text
stringlengths
2
100k
meta
dict
package coop.rchain.casper.helper import java.nio.ByteBuffer import java.nio.file.{Files, Path} import java.util.zip.CRC32 import cats.effect.{Concurrent, Resource, Sync} import cats.syntax.functor._ import com.google.protobuf.ByteString import coop.rchain.blockstorage._ import coop.rchain.blockstorage.dag.{ BlockDagKeyValueStorage, BlockDagStorage, IndexedBlockDagStorage } import coop.rchain.casper.protocol.BlockMessage import coop.rchain.casper.storage.RNodeKeyValueStoreManager import coop.rchain.casper.util.GenesisBuilder.GenesisContext import coop.rchain.casper.util.rholang.{Resources, RuntimeManager} import coop.rchain.catscontrib.TaskContrib.TaskOps import coop.rchain.metrics.Metrics import coop.rchain.metrics.Metrics.MetricsNOP import coop.rchain.models.Validator.Validator import coop.rchain.rspace.Context import coop.rchain.shared.Log import coop.rchain.shared.PathOps.RichPath import monix.eval.Task import monix.execution.Scheduler import org.lmdbjava.{Env, EnvFlags} import org.lmdbjava.ByteBufferProxy.PROXY_SAFE import org.scalatest.{BeforeAndAfter, Suite} trait BlockDagStorageFixture extends BeforeAndAfter { self: Suite => val scheduler = Scheduler.fixedPool("block-dag-storage-fixture-scheduler", 4) def withGenesis[R]( context: GenesisContext )(f: BlockStore[Task] => IndexedBlockDagStorage[Task] => RuntimeManager[Task] => Task[R]): R = { implicit val s = scheduler implicit val metrics = new MetricsNOP[Task]() implicit val log = Log.log[Task] val resource = for { paths <- Resources.copyStorage[Task](context.storageDirectory) blockStore <- Resources.mkBlockStoreAt[Task](paths.blockStoreDir) storeManager <- Resource.liftF(RNodeKeyValueStoreManager[Task](paths.blockDagDir)) blockDagStorage <- Resource.liftF({ implicit val kvm = storeManager BlockDagKeyValueStorage.create[Task] }) indexedBlockDagStorage <- Resource.liftF(IndexedBlockDagStorage.create[Task](blockDagStorage)) runtime <- Resources.mkRuntimeManagerAt[Task](paths.rspaceDir)() } yield (blockStore, indexedBlockDagStorage, runtime) resource.use[R] { case (b, d, r) => f(b)(d)(r) }.unsafeRunSync } def withStorage[R](f: BlockStore[Task] => IndexedBlockDagStorage[Task] => Task[R]): R = { val testProgram = Sync[Task].bracket { Sync[Task].delay { (BlockDagStorageTestFixture.blockDagStorageDir, BlockDagStorageTestFixture.blockStorageDir) } } { case (blockDagStorageDir, blockStorageDir) => implicit val metrics = new MetricsNOP[Task]() implicit val log = Log.log[Task] for { blockStore <- BlockDagStorageTestFixture.createBlockStorage[Task](blockStorageDir) blockDagStorage <- BlockDagStorageTestFixture.createBlockDagStorage(blockDagStorageDir) indexedBlockDagStorage <- IndexedBlockDagStorage.create(blockDagStorage) result <- f(blockStore)(indexedBlockDagStorage) } yield result } { case (blockDagStorageDir, blockStorageDir) => Sync[Task].delay { blockDagStorageDir.recursivelyDelete() blockStorageDir.recursivelyDelete() } } testProgram.unsafeRunSync(scheduler) } } object BlockDagStorageTestFixture { def blockDagStorageDir: Path = Files.createTempDirectory("casper-block-dag-storage-test-") def blockStorageDir: Path = Files.createTempDirectory("casper-block-storage-test-") def writeInitialLatestMessages( latestMessagesData: Path, latestMessagesCrc: Path, latestMessages: Map[Validator, BlockMessage] ): Unit = { val data = latestMessages .foldLeft(ByteString.EMPTY) { case (byteString, (validator, block)) => byteString.concat(validator).concat(block.blockHash) } .toByteArray val crc = new CRC32() latestMessages.foreach { case (validator, block) => crc.update(validator.concat(block.blockHash).toByteArray) } val crcByteBuffer = ByteBuffer.allocate(8) crcByteBuffer.putLong(crc.getValue) Files.write(latestMessagesData, data) Files.write(latestMessagesCrc, crcByteBuffer.array()) } def env( path: Path, mapSize: Long, flags: List[EnvFlags] = List(EnvFlags.MDB_NOTLS) ): Env[ByteBuffer] = Env .create(PROXY_SAFE) .setMapSize(mapSize) .setMaxDbs(8) .setMaxReaders(126) .open(path.toFile, flags: _*) val mapSize: Long = 1024L * 1024L * 1024L def createBlockStorage[F[_]: Concurrent: Metrics: Sync: Log]( blockStorageDir: Path ): F[BlockStore[F]] = { val env = Context.env(blockStorageDir, mapSize) FileLMDBIndexBlockStore.create[F](env, blockStorageDir).map(_.right.get) } def createBlockDagStorage(blockDagStorageDir: Path)( implicit log: Log[Task], metrics: Metrics[Task] ): Task[BlockDagStorage[Task]] = for { storeManager <- RNodeKeyValueStoreManager[Task](blockDagStorageDir) blockDagStorage <- { implicit val kvm = storeManager BlockDagKeyValueStorage.create[Task] } } yield blockDagStorage def createDirectories[F[_]: Concurrent]: Resource[F, (Path, Path)] = Resource.make[F, (Path, Path)] { Sync[F].delay { ( Files.createTempDirectory("casper-block-storage-test-"), Files.createTempDirectory("casper-block-dag-storage-test-") ) } } { case (blockStoreDir, blockDagDir) => Sync[F].delay { blockStoreDir.recursivelyDelete() blockDagDir.recursivelyDelete() } } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved * * The original version of this source code and documentation * is copyrighted and owned by Taligent, Inc., a wholly-owned * subsidiary of IBM. These materials are provided under terms * of a License Agreement between Taligent and Sun. This technology * is protected by multiple US and International patents. * * This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * */ package java.util; import sun.util.ResourceBundleEnumeration; /** * <code>ListResourceBundle</code> is an abstract subclass of * <code>ResourceBundle</code> that manages resources for a locale * in a convenient and easy to use list. See <code>ResourceBundle</code> for * more information about resource bundles in general. * * <P> * Subclasses must override <code>getContents</code> and provide an array, * where each item in the array is a pair of objects. * The first element of each pair is the key, which must be a * <code>String</code>, and the second element is the value associated with * that key. * * <p> * The following <a id="sample">example</a> shows two members of a resource * bundle family with the base name "MyResources". * "MyResources" is the default member of the bundle family, and * "MyResources_fr" is the French member. * These members are based on <code>ListResourceBundle</code> * (a related <a href="PropertyResourceBundle.html#sample">example</a> shows * how you can add a bundle to this family that's based on a properties file). * The keys in this example are of the form "s1" etc. The actual * keys are entirely up to your choice, so long as they are the same as * the keys you use in your program to retrieve the objects from the bundle. * Keys are case-sensitive. * <blockquote> * <pre> * * public class MyResources extends ListResourceBundle { * protected Object[][] getContents() { * return new Object[][] { * // LOCALIZE THIS * {"s1", "The disk \"{1}\" contains {0}."}, // MessageFormat pattern * {"s2", "1"}, // location of {0} in pattern * {"s3", "My Disk"}, // sample disk name * {"s4", "no files"}, // first ChoiceFormat choice * {"s5", "one file"}, // second ChoiceFormat choice * {"s6", "{0,number} files"}, // third ChoiceFormat choice * {"s7", "3 Mar 96"}, // sample date * {"s8", new Dimension(1,5)} // real object, not just string * // END OF MATERIAL TO LOCALIZE * }; * } * } * * public class MyResources_fr extends ListResourceBundle { * protected Object[][] getContents() { * return new Object[][] { * // LOCALIZE THIS * {"s1", "Le disque \"{1}\" {0}."}, // MessageFormat pattern * {"s2", "1"}, // location of {0} in pattern * {"s3", "Mon disque"}, // sample disk name * {"s4", "ne contient pas de fichiers"}, // first ChoiceFormat choice * {"s5", "contient un fichier"}, // second ChoiceFormat choice * {"s6", "contient {0,number} fichiers"}, // third ChoiceFormat choice * {"s7", "3 mars 1996"}, // sample date * {"s8", new Dimension(1,3)} // real object, not just string * // END OF MATERIAL TO LOCALIZE * }; * } * } * </pre> * </blockquote> * * <p> * The implementation of a {@code ListResourceBundle} subclass must be thread-safe * if it's simultaneously used by multiple threads. The default implementations * of the methods in this class are thread-safe. * * @see ResourceBundle * @see PropertyResourceBundle * @since 1.1 */ public abstract class ListResourceBundle extends ResourceBundle { /** * Sole constructor. (For invocation by subclass constructors, typically * implicit.) */ public ListResourceBundle() { } // Implements java.util.ResourceBundle.handleGetObject; inherits javadoc specification. public final Object handleGetObject(String key) { // lazily load the lookup hashtable. if (lookup == null) { loadLookup(); } if (key == null) { throw new NullPointerException(); } return lookup.get(key); // this class ignores locales } /** * Returns an <code>Enumeration</code> of the keys contained in * this <code>ResourceBundle</code> and its parent bundles. * * @return an <code>Enumeration</code> of the keys contained in * this <code>ResourceBundle</code> and its parent bundles. * @see #keySet() */ public Enumeration<String> getKeys() { // lazily load the lookup hashtable. if (lookup == null) { loadLookup(); } ResourceBundle parent = this.parent; return new ResourceBundleEnumeration(lookup.keySet(), (parent != null) ? parent.getKeys() : null); } /** * Returns a <code>Set</code> of the keys contained * <em>only</em> in this <code>ResourceBundle</code>. * * @return a <code>Set</code> of the keys contained only in this * <code>ResourceBundle</code> * @since 1.6 * @see #keySet() */ protected Set<String> handleKeySet() { if (lookup == null) { loadLookup(); } return lookup.keySet(); } /** * Returns an array in which each item is a pair of objects in an * <code>Object</code> array. The first element of each pair is * the key, which must be a <code>String</code>, and the second * element is the value associated with that key. See the class * description for details. * * @return an array of an <code>Object</code> array representing a * key-value pair. */ protected abstract Object[][] getContents(); // ==================privates==================== /** * We lazily load the lookup hashtable. This function does the * loading. */ private synchronized void loadLookup() { if (lookup != null) return; Object[][] contents = getContents(); HashMap<String,Object> temp = new HashMap<>(contents.length); for (Object[] content : contents) { // key must be non-null String, value must be non-null String key = (String) content[0]; Object value = content[1]; if (key == null || value == null) { throw new NullPointerException(); } temp.put(key, value); } lookup = temp; } private volatile Map<String,Object> lookup = null; }
{ "pile_set_name": "Github" }
# SPDX-License-Identifier: GPL-2.0+ # Copyright (c) 2016 Google, Inc # Written by Simon Glass <[email protected]> # # Entry-type module for 'u-boot-nodtb.bin' # from entry import Entry from blob import Entry_blob class Entry_u_boot_spl_nodtb(Entry_blob): """SPL binary without device tree appended Properties / Entry arguments: - filename: Filename of spl/u-boot-spl-nodtb.bin (default 'spl/u-boot-spl-nodtb.bin') This is the U-Boot SPL binary, It does not include a device tree blob at the end of it so may not be able to work without it, assuming SPL needs a device tree to operation on your platform. You can add a u_boot_spl_dtb entry after this one, or use a u_boot_spl entry instead (which contains both SPL and the device tree). """ def __init__(self, section, etype, node): Entry_blob.__init__(self, section, etype, node) def GetDefaultFilename(self): return 'spl/u-boot-spl-nodtb.bin'
{ "pile_set_name": "Github" }
<?php /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** * Class for axis handling. * * PHP versions 4 and 5 * * LICENSE: This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. This library is distributed in the hope that it * will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. You should have received a copy of * the GNU Lesser General Public License along with this library; if not, write * to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA * * @category Images * @package Image_Graph * @subpackage Axis * @author Jesper Veggerby <[email protected]> * @copyright Copyright (C) 2003, 2004 Jesper Veggerby Hansen * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 * @version CVS: $Id: Category.php,v 1.19 2006/03/02 12:15:17 nosey Exp $ * @link http://pear.php.net/package/Image_Graph */ /** * Include file Image/Graph/Axis.php */ require_once 'Image/Graph/Axis.php'; /** * A normal axis thats displays labels with a 'interval' of 1. * This is basically a normal axis where the range is * the number of labels defined, that is the range is explicitly defined * when constructing the axis. * * @category Images * @package Image_Graph * @subpackage Axis * @author Jesper Veggerby <[email protected]> * @copyright Copyright (C) 2003, 2004 Jesper Veggerby Hansen * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 * @version Release: @package_version@ * @link http://pear.php.net/package/Image_Graph */ class Image_Graph_Axis_Category extends Image_Graph_Axis { /** * The labels shown on the axis * @var array * @access private */ var $_labels = false; /** * Image_Graph_Axis_Category [Constructor]. * * @param int $type The type (direction) of the Axis */ function Image_Graph_Axis_Category($type = IMAGE_GRAPH_AXIS_X) { parent::Image_Graph_Axis($type); $this->_labels = array(); $this->setlabelInterval(1); } /** * Gets the minimum value the axis will show. * * This is always 0 * * @return double The minumum value * @access private */ function _getMinimum() { return 0; } /** * Gets the maximum value the axis will show. * * This is always the number of labels passed to the constructor. * * @return double The maximum value * @access private */ function _getMaximum() { return count($this->_labels) - 1; } /** * Sets the minimum value the axis will show. * * A minimum cannot be set on a SequentialAxis, it is always 0. * * @param double Minimum The minumum value to use on the axis * @access private */ function _setMinimum($minimum) { } /** * Sets the maximum value the axis will show * * A maximum cannot be set on a SequentialAxis, it is always the number * of labels passed to the constructor. * * @param double Maximum The maximum value to use on the axis * @access private */ function _setMaximum($maximum) { } /** * Forces the minimum value of the axis * * <b>A minimum cannot be set on this type of axis</b> * * To modify the labels which are displayed on the axis, instead use * setLabelInterval($labels) where $labels is an array containing the * values/labels the axis should display. <b>Note!</b> Only values in * this array will then be displayed on the graph! * * @param double $minimum A minimum cannot be set on this type of axis */ function forceMinimum($minimum, $userEnforce = true) { } /** * Forces the maximum value of the axis * * <b>A maximum cannot be set on this type of axis</b> * * To modify the labels which are displayed on the axis, instead use * setLabelInterval($labels) where $labels is an array containing the * values/labels the axis should display. <b>Note!</b> Only values in * this array will then be displayed on the graph! * * @param double $maximum A maximum cannot be set on this type of axis */ function forceMaximum($maximum, $userEnforce = true) { } /** * Sets an interval for where labels are shown on the axis. * * The label interval is rounded to nearest integer value. * * @param double $labelInterval The interval with which labels are shown */ function setLabelInterval($labelInterval = 'auto', $level = 1) { if (is_array($labelInterval)) { parent::setLabelInterval($labelInterval); } elseif ($labelInterval == 'auto') { parent::setLabelInterval(1); } else { parent::setLabelInterval(round($labelInterval)); } } /** * Preprocessor for values, ie for using logarithmic axis * * @param double $value The value to preprocess * @return double The preprocessed value * @access private */ function _value($value) { // $the_value = array_search($value, $this->_labels); if (isset($this->_labels[$value])) { $the_value = $this->_labels[$value]; if ($the_value !== false) { return $the_value + ($this->_pushValues ? 0.5 : 0); } else { return 0; } } } /** * Get the minor label interval with which axis label ticks are drawn. * * For a sequential axis this is always disabled (i.e false) * * @return double The minor label interval, always false * @access private */ function _minorLabelInterval() { return false; } /** * Get the size in pixels of the axis. * * For an x-axis this is the width of the axis including labels, and for an * y-axis it is the corrresponding height * * @return int The size of the axis * @access private */ function _size() { if (!$this->_visible) { return 0; } $this->_canvas->setFont($this->_getFont()); $maxSize = 0; foreach($this->_labels as $label => $id) { $labelPosition = $this->_point($label); if (is_object($this->_dataPreProcessor)) { $labelText = $this->_dataPreProcessor->_process($label); } else { $labelText = $label; } if ((($this->_type == IMAGE_GRAPH_AXIS_X) && (!$this->_transpose)) || (($this->_type != IMAGE_GRAPH_AXIS_X) && ($this->_transpose))) { $maxSize = max($maxSize, $this->_canvas->textHeight($labelText)); } else { $maxSize = max($maxSize, $this->_canvas->textWidth($labelText)); } } if ($this->_title) { $this->_canvas->setFont($this->_getTitleFont()); if ((($this->_type == IMAGE_GRAPH_AXIS_X) && (!$this->_transpose)) || (($this->_type != IMAGE_GRAPH_AXIS_X) && ($this->_transpose))) { $maxSize += $this->_canvas->textHeight($this->_title); } else { $maxSize += $this->_canvas->textWidth($this->_title); } $maxSize += 10; } return $maxSize +3; } /** * Apply the dataset to the axis. * * This calculates the order of the categories, which is very important * for fx. line plots, so that the line does not "go backwards", consider * these X-sets:<p> * 1: (1, 2, 3, 4, 5, 6)<br> * 2: (0, 1, 2, 3, 4, 5, 6, 7)<p> * If they are not ordered, but simply appended, the categories on the axis * would be:<p> * X: (1, 2, 3, 4, 5, 6, 0, 7)<p> * Which would render the a line for the second plot to show incorrectly. * Instead this algorithm, uses and 'value- is- before' method to see that * the 0 is before a 1 in the second set, and that it should also be before * a 1 in the X set. Hence:<p> * X: (0, 1, 2, 3, 4, 5, 6, 7) * * @param Image_Graph_Dataset $dataset The dataset * @access private */ function _applyDataset(&$dataset) { $newLabels = array(); $allLabels = array(); $dataset->_reset(); $count = 0; $count_new = 0; while ($point = $dataset->_next()) { if ($this->_type == IMAGE_GRAPH_AXIS_X) { $data = $point['X']; } else { $data = $point['Y']; } if (!isset($this->_labels[$data])) { $newLabels[$data] = $count_new++; //$this->_labels[] = $data; } $allLabels[$data] = $count++; } if (count($this->_labels) == 0) { $this->_labels = $newLabels; } elseif ((is_array($newLabels)) && (count($newLabels) > 0)) { // get all intersecting labels $intersect = array_intersect(array_keys($allLabels), array_keys($this->_labels)); // traverse all new and find their relative position withing the // intersec, fx value X0 is before X1 in the intersection, which // means that X0 should be placed before X1 in the label array foreach($newLabels as $newLabel => $id) { $key = $allLabels[$newLabel]; reset($intersect); $this_value = false; // intersect indexes are the same as in allLabels! $first = true; while ((list($id, $value) = each($intersect)) && ($this_value === false)) { if (($first) && ($id > $key)) { $this_value = $value; } elseif ($id >= $key) { $this_value = $value; } $first = false; } if ($this_value === false) { // the new label was not found before anything in the // intersection -> append it $this->_labels[$newLabel] = count($this->_labels); } else { // the new label was found before $this_value in the // intersection, insert the label before this position in // the label array // $key = $this->_labels[$this_value]; $keys = array_keys($this->_labels); $key = array_search($this_value, $keys); $pre = array_slice($keys, 0, $key); $pre[] = $newLabel; $post = array_slice($keys, $key); $this->_labels = array_flip(array_merge($pre, $post)); } } unset($keys); } $labels = array_keys($this->_labels); $i = 0; foreach ($labels as $label) { $this->_labels[$label] = $i++; } // $this->_labels = array_values(array_unique($this->_labels)); $this->_calcLabelInterval(); } /** * Return the label distance. * * @return int The distance between 2 adjacent labels * @access private */ function _labelDistance($level = 1) { reset($this->_labels); list($l1) = each($this->_labels); list($l2) = each($this->_labels); return abs($this->_point($l2) - $this->_point($l1)); } /** * Get next label point * * @param doubt $point The current point, if omitted or false, the first is * returned * @return double The next label point * @access private */ function _getNextLabel($currentLabel = false, $level = 1) { if ($currentLabel === false) { reset($this->_labels); } $result = false; $count = ($currentLabel === false ? $this->_labelInterval() - 1 : 0); while ($count < $this->_labelInterval()) { $result = (list($label) = each($this->_labels)); $count++; } if ($result) { return $label; } else { return false; } } /** * Is the axis numeric or not? * * @return bool True if numeric, false if not * @access private */ function _isNumeric() { return false; } /** * Output the axis * * @return bool Was the output 'good' (true) or 'bad' (false). * @access private */ function _done() { $result = true; if (Image_Graph_Element::_done() === false) { $result = false; } $this->_canvas->startGroup(get_class($this)); $this->_drawAxisLines(); $this->_canvas->startGroup(get_class($this) . '_ticks'); $label = false; while (($label = $this->_getNextLabel($label)) !== false) { $this->_drawTick($label); } $this->_canvas->endGroup(); $this->_canvas->endGroup(); return $result; } } ?>
{ "pile_set_name": "Github" }
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2019-Present Datadog, Inc. */ // Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. package datadog import ( "encoding/json" ) // HostMapWidgetDefinition The host map widget graphs any metric across your hosts using the same visualization available from the main Host Map page. type HostMapWidgetDefinition struct { // List of tag prefixes to group by. Group *[]string `json:"group,omitempty"` // Whether to show the hosts that don’t fit in a group. NoGroupHosts *bool `json:"no_group_hosts,omitempty"` // Whether to show the hosts with no metrics. NoMetricHosts *bool `json:"no_metric_hosts,omitempty"` NodeType *WidgetNodeType `json:"node_type,omitempty"` // Notes on the title. Notes *string `json:"notes,omitempty"` Requests HostMapWidgetDefinitionRequests `json:"requests"` // List of tags used to filter the map. Scope *[]string `json:"scope,omitempty"` Style *HostMapWidgetDefinitionStyle `json:"style,omitempty"` // Title of the widget. Title *string `json:"title,omitempty"` TitleAlign *WidgetTextAlign `json:"title_align,omitempty"` // Size of the title. TitleSize *string `json:"title_size,omitempty"` Type HostMapWidgetDefinitionType `json:"type"` } // NewHostMapWidgetDefinition instantiates a new HostMapWidgetDefinition object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewHostMapWidgetDefinition(requests HostMapWidgetDefinitionRequests, type_ HostMapWidgetDefinitionType) *HostMapWidgetDefinition { this := HostMapWidgetDefinition{} this.Requests = requests this.Type = type_ return &this } // NewHostMapWidgetDefinitionWithDefaults instantiates a new HostMapWidgetDefinition object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewHostMapWidgetDefinitionWithDefaults() *HostMapWidgetDefinition { this := HostMapWidgetDefinition{} var type_ HostMapWidgetDefinitionType = "hostmap" this.Type = type_ return &this } // GetGroup returns the Group field value if set, zero value otherwise. func (o *HostMapWidgetDefinition) GetGroup() []string { if o == nil || o.Group == nil { var ret []string return ret } return *o.Group } // GetGroupOk returns a tuple with the Group field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *HostMapWidgetDefinition) GetGroupOk() (*[]string, bool) { if o == nil || o.Group == nil { return nil, false } return o.Group, true } // HasGroup returns a boolean if a field has been set. func (o *HostMapWidgetDefinition) HasGroup() bool { if o != nil && o.Group != nil { return true } return false } // SetGroup gets a reference to the given []string and assigns it to the Group field. func (o *HostMapWidgetDefinition) SetGroup(v []string) { o.Group = &v } // GetNoGroupHosts returns the NoGroupHosts field value if set, zero value otherwise. func (o *HostMapWidgetDefinition) GetNoGroupHosts() bool { if o == nil || o.NoGroupHosts == nil { var ret bool return ret } return *o.NoGroupHosts } // GetNoGroupHostsOk returns a tuple with the NoGroupHosts field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *HostMapWidgetDefinition) GetNoGroupHostsOk() (*bool, bool) { if o == nil || o.NoGroupHosts == nil { return nil, false } return o.NoGroupHosts, true } // HasNoGroupHosts returns a boolean if a field has been set. func (o *HostMapWidgetDefinition) HasNoGroupHosts() bool { if o != nil && o.NoGroupHosts != nil { return true } return false } // SetNoGroupHosts gets a reference to the given bool and assigns it to the NoGroupHosts field. func (o *HostMapWidgetDefinition) SetNoGroupHosts(v bool) { o.NoGroupHosts = &v } // GetNoMetricHosts returns the NoMetricHosts field value if set, zero value otherwise. func (o *HostMapWidgetDefinition) GetNoMetricHosts() bool { if o == nil || o.NoMetricHosts == nil { var ret bool return ret } return *o.NoMetricHosts } // GetNoMetricHostsOk returns a tuple with the NoMetricHosts field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *HostMapWidgetDefinition) GetNoMetricHostsOk() (*bool, bool) { if o == nil || o.NoMetricHosts == nil { return nil, false } return o.NoMetricHosts, true } // HasNoMetricHosts returns a boolean if a field has been set. func (o *HostMapWidgetDefinition) HasNoMetricHosts() bool { if o != nil && o.NoMetricHosts != nil { return true } return false } // SetNoMetricHosts gets a reference to the given bool and assigns it to the NoMetricHosts field. func (o *HostMapWidgetDefinition) SetNoMetricHosts(v bool) { o.NoMetricHosts = &v } // GetNodeType returns the NodeType field value if set, zero value otherwise. func (o *HostMapWidgetDefinition) GetNodeType() WidgetNodeType { if o == nil || o.NodeType == nil { var ret WidgetNodeType return ret } return *o.NodeType } // GetNodeTypeOk returns a tuple with the NodeType field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *HostMapWidgetDefinition) GetNodeTypeOk() (*WidgetNodeType, bool) { if o == nil || o.NodeType == nil { return nil, false } return o.NodeType, true } // HasNodeType returns a boolean if a field has been set. func (o *HostMapWidgetDefinition) HasNodeType() bool { if o != nil && o.NodeType != nil { return true } return false } // SetNodeType gets a reference to the given WidgetNodeType and assigns it to the NodeType field. func (o *HostMapWidgetDefinition) SetNodeType(v WidgetNodeType) { o.NodeType = &v } // GetNotes returns the Notes field value if set, zero value otherwise. func (o *HostMapWidgetDefinition) GetNotes() string { if o == nil || o.Notes == nil { var ret string return ret } return *o.Notes } // GetNotesOk returns a tuple with the Notes field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *HostMapWidgetDefinition) GetNotesOk() (*string, bool) { if o == nil || o.Notes == nil { return nil, false } return o.Notes, true } // HasNotes returns a boolean if a field has been set. func (o *HostMapWidgetDefinition) HasNotes() bool { if o != nil && o.Notes != nil { return true } return false } // SetNotes gets a reference to the given string and assigns it to the Notes field. func (o *HostMapWidgetDefinition) SetNotes(v string) { o.Notes = &v } // GetRequests returns the Requests field value func (o *HostMapWidgetDefinition) GetRequests() HostMapWidgetDefinitionRequests { if o == nil { var ret HostMapWidgetDefinitionRequests return ret } return o.Requests } // GetRequestsOk returns a tuple with the Requests field value // and a boolean to check if the value has been set. func (o *HostMapWidgetDefinition) GetRequestsOk() (*HostMapWidgetDefinitionRequests, bool) { if o == nil { return nil, false } return &o.Requests, true } // SetRequests sets field value func (o *HostMapWidgetDefinition) SetRequests(v HostMapWidgetDefinitionRequests) { o.Requests = v } // GetScope returns the Scope field value if set, zero value otherwise. func (o *HostMapWidgetDefinition) GetScope() []string { if o == nil || o.Scope == nil { var ret []string return ret } return *o.Scope } // GetScopeOk returns a tuple with the Scope field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *HostMapWidgetDefinition) GetScopeOk() (*[]string, bool) { if o == nil || o.Scope == nil { return nil, false } return o.Scope, true } // HasScope returns a boolean if a field has been set. func (o *HostMapWidgetDefinition) HasScope() bool { if o != nil && o.Scope != nil { return true } return false } // SetScope gets a reference to the given []string and assigns it to the Scope field. func (o *HostMapWidgetDefinition) SetScope(v []string) { o.Scope = &v } // GetStyle returns the Style field value if set, zero value otherwise. func (o *HostMapWidgetDefinition) GetStyle() HostMapWidgetDefinitionStyle { if o == nil || o.Style == nil { var ret HostMapWidgetDefinitionStyle return ret } return *o.Style } // GetStyleOk returns a tuple with the Style field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *HostMapWidgetDefinition) GetStyleOk() (*HostMapWidgetDefinitionStyle, bool) { if o == nil || o.Style == nil { return nil, false } return o.Style, true } // HasStyle returns a boolean if a field has been set. func (o *HostMapWidgetDefinition) HasStyle() bool { if o != nil && o.Style != nil { return true } return false } // SetStyle gets a reference to the given HostMapWidgetDefinitionStyle and assigns it to the Style field. func (o *HostMapWidgetDefinition) SetStyle(v HostMapWidgetDefinitionStyle) { o.Style = &v } // GetTitle returns the Title field value if set, zero value otherwise. func (o *HostMapWidgetDefinition) GetTitle() string { if o == nil || o.Title == nil { var ret string return ret } return *o.Title } // GetTitleOk returns a tuple with the Title field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *HostMapWidgetDefinition) GetTitleOk() (*string, bool) { if o == nil || o.Title == nil { return nil, false } return o.Title, true } // HasTitle returns a boolean if a field has been set. func (o *HostMapWidgetDefinition) HasTitle() bool { if o != nil && o.Title != nil { return true } return false } // SetTitle gets a reference to the given string and assigns it to the Title field. func (o *HostMapWidgetDefinition) SetTitle(v string) { o.Title = &v } // GetTitleAlign returns the TitleAlign field value if set, zero value otherwise. func (o *HostMapWidgetDefinition) GetTitleAlign() WidgetTextAlign { if o == nil || o.TitleAlign == nil { var ret WidgetTextAlign return ret } return *o.TitleAlign } // GetTitleAlignOk returns a tuple with the TitleAlign field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *HostMapWidgetDefinition) GetTitleAlignOk() (*WidgetTextAlign, bool) { if o == nil || o.TitleAlign == nil { return nil, false } return o.TitleAlign, true } // HasTitleAlign returns a boolean if a field has been set. func (o *HostMapWidgetDefinition) HasTitleAlign() bool { if o != nil && o.TitleAlign != nil { return true } return false } // SetTitleAlign gets a reference to the given WidgetTextAlign and assigns it to the TitleAlign field. func (o *HostMapWidgetDefinition) SetTitleAlign(v WidgetTextAlign) { o.TitleAlign = &v } // GetTitleSize returns the TitleSize field value if set, zero value otherwise. func (o *HostMapWidgetDefinition) GetTitleSize() string { if o == nil || o.TitleSize == nil { var ret string return ret } return *o.TitleSize } // GetTitleSizeOk returns a tuple with the TitleSize field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *HostMapWidgetDefinition) GetTitleSizeOk() (*string, bool) { if o == nil || o.TitleSize == nil { return nil, false } return o.TitleSize, true } // HasTitleSize returns a boolean if a field has been set. func (o *HostMapWidgetDefinition) HasTitleSize() bool { if o != nil && o.TitleSize != nil { return true } return false } // SetTitleSize gets a reference to the given string and assigns it to the TitleSize field. func (o *HostMapWidgetDefinition) SetTitleSize(v string) { o.TitleSize = &v } // GetType returns the Type field value func (o *HostMapWidgetDefinition) GetType() HostMapWidgetDefinitionType { if o == nil { var ret HostMapWidgetDefinitionType return ret } return o.Type } // GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. func (o *HostMapWidgetDefinition) GetTypeOk() (*HostMapWidgetDefinitionType, bool) { if o == nil { return nil, false } return &o.Type, true } // SetType sets field value func (o *HostMapWidgetDefinition) SetType(v HostMapWidgetDefinitionType) { o.Type = v } func (o HostMapWidgetDefinition) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Group != nil { toSerialize["group"] = o.Group } if o.NoGroupHosts != nil { toSerialize["no_group_hosts"] = o.NoGroupHosts } if o.NoMetricHosts != nil { toSerialize["no_metric_hosts"] = o.NoMetricHosts } if o.NodeType != nil { toSerialize["node_type"] = o.NodeType } if o.Notes != nil { toSerialize["notes"] = o.Notes } if true { toSerialize["requests"] = o.Requests } if o.Scope != nil { toSerialize["scope"] = o.Scope } if o.Style != nil { toSerialize["style"] = o.Style } if o.Title != nil { toSerialize["title"] = o.Title } if o.TitleAlign != nil { toSerialize["title_align"] = o.TitleAlign } if o.TitleSize != nil { toSerialize["title_size"] = o.TitleSize } if true { toSerialize["type"] = o.Type } return json.Marshal(toSerialize) } type NullableHostMapWidgetDefinition struct { value *HostMapWidgetDefinition isSet bool } func (v NullableHostMapWidgetDefinition) Get() *HostMapWidgetDefinition { return v.value } func (v *NullableHostMapWidgetDefinition) Set(val *HostMapWidgetDefinition) { v.value = val v.isSet = true } func (v NullableHostMapWidgetDefinition) IsSet() bool { return v.isSet } func (v *NullableHostMapWidgetDefinition) Unset() { v.value = nil v.isSet = false } func NewNullableHostMapWidgetDefinition(val *HostMapWidgetDefinition) *NullableHostMapWidgetDefinition { return &NullableHostMapWidgetDefinition{value: val, isSet: true} } func (v NullableHostMapWidgetDefinition) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableHostMapWidgetDefinition) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <reTestXmlDataContainer xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" reTestVersion="1.11.2" dataType="de.retest.recheck.ui.descriptors.SutState" dataTypeVersion="4"> <data xsi:type="sutState"> <descriptors retestId="html" screenId="1" screen="AutoHealingTest" title="AutoHealingTest"> <identifyingAttributes> <attributes> <attribute key="absolute-outline" xsi:type="outlineAttribute"> <x>0</x> <y>0</y> <height>37</height> <width>1200</width> </attribute> <attribute key="outline" xsi:type="outlineAttribute"> <x>0</x> <y>0</y> <height>37</height> <width>1200</width> </attribute> <attribute key="path" xsi:type="pathAttribute">html[1]</attribute> <attribute key="suffix" xsi:type="suffixAttribute">1</attribute> <attribute key="type" xsi:type="stringAttribute">html</attribute> </attributes> </identifyingAttributes> <attributes> <attributes> <entry> <key>lang</key> <value xsi:type="xsd:string">en</value> </entry> <entry> <key>shown</key> <value xsi:type="xsd:string">true</value> </entry> </attributes> </attributes> <containedElements retestId="head"> <identifyingAttributes> <attributes> <attribute key="absolute-outline" xsi:type="outlineAttribute"> <x>0</x> <y>0</y> <height>0</height> <width>0</width> </attribute> <attribute key="outline" xsi:type="outlineAttribute"> <x>0</x> <y>0</y> <height>-37</height> <width>-1200</width> </attribute> <attribute key="path" xsi:type="pathAttribute">html[1]/head[1]</attribute> <attribute key="suffix" xsi:type="suffixAttribute">1</attribute> <attribute key="type" xsi:type="stringAttribute">head</attribute> </attributes> </identifyingAttributes> <attributes> <attributes> <entry> <key>shown</key> <value xsi:type="xsd:string">false</value> </entry> </attributes> </attributes> <containedElements retestId="autohealingtest"> <identifyingAttributes> <attributes> <attribute key="absolute-outline" xsi:type="outlineAttribute"> <x>0</x> <y>0</y> <height>0</height> <width>0</width> </attribute> <attribute key="outline" xsi:type="outlineAttribute"> <x>0</x> <y>0</y> <height>0</height> <width>0</width> </attribute> <attribute key="path" xsi:type="pathAttribute">html[1]/head[1]/title[1]</attribute> <attribute key="suffix" xsi:type="suffixAttribute">1</attribute> <attribute key="text" xsi:type="textAttribute">AutoHealingTest</attribute> <attribute key="type" xsi:type="stringAttribute">title</attribute> </attributes> </identifyingAttributes> <attributes> <attributes> <entry> <key>shown</key> <value xsi:type="xsd:string">false</value> </entry> </attributes> </attributes> </containedElements> <containedElements retestId="meta"> <identifyingAttributes> <attributes> <attribute key="absolute-outline" xsi:type="outlineAttribute"> <x>0</x> <y>0</y> <height>0</height> <width>0</width> </attribute> <attribute key="outline" xsi:type="outlineAttribute"> <x>0</x> <y>0</y> <height>0</height> <width>0</width> </attribute> <attribute key="path" xsi:type="pathAttribute">html[1]/head[1]/meta[1]</attribute> <attribute key="suffix" xsi:type="suffixAttribute">1</attribute> <attribute key="type" xsi:type="stringAttribute">meta</attribute> </attributes> </identifyingAttributes> <attributes> <attributes> <entry> <key>charset</key> <value xsi:type="xsd:string">UTF-8</value> </entry> <entry> <key>shown</key> <value xsi:type="xsd:string">false</value> </entry> </attributes> </attributes> </containedElements> <containedElements retestId="meta-1"> <identifyingAttributes> <attributes> <attribute key="absolute-outline" xsi:type="outlineAttribute"> <x>0</x> <y>0</y> <height>0</height> <width>0</width> </attribute> <attribute key="name" xsi:type="stringAttribute">viewport</attribute> <attribute key="outline" xsi:type="outlineAttribute"> <x>0</x> <y>0</y> <height>0</height> <width>0</width> </attribute> <attribute key="path" xsi:type="pathAttribute">html[1]/head[1]/meta[2]</attribute> <attribute key="suffix" xsi:type="suffixAttribute">2</attribute> <attribute key="type" xsi:type="stringAttribute">meta</attribute> </attributes> </identifyingAttributes> <attributes> <attributes> <entry> <key>content</key> <value xsi:type="xsd:string">width=device-width, initial-scale=1.0</value> </entry> <entry> <key>shown</key> <value xsi:type="xsd:string">false</value> </entry> </attributes> </attributes> </containedElements> <containedElements retestId="meta-2"> <identifyingAttributes> <attributes> <attribute key="absolute-outline" xsi:type="outlineAttribute"> <x>0</x> <y>0</y> <height>0</height> <width>0</width> </attribute> <attribute key="outline" xsi:type="outlineAttribute"> <x>0</x> <y>0</y> <height>0</height> <width>0</width> </attribute> <attribute key="path" xsi:type="pathAttribute">html[1]/head[1]/meta[3]</attribute> <attribute key="suffix" xsi:type="suffixAttribute">3</attribute> <attribute key="type" xsi:type="stringAttribute">meta</attribute> </attributes> </identifyingAttributes> <attributes> <attributes> <entry> <key>content</key> <value xsi:type="xsd:string">ie=edge</value> </entry> <entry> <key>http-equiv</key> <value xsi:type="xsd:string">X-UA-Compatible</value> </entry> <entry> <key>shown</key> <value xsi:type="xsd:string">false</value> </entry> </attributes> </attributes> </containedElements> </containedElements> <containedElements retestId="body"> <identifyingAttributes> <attributes> <attribute key="absolute-outline" xsi:type="outlineAttribute"> <x>8</x> <y>8</y> <height>21</height> <width>1184</width> </attribute> <attribute key="outline" xsi:type="outlineAttribute"> <x>8</x> <y>8</y> <height>-16</height> <width>-16</width> </attribute> <attribute key="path" xsi:type="pathAttribute">html[1]/body[1]</attribute> <attribute key="suffix" xsi:type="suffixAttribute">1</attribute> <attribute key="type" xsi:type="stringAttribute">body</attribute> </attributes> </identifyingAttributes> <attributes> <attributes> <entry> <key>shown</key> <value xsi:type="xsd:string">true</value> </entry> </attributes> </attributes> <containedElements retestId="id"> <identifyingAttributes> <attributes> <attribute key="absolute-outline" xsi:type="outlineAttribute"> <x>123</x> <y>8</y> <height>21</height> <width>173</width> </attribute> <attribute key="id" xsi:type="stringAttribute">id</attribute> <attribute key="outline" xsi:type="outlineAttribute"> <x>115</x> <y>0</y> <height>0</height> <width>-1011</width> </attribute> <attribute key="path" xsi:type="pathAttribute">html[1]/body[1]/input[1]</attribute> <attribute key="suffix" xsi:type="suffixAttribute">1</attribute> <attribute key="type" xsi:type="stringAttribute">input</attribute> </attributes> </identifyingAttributes> <attributes> <attributes> <entry> <key>background-color</key> <value xsi:type="xsd:string">rgb(255, 255, 255)</value> </entry> <entry> <key>border-bottom-style</key> <value xsi:type="xsd:string">inset</value> </entry> <entry> <key>border-bottom-width</key> <value xsi:type="xsd:string">2px</value> </entry> <entry> <key>border-left-style</key> <value xsi:type="xsd:string">inset</value> </entry> <entry> <key>border-left-width</key> <value xsi:type="xsd:string">2px</value> </entry> <entry> <key>border-right-style</key> <value xsi:type="xsd:string">inset</value> </entry> <entry> <key>border-right-width</key> <value xsi:type="xsd:string">2px</value> </entry> <entry> <key>border-top-style</key> <value xsi:type="xsd:string">inset</value> </entry> <entry> <key>border-top-width</key> <value xsi:type="xsd:string">2px</value> </entry> <entry> <key>font-family</key> <value xsi:type="xsd:string">Arial</value> </entry> <entry> <key>font-size</key> <value xsi:type="xsd:string">13.3333px</value> </entry> <entry> <key>margin-bottom</key> <value xsi:type="xsd:string">0px</value> </entry> <entry> <key>margin-top</key> <value xsi:type="xsd:string">0px</value> </entry> <entry> <key>padding-bottom</key> <value xsi:type="xsd:string">1px</value> </entry> <entry> <key>padding-top</key> <value xsi:type="xsd:string">1px</value> </entry> <entry> <key>read-only</key> <value xsi:type="xsd:string">true</value> </entry> <entry> <key>shown</key> <value xsi:type="xsd:string">true</value> </entry> <entry> <key>type</key> <value xsi:type="xsd:string">text</value> </entry> <entry> <key>value</key> <value xsi:type="xsd:string">a</value> </entry> </attributes> </attributes> </containedElements> <containedElements retestId="a"> <identifyingAttributes> <attributes> <attribute key="absolute-outline" xsi:type="outlineAttribute"> <x>8</x> <y>8</y> <height>21</height> <width>111</width> </attribute> <attribute key="id" xsi:type="stringAttribute">a</attribute> <attribute key="outline" xsi:type="outlineAttribute"> <x>0</x> <y>0</y> <height>0</height> <width>-1073</width> </attribute> <attribute key="path" xsi:type="pathAttribute">html[1]/body[1]/button[1]</attribute> <attribute key="suffix" xsi:type="suffixAttribute">1</attribute> <attribute key="text" xsi:type="textAttribute">Click to change!</attribute> <attribute key="type" xsi:type="stringAttribute">button</attribute> </attributes> </identifyingAttributes> <attributes> <attributes> <entry> <key>align-items</key> <value xsi:type="xsd:string">flex-start</value> </entry> <entry> <key>background-color</key> <value xsi:type="xsd:string">rgb(221, 221, 221)</value> </entry> <entry> <key>border-bottom-color</key> <value xsi:type="xsd:string">rgb(221, 221, 221)</value> </entry> <entry> <key>border-bottom-style</key> <value xsi:type="xsd:string">outset</value> </entry> <entry> <key>border-bottom-width</key> <value xsi:type="xsd:string">2px</value> </entry> <entry> <key>border-left-color</key> <value xsi:type="xsd:string">rgb(221, 221, 221)</value> </entry> <entry> <key>border-left-style</key> <value xsi:type="xsd:string">outset</value> </entry> <entry> <key>border-left-width</key> <value xsi:type="xsd:string">2px</value> </entry> <entry> <key>border-right-color</key> <value xsi:type="xsd:string">rgb(221, 221, 221)</value> </entry> <entry> <key>border-right-style</key> <value xsi:type="xsd:string">outset</value> </entry> <entry> <key>border-right-width</key> <value xsi:type="xsd:string">2px</value> </entry> <entry> <key>border-top-color</key> <value xsi:type="xsd:string">rgb(221, 221, 221)</value> </entry> <entry> <key>border-top-style</key> <value xsi:type="xsd:string">outset</value> </entry> <entry> <key>border-top-width</key> <value xsi:type="xsd:string">2px</value> </entry> <entry> <key>box-sizing</key> <value xsi:type="xsd:string">border-box</value> </entry> <entry> <key>display</key> <value xsi:type="xsd:string">inline-block</value> </entry> <entry> <key>font-family</key> <value xsi:type="xsd:string">Arial</value> </entry> <entry> <key>font-size</key> <value xsi:type="xsd:string">13.3333px</value> </entry> <entry> <key>padding-bottom</key> <value xsi:type="xsd:string">1px</value> </entry> <entry> <key>padding-left</key> <value xsi:type="xsd:string">6px</value> </entry> <entry> <key>padding-right</key> <value xsi:type="xsd:string">6px</value> </entry> <entry> <key>padding-top</key> <value xsi:type="xsd:string">1px</value> </entry> <entry> <key>read-only</key> </entry> <entry> <key>shown</key> <value xsi:type="xsd:string">true</value> </entry> <entry> <key>text-align</key> <value xsi:type="xsd:string">center</value> </entry> </attributes> </attributes> </containedElements> </containedElements> </descriptors> <metadata> <entry> <key>driver.type</key> <value>UnbreakableDriver</value> </entry> <entry> <key>time.offset</key> <value>+01:00</value> </entry> <entry> <key>os.arch</key> <value>amd64</value> </entry> <entry> <key>check.type</key> <value>driver</value> </entry> <entry> <key>vcs.commit</key> <value>133270c5c2878a8275304a840baec0004fb0a2fb</value> </entry> <entry> <key>window.height</key> <value>800</value> </entry> <entry> <key>vcs.branch</key> <value>feature/RET-1917-implement-warning-creation</value> </entry> <entry> <key>url</key> <value>file:///C:/Users/diehl/Documents/Work/Repo/Company/open/recheck-web/target/test-classes/de/retest/web/AutoHealingTest.html</value> </entry> <entry> <key>machine.name</key> <value>PC-BASTIAN</value> </entry> <entry> <key>os.version</key> <value>10.0</value> </entry> <entry> <key>browser.name</key> <value>chrome</value> </entry> <entry> <key>browser.version</key> <value>79.0.3945.117</value> </entry> <entry> <key>time.time</key> <value>15:39:16.33</value> </entry> <entry> <key>time.zone</key> <value>Europe/Berlin</value> </entry> <entry> <key>window.width</key> <value>1200</value> </entry> <entry> <key>os.name</key> <value>XP</value> </entry> <entry> <key>time.date</key> <value>2020-01-08</value> </entry> <entry> <key>vcs.name</key> <value>git</value> </entry> </metadata> </data> </reTestXmlDataContainer>
{ "pile_set_name": "Github" }
import { delegatesAdded } from '../../actions/voting'; import actionTypes from '../../constants/actions'; const votingMiddleware = store => next => (action) => { next(action); switch (action.type) { case actionTypes.accountLoggedOut: store.dispatch(delegatesAdded({ list: [] })); store.dispatch({ type: actionTypes.votesAdded, data: { list: [] }, }); break; default: break; } }; export default votingMiddleware;
{ "pile_set_name": "Github" }
package docs.directives import spray.http.StatusCodes.OK import spray.http.HttpHeaders.Host class HostDirectivesExamplesSpec extends DirectivesSpec { "extract-hostname" in { val route = hostName { hn => complete(s"Hostname: $hn") } Get() ~> Host("company.com", 9090) ~> route ~> check { status === OK responseAs[String] === "Hostname: company.com" } } "list-of-hosts" in { val route = host("api.company.com", "rest.company.com") { complete("Ok") } Get() ~> Host("rest.company.com") ~> route ~> check { status === OK responseAs[String] === "Ok" } Get() ~> Host("notallowed.company.com") ~> route ~> check { handled must beFalse } } "predicate" in { val shortOnly: String => Boolean = (hostname) => hostname.length < 10 val route = host(shortOnly) { complete("Ok") } Get() ~> Host("short.com") ~> route ~> check { status === OK responseAs[String] === "Ok" } Get() ~> Host("verylonghostname.com") ~> route ~> check { handled must beFalse } } "using-regex" in { val route = host("api|rest".r) { prefix => complete(s"Extracted prefix: $prefix") } ~ host("public.(my|your)company.com".r) { captured => complete(s"You came through $captured company") } Get() ~> Host("api.company.com") ~> route ~> check { status === OK responseAs[String] === "Extracted prefix: api" } Get() ~> Host("public.mycompany.com") ~> route ~> check { status === OK responseAs[String] === "You came through my company" } } "failing-regex" in { { host("server-([0-9]).company.(com|net|org)".r) { target => complete("Will never complete :'(") } } must throwAn[IllegalArgumentException] } }
{ "pile_set_name": "Github" }
{ "images" : [ { "idiom" : "universal", "scale" : "1x" }, { "idiom" : "universal", "filename" : "[email protected]", "scale" : "2x" }, { "idiom" : "universal", "filename" : "[email protected]", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } }
{ "pile_set_name": "Github" }
// -*- C++ -*- //===----------------------------- iterator -------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef _LIBCPP_EXPERIMENTAL_ITERATOR #define _LIBCPP_EXPERIMENTAL_ITERATOR /* namespace std { namespace experimental { inline namespace fundamentals_v2 { template <class DelimT, class charT = char, class traits = char_traits<charT>> class ostream_joiner { public: typedef charT char_type; typedef traits traits_type; typedef basic_ostream<charT, traits> ostream_type; typedef output_iterator_tag iterator_category; typedef void value_type; typedef void difference_type; typedef void pointer; typedef void reference; ostream_joiner(ostream_type& s, const DelimT& delimiter); ostream_joiner(ostream_type& s, DelimT&& delimiter); template<typename T> ostream_joiner& operator=(const T& value); ostream_joiner& operator*() noexcept; ostream_joiner& operator++() noexcept; ostream_joiner& operator++(int) noexcept; private: ostream_type* out_stream; // exposition only DelimT delim; // exposition only bool first_element; // exposition only }; template <class charT, class traits, class DelimT> ostream_joiner<decay_t<DelimT>, charT, traits> make_ostream_joiner(basic_ostream<charT, traits>& os, DelimT&& delimiter); } // inline namespace fundamentals_v2 } // namespace experimental } // namespace std */ #include <experimental/__config> #if _LIBCPP_STD_VER > 11 #include <iterator> _LIBCPP_BEGIN_NAMESPACE_LFTS template <class _Delim, class _CharT = char, class _Traits = char_traits<_CharT>> class ostream_joiner { public: typedef _CharT char_type; typedef _Traits traits_type; typedef basic_ostream<char_type,traits_type> ostream_type; typedef output_iterator_tag iterator_category; typedef void value_type; typedef void difference_type; typedef void pointer; typedef void reference; ostream_joiner(ostream_type& __os, _Delim&& __d) : __output_iter(_VSTD::addressof(__os)), __delim(_VSTD::move(__d)), __first(true) {} ostream_joiner(ostream_type& __os, const _Delim& __d) : __output_iter(_VSTD::addressof(__os)), __delim(__d), __first(true) {} template<typename _Tp> ostream_joiner& operator=(const _Tp& __v) { if (!__first) *__output_iter << __delim; __first = false; *__output_iter << __v; return *this; } ostream_joiner& operator*() _NOEXCEPT { return *this; } ostream_joiner& operator++() _NOEXCEPT { return *this; } ostream_joiner& operator++(int) _NOEXCEPT { return *this; } private: ostream_type* __output_iter; _Delim __delim; bool __first; }; template <class _CharT, class _Traits, class _Delim> ostream_joiner<typename decay<_Delim>::type, _CharT, _Traits> make_ostream_joiner(basic_ostream<_CharT, _Traits>& __os, _Delim && __d) { return ostream_joiner<typename decay<_Delim>::type, _CharT, _Traits>(__os, _VSTD::forward<_Delim>(__d)); } _LIBCPP_END_NAMESPACE_LFTS #endif /* _LIBCPP_STD_VER > 11 */ #endif // _LIBCPP_EXPERIMENTAL_ITERATOR
{ "pile_set_name": "Github" }
# Copyright 1999-2006 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # $Header$ DESCRIPTION="IceCast live streamer, delivering ogg and mp3 streams simultaneously to multiple hosts." HOMEPAGE="http://darkice.tyrell.hu/" SRC_URI="http://darkice.tyrell.hu/dist/${PV}/${P}.tar.gz" LICENSE="GPL-2" SLOT="0" KEYWORDS="~alpha ~amd64 ~hppa ~ppc ~sparc ~x86" IUSE="alsa encode jack vorbis" DEPEND="encode? ( >=media-sound/lame-1.89 ) vorbis? ( >=media-libs/libvorbis-1.0 ) alsa? ( >=media-libs/alsa-lib-1.0.0 ) jack? ( media-sound/jack-audio-connection-kit )" src_compile() { if ! use encode && ! use vorbis then eerror "You need support for mp3 or Ogg Vorbis enconding for this" eerror "package. Please merge again with at least one of the " eerror "\`encode' and \`vorbis' USE flags enabled:" eerror eerror " # USE=\"encode\" emerge darkice" eerror " # USE=\"vorbis\" emerge darkice" die "Won't build without support for lame nor vorbis" fi econf $(use_with alsa) \ $(use_with encode lame) \ $(use_with jack) \ $(use_with vorbis) || die "configuration failed" emake || die "Compilation failed" } src_install() { einstall darkicedocdir=${D}/usr/share/doc/${PF} || die "make install failed" dodoc AUTHORS ChangeLog NEWS README TODO }
{ "pile_set_name": "Github" }
(;CA[UTF-8]AP[YuanYu]GM[1]FF[4] SZ[19] GN[] DT[2017-07-03] PB[骊龙]BR[9段] PW[NIPOHC]WR[9段] KM[0]HA[0]RU[Japanese]RE[W+R]TM[60]TC[3]TT[60] ;B[pd];W[dd];B[qp];W[dq];B[oq];W[qf];B[nc];W[qo];B[po];W[qn];B[pn] ;W[ql];B[qm];W[rm];B[pm];W[pi];B[co];W[iq];B[ep];W[eq];B[fp];W[fq] ;B[gp];W[hq];B[gq];W[gr];B[fr];W[hr];B[cq];W[dp];B[do];W[cp];B[bp] ;W[cr];B[bq];W[er];B[cj];W[fc];B[pl];W[qk];B[rl];W[rn];B[rk];W[qj] ;B[rp];W[rj];B[qe];W[qc];B[pf];W[ob];B[nb];W[oc];B[od];W[rd];B[re] ;W[rb];B[oa];W[pb];B[cf];W[dk];B[dj];W[ek];B[ej];W[en];B[eo];W[bn] ;B[bo];W[fk];B[bl];W[ic];B[jc];W[jd];B[kd];W[kc];B[jb];W[ke];B[ld] ;W[id];B[cd];W[cc];B[bc];W[ce];B[bd];W[df];B[dc];W[ec];B[be];W[de] ;B[fj];W[hk];B[gk];W[gl];B[gj];W[hl];B[lq];W[db];B[cg];W[kb];B[lb] ;W[ib];B[dm];W[em];B[lc];W[ja];B[ro];W[sk];B[sn];W[sl];B[qd];W[sd] ;B[sb];W[pa];B[ra];W[rc];B[pc];W[na];B[ma];W[rf];B[se];W[qa];B[oa] ;W[sa];B[pg];W[qh];B[ra];W[na];B[qg];W[rg];B[oa];W[sa];B[rh];W[ri] ;B[ra];W[na];B[ph];W[sh];B[lg];W[lp];B[oa];W[sa];B[kq];W[mp];B[mq] ;W[np];B[nq];W[oh];B[ng];W[nh];B[ln];W[kp];B[ra];W[na];B[mh];W[op] ;B[pp];W[io];B[oa];W[sa];B[mj];W[nj];B[jf];W[je];B[nk];W[bb];B[br] ;W[jr];B[ra];W[na];B[if];W[ms];B[oa];W[sa];B[ns];W[dg];B[ra];W[na] ;B[ds];W[es];B[oa];W[sa];B[oj];W[ni];B[mi];W[oi];B[jm];W[dn];B[cn] ;W[cm];B[cl];W[dl];B[hn];W[hj];B[ho];W[jo];B[hi];W[im];B[in];W[ii] ;B[jk];W[hh];B[gi];W[jl];B[kk];W[kl];B[jn];W[jj];B[ih];W[jh];B[ig] ;W[kj];B[lk];W[kh];B[ra];W[na];B[jq];W[jp];B[oa];W[sa];B[kr];W[ks] ;B[ra];W[na];B[ls];W[lr];B[oa];W[sa];B[cb];W[ca];B[ra];W[na];B[hp] ;W[ip];B[oa];W[sa];B[bm];W[gm];B[ra];W[na];B[is];W[js];B[oa];W[sa] ;B[fn];W[fm];B[ra];W[na];B[dh];W[eh];B[oa];W[sa];B[ik];W[ij];B[ra] ;W[na];B[il];W[ch];B[bh];W[gf];B[oa];W[sa];B[kg];W[ok];B[ra];W[na] ;B[he];W[di];B[ci];W[bs];B[ge];W[ls];B[mr];W[ir];B[oa];W[sa];B[gc] ;W[gb];B[ra];W[na];B[hc];W[og];B[of];W[nf];B[ne];W[mg];B[mf];W[ng] ;B[oa];W[sa];B[hb];W[ha];B[ra];W[na];B[fb];W[ga];B[oa];W[sa];B[fa] ;W[ia];B[ra];W[na];B[pk];W[pj];B[oa];W[sa];B[cs];W[dr];B[ff];W[gh] ;B[ra];W[na];B[lf];W[os];B[nl];W[nr];B[or];W[ns])
{ "pile_set_name": "Github" }
/* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * 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. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Jani Monoses <[email protected]> * */ #ifndef __LWIP_IP_FRAG_H__ #define __LWIP_IP_FRAG_H__ #include "lwip/opt.h" #include "lwip/err.h" #include "lwip/pbuf.h" #include "lwip/netif.h" #include "lwip/ip_addr.h" #include "lwip/ip.h" #ifdef __cplusplus extern "C" { #endif #if IP_REASSEMBLY /* The IP reassembly timer interval in milliseconds. */ #define IP_TMR_INTERVAL 1000 /* IP reassembly helper struct. * This is exported because memp needs to know the size. */ struct ip_reassdata { struct ip_reassdata *next; struct pbuf *p; struct ip_hdr iphdr; u16_t datagram_len; u8_t flags; u8_t timer; }; void ip_reass_init(void)ICACHE_FLASH_ATTR; void ip_reass_tmr(void)ICACHE_FLASH_ATTR; struct pbuf * ip_reass(struct pbuf *p)ICACHE_FLASH_ATTR; #endif /* IP_REASSEMBLY */ #if IP_FRAG #if !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF /** A custom pbuf that holds a reference to another pbuf, which is freed * when this custom pbuf is freed. This is used to create a custom PBUF_REF * that points into the original pbuf. */ struct pbuf_custom_ref { /** 'base class' */ struct pbuf_custom pc; /** pointer to the original pbuf that is referenced */ struct pbuf *original; }; #endif /* !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF */ err_t ip_frag(struct pbuf *p, struct netif *netif, ip_addr_t *dest)ICACHE_FLASH_ATTR; #endif /* IP_FRAG */ #ifdef __cplusplus } #endif #endif /* __LWIP_IP_FRAG_H__ */
{ "pile_set_name": "Github" }
// PpmdZip.cpp #include "StdAfx.h" #include "../../../C/CpuArch.h" #include "../Common/RegisterCodec.h" #include "../Common/StreamUtils.h" #include "PpmdZip.h" namespace NCompress { namespace NPpmdZip { CDecoder::CDecoder(bool fullFileMode): _fullFileMode(fullFileMode) { _ppmd.Stream.In = &_inStream.vt; Ppmd8_Construct(&_ppmd); } CDecoder::~CDecoder() { Ppmd8_Free(&_ppmd, &g_BigAlloc); } STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) { if (!_outStream.Alloc()) return E_OUTOFMEMORY; if (!_inStream.Alloc(1 << 20)) return E_OUTOFMEMORY; _inStream.Stream = inStream; _inStream.Init(); { Byte buf[2]; for (int i = 0; i < 2; i++) buf[i] = _inStream.ReadByte(); if (_inStream.Extra) return S_FALSE; UInt32 val = GetUi16(buf); UInt32 order = (val & 0xF) + 1; UInt32 mem = ((val >> 4) & 0xFF) + 1; UInt32 restor = (val >> 12); if (order < 2 || restor > 2) return S_FALSE; #ifndef PPMD8_FREEZE_SUPPORT if (restor == 2) return E_NOTIMPL; #endif if (!Ppmd8_Alloc(&_ppmd, mem << 20, &g_BigAlloc)) return E_OUTOFMEMORY; if (!Ppmd8_RangeDec_Init(&_ppmd)) return S_FALSE; Ppmd8_Init(&_ppmd, order, restor); } bool wasFinished = false; UInt64 processedSize = 0; for (;;) { size_t size = kBufSize; if (outSize) { const UInt64 rem = *outSize - processedSize; if (size > rem) { size = (size_t)rem; if (size == 0) break; } } Byte *data = _outStream.Buf; size_t i = 0; int sym = 0; do { sym = Ppmd8_DecodeSymbol(&_ppmd); if (_inStream.Extra || sym < 0) break; data[i] = (Byte)sym; } while (++i != size); processedSize += i; RINOK(WriteStream(outStream, _outStream.Buf, i)); RINOK(_inStream.Res); if (_inStream.Extra) return S_FALSE; if (sym < 0) { if (sym != -1) return S_FALSE; wasFinished = true; break; } if (progress) { const UInt64 inProccessed = _inStream.GetProcessed(); RINOK(progress->SetRatioInfo(&inProccessed, &processedSize)); } } RINOK(_inStream.Res); if (_fullFileMode) { if (!wasFinished) { int res = Ppmd8_DecodeSymbol(&_ppmd); RINOK(_inStream.Res); if (_inStream.Extra || res != -1) return S_FALSE; } if (!Ppmd8_RangeDec_IsFinishedOK(&_ppmd)) return S_FALSE; if (inSize && *inSize != _inStream.GetProcessed()) return S_FALSE; } return S_OK; } STDMETHODIMP CDecoder::SetFinishMode(UInt32 finishMode) { _fullFileMode = (finishMode != 0); return S_OK; } STDMETHODIMP CDecoder::GetInStreamProcessedSize(UInt64 *value) { *value = _inStream.GetProcessed(); return S_OK; } // ---------- Encoder ---------- void CEncProps::Normalize(int level) { if (level < 0) level = 5; if (level == 0) level = 1; if (level > 9) level = 9; if (MemSizeMB == (UInt32)(Int32)-1) MemSizeMB = (1 << ((level > 8 ? 8 : level) - 1)); const unsigned kMult = 16; if ((MemSizeMB << 20) / kMult > ReduceSize) { for (UInt32 m = (1 << 20); m <= (1 << 28); m <<= 1) { if (ReduceSize <= m / kMult) { m >>= 20; if (MemSizeMB > m) MemSizeMB = m; break; } } } if (Order == -1) Order = 3 + level; if (Restor == -1) Restor = level < 7 ? PPMD8_RESTORE_METHOD_RESTART : PPMD8_RESTORE_METHOD_CUT_OFF; } CEncoder::~CEncoder() { Ppmd8_Free(&_ppmd, &g_BigAlloc); } STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps) { int level = -1; CEncProps props; for (UInt32 i = 0; i < numProps; i++) { const PROPVARIANT &prop = coderProps[i]; PROPID propID = propIDs[i]; if (propID > NCoderPropID::kReduceSize) continue; if (propID == NCoderPropID::kReduceSize) { if (prop.vt == VT_UI8 && prop.uhVal.QuadPart < (UInt32)(Int32)-1) props.ReduceSize = (UInt32)prop.uhVal.QuadPart; continue; } if (prop.vt != VT_UI4) return E_INVALIDARG; UInt32 v = (UInt32)prop.ulVal; switch (propID) { case NCoderPropID::kUsedMemorySize: if (v < (1 << 20) || v > (1 << 28)) return E_INVALIDARG; props.MemSizeMB = v >> 20; break; case NCoderPropID::kOrder: if (v < PPMD8_MIN_ORDER || v > PPMD8_MAX_ORDER) return E_INVALIDARG; props.Order = (Byte)v; break; case NCoderPropID::kNumThreads: break; case NCoderPropID::kLevel: level = (int)v; break; case NCoderPropID::kAlgorithm: if (v > 1) return E_INVALIDARG; props.Restor = v; break; default: return E_INVALIDARG; } } props.Normalize(level); _props = props; return S_OK; } CEncoder::CEncoder() { _props.Normalize(-1); _ppmd.Stream.Out = &_outStream.vt; Ppmd8_Construct(&_ppmd); } STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) { if (!_inStream.Alloc()) return E_OUTOFMEMORY; if (!_outStream.Alloc(1 << 20)) return E_OUTOFMEMORY; if (!Ppmd8_Alloc(&_ppmd, _props.MemSizeMB << 20, &g_BigAlloc)) return E_OUTOFMEMORY; _outStream.Stream = outStream; _outStream.Init(); Ppmd8_RangeEnc_Init(&_ppmd); Ppmd8_Init(&_ppmd, _props.Order, _props.Restor); UInt32 val = (UInt32)((_props.Order - 1) + ((_props.MemSizeMB - 1) << 4) + (_props.Restor << 12)); _outStream.WriteByte((Byte)(val & 0xFF)); _outStream.WriteByte((Byte)(val >> 8)); RINOK(_outStream.Res); UInt64 processed = 0; for (;;) { UInt32 size; RINOK(inStream->Read(_inStream.Buf, kBufSize, &size)); if (size == 0) { Ppmd8_EncodeSymbol(&_ppmd, -1); Ppmd8_RangeEnc_FlushData(&_ppmd); return _outStream.Flush(); } for (UInt32 i = 0; i < size; i++) { Ppmd8_EncodeSymbol(&_ppmd, _inStream.Buf[i]); RINOK(_outStream.Res); } processed += size; if (progress) { const UInt64 outProccessed = _outStream.GetProcessed(); RINOK(progress->SetRatioInfo(&processed, &outProccessed)); } } } }}
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: db16d828fd4d5044aa8ef91e8bfbb4ef folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
/* ------------------------------------------------------------------------------ * * # Daterange picker * * Date range picker component for Bootstrap * * Version: 1.2 * Latest update: Mar 10, 2016 * * ---------------------------------------------------------------------------- */ // Core // ------------------------------ .daterangepicker { position: absolute; left: 0; margin-top: 5px; width: auto; padding: 0; // Override default dropdown styles &.dropdown-menu { max-width: none; background-color: transparent; border: 0; z-index: @zindex-dropdown; .box-shadow(none); } // Dropup &.dropup { margin-top: -(@list-spacing); } // Align containers .ranges, .calendar { float: left; } // Display calendars on left side &.opensleft { .calendars { float: left; } } // Display calendars on right side &.opensright { .calendars { float: right; } } // And remove floats in single picker &.single { .calendar { float: none; margin-left: 0; margin-right: 0; } // Hide range menu .ranges { display: none; } } // Display calendars &.show-calendar .calendar { display: block; } // Calendar .calendar { display: none; background-color: @dropdown-bg; border: 1px solid @dropdown-border; border-radius: @border-radius-base; margin: @list-spacing; padding: (@list-spacing * 2); .box-shadow(0 1px 3px fade(#000, 10%)); } } // Table // ------------------------------ .daterangepicker { // Table defaults table { width: 100%; margin: 0; tbody { th, td { cursor: pointer; } } } // Cells th, td { white-space: nowrap; text-align: center; &.week { font-size: 80%; color: #ccc; } } // Header th { color: @text-muted; font-weight: normal; font-size: @font-size-small; // Icons > i { top: 0; } // Arrow buttons &.prev, &.next { cursor: pointer; } // Available dates &.available { &:hover, &:focus { color: @text-color; } } } // Table content cells td { // Available days &.available { &:hover, &:focus { background-color: @dropdown-link-hover-bg; } } // Inactive days &.off, &.disabled { color: #ccc; } // Disabled days &.disabled { cursor: @cursor-disabled; } // Highlight dates in range &.in-range { background-color: @dropdown-link-hover-bg; } // Active date &.active { &, &:hover, &:focus { background-color: @color-teal-400; color: #fff; border-radius: @border-radius-base; } } } // Override default condensed styles .table-condensed { tr > th, tr > td { padding: @padding-xs-horizontal; line-height: 1; } // Add extra top padding to day names thead tr:last-child th { padding-top: (@list-spacing * 2); } // Month heading .month { font-size: @font-size-h6; line-height: 1; color: @text-color; padding-top: @content-padding-base; padding-bottom: @content-padding-base; font-weight: 400; } } } // Elements // ------------------------------ .daterangepicker { // Selects select { display: inline-block; &.monthselect { margin-right: 2%; width: 56%; } &.yearselect { width: 40%; } &.hourselect, &.minuteselect, &.secondselect, &.ampmselect { width: 60px; padding-left: 0; padding-right: 0; margin-bottom: 0; } } // Text inputs .daterangepicker_input { position: relative; // Calendar icons i { position: absolute; right: @padding-small-horizontal; top: auto; bottom: ((@input-height-base - @icon-font-size) / 2); color: @text-muted; } // Add right padding for inputs input { padding-left: @padding-small-horizontal; padding-right: (@padding-small-horizontal + @icon-font-size + @padding-base-vertical); } } // Time picker .calendar-time { text-align: center; margin: @padding-base-horizontal 0; // Disabled state select.disabled { color: #ccc; cursor: @cursor-disabled; } } } // Ranges dropdown // ------------------------------ .ranges { background-color: @dropdown-bg; position: relative; border: 1px solid @dropdown-border; border-radius: @border-radius-base; width: 200px; margin-top: @list-spacing; .box-shadow(0 1px 3px fade(#000, 10%)); // Remove left margin if on right side .opensright & { margin-left: 0; } // Remove left margin if on left side .opensleft & { margin-right: 0; } // List with links ul { list-style: none; margin: 0; padding: @list-spacing 0; // Add top border & + .daterangepicker-inputs { border-top: 1px solid @dropdown-divider-bg; } // List item li { color: @text-color; padding: (@padding-base-vertical + 1) @padding-base-horizontal; cursor: pointer; margin-top: 1px; &:first-child { margin-top: 0; } // Hover bg color &:hover, &:focus { background-color: @dropdown-link-hover-bg; } // Active item color &.active { color: @dropdown-link-active-color; background-color: @color-teal-400; } } } // Text inputs .daterangepicker-inputs { padding: @padding-base-horizontal; padding-top: @padding-base-horizontal + @list-spacing; // we need to match menu vertical spacing // Inputs container .daterangepicker_input { // Add top margin to the second field & + .daterangepicker_input { margin-top: @padding-base-horizontal + @list-spacing;; } // Text label > span { display: block; font-size: @font-size-small; margin-bottom: @padding-base-vertical; color: @text-muted; } } // Add top divider & + .range_inputs { border-top: 1px solid @dropdown-divider-bg; } } // Buttons area .range_inputs { padding: @padding-base-horizontal; // Buttons .btn { display: block; width: 100%; } .btn + .btn { margin-top: @padding-base-horizontal; } } // Setup mobile view @media (min-width: @screen-sm) { margin: @list-spacing; } } // Custom ranges layout // ------------------------------ // Container .daterange-custom { cursor: pointer; // Clearing floats &:after { content: ''; display: table; clear: both; } // Labels and badges .label, .badge { margin: 4px 0 0 @element-horizontal-spacing; vertical-align: top; } .label-icon { margin-top: 0; margin-right: 5px; } } // Layout .daterange-custom-display { display: inline-block; position: relative; padding-left: (@icon-font-size + 5); line-height: 1; // Arrow icon &:after { content: '\e9c9'; font-family: 'icomoon'; display: inline-block; position: absolute; top: 50%; left: 0; margin-top: -(@icon-font-size / 2); -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; .transition(all ease-in-out 0.2s); // Rotate if open/closed .daterange-custom.is-opened & { .rotate(180deg); } } // Date number > i { display: inline-block; font-size: 28px; font-weight: normal; font-style: normal; letter-spacing: @heading-letter-spacing; } // Date details b { display: inline-block; margin-left: 4px; font-weight: 400; // Month/year > i { font-size: @font-size-mini; display: block; line-height: @font-size-small; text-transform: uppercase; font-style: normal; font-weight: 400; } } // Line divider em { line-height: 30px; vertical-align: top; margin: 0 4px; } } // Setup mobile view // ------------------------------ @media (max-width: @screen-sm) { // Layout .opensleft, .opensright { left: 0!important; right: 0; // Stack calendars container .calendars { float: none; } // Stack elements .daterangepicker& { .ranges, .calendar, .calendars { float: none; } } } // Elements .daterangepicker { width: 100%; padding-left: @grid-gutter-width; padding-right: @grid-gutter-width; // Remove side margin from calendars .calendar { margin-left: 0; margin-right: 0; } // Make ranges full width .ranges { width: 100%; } } }
{ "pile_set_name": "Github" }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`features/virtualized-table/VirtualizedTable should successfully render a VirtualizedTable 1`] = ` <VirtualizedTable intl={ Object { "formatDate": [Function], "formatMessage": [Function], "formatRelativeTime": [Function], } } rowData={ Array [ Object { "description": "description1", "name": "name1", }, Object { "description": "description2", "name": "name2", }, Object { "description": "description3", "name": "name3", }, ] } > <Column cellDataGetter={[Function]} cellRenderer={[Function]} dataKey="name" defaultSortDirection="ASC" flexGrow={0} flexShrink={1} headerRenderer={[Function]} label="Name" style={Object {}} width={100} /> <Column cellDataGetter={[Function]} cellRenderer={[Function]} dataKey="description" defaultSortDirection="ASC" flexGrow={0} flexShrink={1} headerRenderer={[Function]} label="Description" style={Object {}} width={100} /> </VirtualizedTable> `; exports[`features/virtualized-table/VirtualizedTable should successfully render a VirtualizedTable 2`] = ` <AutoSizer disableHeight={true} disableWidth={false} onResize={[Function]} style={Object {}} > <Component /> </AutoSizer> `; exports[`features/virtualized-table/VirtualizedTable should successfully render a VirtualizedTable 3`] = ` <WindowScroller onResize={[Function]} onScroll={[Function]} scrollElement={[Window]} scrollingResetTimeInterval={150} serverHeight={0} serverWidth={0} > <Component /> </WindowScroller> `; exports[`features/virtualized-table/VirtualizedTable should successfully render a VirtualizedTable 4`] = ` <Table autoHeight={true} className="bdl-VirtualizedTable" disableHeader={false} estimatedRowSize={30} headerHeight={39} headerRowRenderer={[Function]} headerStyle={Object {}} height={768} isScrolling={false} noRowsRenderer={[Function]} onRowsRendered={[Function]} onScroll={[Function]} overscanIndicesGetter={[Function]} overscanRowCount={10} rowCount={3} rowGetter={[Function]} rowHeight={52} rowRenderer={[Function]} rowStyle={Object {}} scrollToAlignment="auto" scrollToIndex={-1} scrollTop={0} sort={[Function]} style={Object {}} tabIndex={-1} width={0} > <Column cellDataGetter={[Function]} cellRenderer={[Function]} dataKey="name" defaultSortDirection="ASC" flexGrow={0} flexShrink={1} headerRenderer={[Function]} label="Name" style={Object {}} width={100} /> <Column cellDataGetter={[Function]} cellRenderer={[Function]} dataKey="description" defaultSortDirection="ASC" flexGrow={0} flexShrink={1} headerRenderer={[Function]} label="Description" style={Object {}} width={100} /> </Table> `; exports[`features/virtualized-table/VirtualizedTable should successfully render a VirtualizedTable with fixed height 1`] = ` <AutoSizer defaultHeight={10} disableHeight={true} disableWidth={false} onResize={[Function]} style={Object {}} > <Component /> </AutoSizer> `; exports[`features/virtualized-table/VirtualizedTable should successfully render a VirtualizedTable with fixed height 2`] = ` <Table className="bdl-VirtualizedTable" disableHeader={false} estimatedRowSize={30} headerHeight={39} headerRowRenderer={[Function]} headerStyle={Object {}} height={10} noRowsRenderer={[Function]} onRowsRendered={[Function]} onScroll={[Function]} overscanIndicesGetter={[Function]} overscanRowCount={10} rowCount={3} rowGetter={[Function]} rowHeight={52} rowRenderer={[Function]} rowStyle={Object {}} scrollToAlignment="auto" scrollToIndex={-1} sort={[Function]} style={Object {}} tabIndex={-1} width={0} > <Column cellDataGetter={[Function]} cellRenderer={[Function]} dataKey="name" defaultSortDirection="ASC" flexGrow={0} flexShrink={1} headerRenderer={[Function]} label="Name" style={Object {}} width={100} /> <Column cellDataGetter={[Function]} cellRenderer={[Function]} dataKey="description" defaultSortDirection="ASC" flexGrow={0} flexShrink={1} headerRenderer={[Function]} label="Description" style={Object {}} width={100} /> </Table> `;
{ "pile_set_name": "Github" }
include ../../../GDALmake.opt OBJ = ogrmdbdatasource.o ogrmdblayer.o ogrmdbdriver.o \ ogrmdbjackcess.o CPPFLAGS := -I.. $(JAVA_INC) $(CPPFLAGS) default: $(O_OBJ:.o=.$(OBJ_EXT)) clean: rm -f *.o $(O_OBJ) $(O_OBJ): ogr_mdb.h
{ "pile_set_name": "Github" }
//***************************************************************************** // Copyright 2017-2020 Intel Corporation // // 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. //***************************************************************************** #include "gtest/gtest.h" #include "ngraph/ngraph.hpp" #include "util/type_prop.hpp" using namespace std; using namespace ngraph; TEST(type_prop, lstm_cell) { const size_t batch_size = 2; const size_t input_size = 3; const size_t hidden_size = 3; const size_t gates_count = 4; const auto X = make_shared<op::v0::Parameter>(element::f32, Shape{batch_size, input_size}); const auto W = make_shared<op::v0::Parameter>(element::f32, Shape{gates_count * hidden_size, input_size}); const auto R = make_shared<op::v0::Parameter>(element::f32, Shape{gates_count * hidden_size, hidden_size}); const auto H_t = make_shared<op::v0::Parameter>(element::f32, Shape{batch_size, hidden_size}); const auto C_t = make_shared<op::v0::Parameter>(element::f32, Shape{batch_size, hidden_size}); const auto lstm_cell = make_shared<op::v0::LSTMCell>(X, H_t, C_t, W, R, hidden_size); EXPECT_EQ(lstm_cell->get_hidden_size(), hidden_size); EXPECT_EQ(lstm_cell->get_clip(), 0.f); EXPECT_TRUE(lstm_cell->get_activations_alpha().empty()); EXPECT_TRUE(lstm_cell->get_activations_beta().empty()); EXPECT_EQ(lstm_cell->get_activations()[0], "sigmoid"); EXPECT_EQ(lstm_cell->get_activations()[1], "tanh"); EXPECT_EQ(lstm_cell->get_activations()[2], "tanh"); EXPECT_EQ(lstm_cell->get_weights_format(), op::LSTMWeightsFormat::IFCO); EXPECT_FALSE(lstm_cell->get_input_forget()); EXPECT_EQ(lstm_cell->get_output_element_type(0), element::f32); EXPECT_EQ(lstm_cell->get_output_shape(0), (Shape{batch_size, hidden_size})); EXPECT_EQ(lstm_cell->get_output_element_type(1), element::f32); EXPECT_EQ(lstm_cell->get_output_shape(1), (Shape{batch_size, hidden_size})); } TEST(type_prop, lstm_cell_invalid_input) { const size_t batch_size = 2; const size_t input_size = 3; const size_t hidden_size = 3; const size_t gates_count = 4; auto X = make_shared<op::v0::Parameter>(element::f32, Shape{batch_size, input_size}); auto R = make_shared<op::v0::Parameter>(element::f32, Shape{gates_count * hidden_size, hidden_size}); auto H_t = make_shared<op::v0::Parameter>(element::f32, Shape{batch_size, hidden_size}); auto C_t = make_shared<op::v0::Parameter>(element::f32, Shape{batch_size, hidden_size}); // Invalid W tensor shape. auto W = make_shared<op::v0::Parameter>(element::f32, Shape{1 * hidden_size, input_size}); try { const auto lstm_cell = make_shared<op::v0::LSTMCell>(X, H_t, C_t, W, R, hidden_size); FAIL() << "LSTMCell node was created with invalid data."; } catch (const NodeValidationFailure& error) { EXPECT_HAS_SUBSTRING(error.what(), std::string("Input tensor W must have shape")); } // Invalid R tensor shape. W = make_shared<op::v0::Parameter>(element::f32, Shape{gates_count * hidden_size, input_size}); R = make_shared<op::v0::Parameter>(element::f32, Shape{gates_count * hidden_size, 1}); try { const auto lstm_cell = make_shared<op::v0::LSTMCell>(X, H_t, C_t, W, R, hidden_size); FAIL() << "LSTMCell node was created with invalid data."; } catch (const NodeValidationFailure& error) { EXPECT_HAS_SUBSTRING(error.what(), std::string("Input tensor R must have shape")); } // Invalid H_t tensor shape. R = make_shared<op::v0::Parameter>(element::f32, Shape{gates_count * hidden_size, hidden_size}); H_t = make_shared<op::v0::Parameter>(element::f32, Shape{4, hidden_size}); try { const auto lstm_cell = make_shared<op::v0::LSTMCell>(X, H_t, C_t, W, R, hidden_size); FAIL() << "LSTMCell node was created with invalid data."; } catch (const NodeValidationFailure& error) { EXPECT_HAS_SUBSTRING(error.what(), std::string("Input tensor initial_hidden_state must have shape")); } // Invalid C_t tensor shape. H_t = make_shared<op::v0::Parameter>(element::f32, Shape{batch_size, hidden_size}); C_t = make_shared<op::v0::Parameter>(element::f32, Shape{4, hidden_size}); try { const auto lstm_cell = make_shared<op::v0::LSTMCell>(X, H_t, C_t, W, R, hidden_size); FAIL() << "LSTMCell node was created with invalid data."; } catch (const NodeValidationFailure& error) { EXPECT_HAS_SUBSTRING(error.what(), std::string("Input tensor initial_cell_state must have shape")); } // Invalid B tensor shape. C_t = make_shared<op::v0::Parameter>(element::f32, Shape{batch_size, hidden_size}); auto B = make_shared<op::v0::Parameter>(element::f32, Shape{2 * gates_count * hidden_size}); auto P = make_shared<op::v0::Parameter>(element::f32, Shape{3 * hidden_size}); try { const auto lstm_cell = make_shared<op::v0::LSTMCell>(X, H_t, C_t, W, R, B, P, hidden_size); FAIL() << "LSTMCell node was created with invalid data."; } catch (const NodeValidationFailure& error) { EXPECT_HAS_SUBSTRING(error.what(), std::string("Input tensor B must have shape")); } // Invalid P tensor shape. B = make_shared<op::v0::Parameter>(element::f32, Shape{gates_count * hidden_size}); P = make_shared<op::v0::Parameter>(element::f32, Shape{hidden_size}); try { const auto lstm_cell = make_shared<op::v0::LSTMCell>(X, H_t, C_t, W, R, B, P, hidden_size); FAIL() << "LSTMCell node was created with invalid data."; } catch (const NodeValidationFailure& error) { EXPECT_HAS_SUBSTRING(error.what(), std::string("Input tensor P must have shape")); } }
{ "pile_set_name": "Github" }
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "rgw_common.h" #include "rgw_rest_pubsub_common.h" #include "common/dout.h" #include "rgw_url.h" #include "rgw_sal_rados.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_rgw bool validate_and_update_endpoint_secret(rgw_pubsub_sub_dest& dest, CephContext *cct, const RGWEnv& env) { if (dest.push_endpoint.empty()) { return true; } std::string user; std::string password; if (!rgw::parse_url_userinfo(dest.push_endpoint, user, password)) { ldout(cct, 1) << "endpoint validation error: malformed endpoint URL:" << dest.push_endpoint << dendl; return false; } // this should be verified inside parse_url() ceph_assert(user.empty() == password.empty()); if (!user.empty()) { dest.stored_secret = true; if (!rgw_transport_is_secure(cct, env)) { ldout(cct, 1) << "endpoint validation error: sending password over insecure transport" << dendl; return false; } } return true; } bool subscription_has_endpoint_secret(const rgw_pubsub_sub_config& sub) { return sub.dest.stored_secret; } bool topic_has_endpoint_secret(const rgw_pubsub_topic_subs& topic) { return topic.topic.dest.stored_secret; } bool topics_has_endpoint_secret(const rgw_pubsub_user_topics& topics) { for (const auto& topic : topics.topics) { if (topic_has_endpoint_secret(topic.second)) return true; } return false; } void RGWPSCreateTopicOp::execute() { op_ret = get_params(); if (op_ret < 0) { return; } ups.emplace(store, s->owner.get_id()); op_ret = ups->create_topic(topic_name, dest, topic_arn, opaque_data); if (op_ret < 0) { ldout(s->cct, 1) << "failed to create topic '" << topic_name << "', ret=" << op_ret << dendl; return; } ldout(s->cct, 20) << "successfully created topic '" << topic_name << "'" << dendl; } void RGWPSListTopicsOp::execute() { ups.emplace(store, s->owner.get_id()); op_ret = ups->get_user_topics(&result); // if there are no topics it is not considered an error op_ret = op_ret == -ENOENT ? 0 : op_ret; if (op_ret < 0) { ldout(s->cct, 1) << "failed to get topics, ret=" << op_ret << dendl; return; } if (topics_has_endpoint_secret(result) && !rgw_transport_is_secure(s->cct, *(s->info.env))) { ldout(s->cct, 1) << "topics contain secret and cannot be sent over insecure transport" << dendl; op_ret = -EPERM; return; } ldout(s->cct, 20) << "successfully got topics" << dendl; } void RGWPSGetTopicOp::execute() { op_ret = get_params(); if (op_ret < 0) { return; } ups.emplace(store, s->owner.get_id()); op_ret = ups->get_topic(topic_name, &result); if (topic_has_endpoint_secret(result) && !rgw_transport_is_secure(s->cct, *(s->info.env))) { ldout(s->cct, 1) << "topic '" << topic_name << "' contain secret and cannot be sent over insecure transport" << dendl; op_ret = -EPERM; return; } if (op_ret < 0) { ldout(s->cct, 1) << "failed to get topic '" << topic_name << "', ret=" << op_ret << dendl; return; } ldout(s->cct, 1) << "successfully got topic '" << topic_name << "'" << dendl; } void RGWPSDeleteTopicOp::execute() { op_ret = get_params(); if (op_ret < 0) { return; } ups.emplace(store, s->owner.get_id()); op_ret = ups->remove_topic(topic_name); if (op_ret < 0) { ldout(s->cct, 1) << "failed to remove topic '" << topic_name << ", ret=" << op_ret << dendl; return; } ldout(s->cct, 1) << "successfully removed topic '" << topic_name << "'" << dendl; } void RGWPSCreateSubOp::execute() { op_ret = get_params(); if (op_ret < 0) { return; } ups.emplace(store, s->owner.get_id()); auto sub = ups->get_sub(sub_name); op_ret = sub->subscribe(topic_name, dest); if (op_ret < 0) { ldout(s->cct, 1) << "failed to create subscription '" << sub_name << "', ret=" << op_ret << dendl; return; } ldout(s->cct, 20) << "successfully created subscription '" << sub_name << "'" << dendl; } void RGWPSGetSubOp::execute() { op_ret = get_params(); if (op_ret < 0) { return; } ups.emplace(store, s->owner.get_id()); auto sub = ups->get_sub(sub_name); op_ret = sub->get_conf(&result); if (subscription_has_endpoint_secret(result) && !rgw_transport_is_secure(s->cct, *(s->info.env))) { ldout(s->cct, 1) << "subscription '" << sub_name << "' contain secret and cannot be sent over insecure transport" << dendl; op_ret = -EPERM; return; } if (op_ret < 0) { ldout(s->cct, 1) << "failed to get subscription '" << sub_name << "', ret=" << op_ret << dendl; return; } ldout(s->cct, 20) << "successfully got subscription '" << sub_name << "'" << dendl; } void RGWPSDeleteSubOp::execute() { op_ret = get_params(); if (op_ret < 0) { return; } ups.emplace(store, s->owner.get_id()); auto sub = ups->get_sub(sub_name); op_ret = sub->unsubscribe(topic_name); if (op_ret < 0) { ldout(s->cct, 1) << "failed to remove subscription '" << sub_name << "', ret=" << op_ret << dendl; return; } ldout(s->cct, 20) << "successfully removed subscription '" << sub_name << "'" << dendl; } void RGWPSAckSubEventOp::execute() { op_ret = get_params(); if (op_ret < 0) { return; } ups.emplace(store, s->owner.get_id()); auto sub = ups->get_sub_with_events(sub_name); op_ret = sub->remove_event(event_id); if (op_ret < 0) { ldout(s->cct, 1) << "failed to ack event on subscription '" << sub_name << "', ret=" << op_ret << dendl; return; } ldout(s->cct, 20) << "successfully acked event on subscription '" << sub_name << "'" << dendl; } void RGWPSPullSubEventsOp::execute() { op_ret = get_params(); if (op_ret < 0) { return; } ups.emplace(store, s->owner.get_id()); sub = ups->get_sub_with_events(sub_name); if (!sub) { op_ret = -ENOENT; ldout(s->cct, 1) << "failed to get subscription '" << sub_name << "' for events, ret=" << op_ret << dendl; return; } op_ret = sub->list_events(marker, max_entries); if (op_ret < 0) { ldout(s->cct, 1) << "failed to get events from subscription '" << sub_name << "', ret=" << op_ret << dendl; return; } ldout(s->cct, 20) << "successfully got events from subscription '" << sub_name << "'" << dendl; } int RGWPSCreateNotifOp::verify_permission() { int ret = get_params(); if (ret < 0) { return ret; } const auto& id = s->owner.get_id(); ret = store->getRados()->get_bucket_info(store->svc(), id.tenant, bucket_name, bucket_info, nullptr, null_yield, nullptr); if (ret < 0) { ldout(s->cct, 1) << "failed to get bucket info, cannot verify ownership" << dendl; return ret; } if (bucket_info.owner != id) { ldout(s->cct, 1) << "user doesn't own bucket, not allowed to create notification" << dendl; return -EPERM; } return 0; } int RGWPSDeleteNotifOp::verify_permission() { int ret = get_params(); if (ret < 0) { return ret; } ret = store->getRados()->get_bucket_info(store->svc(), s->owner.get_id().tenant, bucket_name, bucket_info, nullptr, null_yield, nullptr); if (ret < 0) { return ret; } if (bucket_info.owner != s->owner.get_id()) { ldout(s->cct, 1) << "user doesn't own bucket, cannot remove notification" << dendl; return -EPERM; } return 0; } int RGWPSListNotifsOp::verify_permission() { int ret = get_params(); if (ret < 0) { return ret; } ret = store->getRados()->get_bucket_info(store->svc(), s->owner.get_id().tenant, bucket_name, bucket_info, nullptr, null_yield, nullptr); if (ret < 0) { return ret; } if (bucket_info.owner != s->owner.get_id()) { ldout(s->cct, 1) << "user doesn't own bucket, cannot get notification list" << dendl; return -EPERM; } return 0; }
{ "pile_set_name": "Github" }
// Package require implements the same assertions as the `assert` package but // stops test execution when a test fails. // // Example Usage // // The following is a complete example using require in a standard test function: // import ( // "testing" // "github.com/stretchr/testify/require" // ) // // func TestSomething(t *testing.T) { // // var a string = "Hello" // var b string = "Hello" // // require.Equal(t, a, b, "The two words should be the same.") // // } // // Assertions // // The `require` package have same global functions as in the `assert` package, // but instead of returning a boolean result they call `t.FailNow()`. // // Every assertion function also takes an optional string message as the final argument, // allowing custom error messages to be appended to the message the assertion method outputs. package require
{ "pile_set_name": "Github" }
# Change Log All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. ## [3.2.5](https://github.com/liferay/clay/compare/@clayui/[email protected]...@clayui/[email protected]) (2020-08-28) **Note:** Version bump only for package @clayui/tabs ## [3.2.4](https://github.com/liferay/clay/compare/@clayui/[email protected]...@clayui/[email protected]) (2020-08-26) **Note:** Version bump only for package @clayui/tabs ## [3.2.3](https://github.com/liferay/clay/compare/@clayui/[email protected]...@clayui/[email protected]) (2020-07-28) ### Bug Fixes - update packages to appropriate dependencies ([0026168](https://github.com/liferay/clay/commit/0026168)) ## [3.2.2](https://github.com/liferay/clay/compare/@clayui/[email protected]...@clayui/[email protected]) (2020-07-07) ### Bug Fixes - **@clayui/tabs:** check if child is truthy first before cloning ([c357b7d](https://github.com/liferay/clay/commit/c357b7d)) ## [3.2.1](https://github.com/liferay/clay/compare/@clayui/[email protected]...@clayui/[email protected]) (2020-06-18) ### Bug Fixes - **@clayui/tabs:** Make sure we use strict equation ([ad8dd39](https://github.com/liferay/clay/commit/ad8dd39)) # [3.2.0](https://github.com/liferay/clay/compare/@clayui/[email protected]...@clayui/[email protected]) (2020-05-21) ### Features - **@clayui/tabs:** add TabPanel as an alias for TabPane ([924ae4e](https://github.com/liferay/clay/commit/924ae4e)) - **clayui.com:** Revert the change made to headings used, rename stickers and tables to sticker and table respectively, also change some wording ([791dabe](https://github.com/liferay/clay/commit/791dabe)) - **clayui.com:** Update content structure: Checkbox, Management Toolbar, Select Box, Sticker, Table & Tabs ([0fcd54a](https://github.com/liferay/clay/commit/0fcd54a)) ## [3.1.1](https://github.com/liferay/clay/compare/@clayui/[email protected]...@clayui/[email protected]) (2020-04-24) ### Bug Fixes - Fix accessibility issues ([5e09db0](https://github.com/liferay/clay/commit/5e09db0)) # 3.1.0 (2020-02-28) ### Bug Fixes - replace npm in favor of yarn in new packages ([e366fbb](https://github.com/liferay/clay/commit/e366fbb)) - **@clayui/tabs:** add the relationship between tab and tabpane in stories ([ee9edc4](https://github.com/liferay/clay/commit/ee9edc4)) - **@clayui/tabs:** adjust class name timing so that it the tab properly fades in ([b0df6b8](https://github.com/liferay/clay/commit/b0df6b8)) - **@clayui/tabs:** fix the use of React.forwardRef ([a7ce7e0](https://github.com/liferay/clay/commit/a7ce7e0)) - **tabs:** Turns `active` property optional when using Item, default value is `false` ([bb1ae86](https://github.com/liferay/clay/commit/bb1ae86)) ### Features - **tabs:** Creates Tabs component ([4418cc2](https://github.com/liferay/clay/commit/4418cc2)) ## [3.0.6](https://github.com/liferay/clay/tree/master/packages/clay-tabs/compare/@clayui/[email protected]...@clayui/[email protected]) (2020-01-31) **Note:** Version bump only for package @clayui/tabs ## [3.0.5](https://github.com/liferay/clay/tree/master/packages/clay-tabs/compare/@clayui/[email protected]...@clayui/[email protected]) (2020-01-20) **Note:** Version bump only for package @clayui/tabs ## [3.0.4](https://github.com/liferay/clay/tree/master/packages/clay-tabs/compare/@clayui/[email protected]...@clayui/[email protected]) (2019-12-05) **Note:** Version bump only for package @clayui/tabs ## [3.0.3](https://github.com/liferay/clay/tree/master/packages/clay-tabs/compare/@clayui/[email protected]...@clayui/[email protected]) (2019-11-07) **Note:** Version bump only for package @clayui/tabs ## [3.0.2](https://github.com/liferay/clay/tree/master/packages/clay-tabs/compare/@clayui/[email protected]...@clayui/[email protected]) (2019-11-01) **Note:** Version bump only for package @clayui/tabs ## [3.0.1](https://github.com/liferay/clay/tree/master/packages/clay-tabs/compare/@clayui/[email protected]...@clayui/[email protected]) (2019-10-28) **Note:** Version bump only for package @clayui/tabs
{ "pile_set_name": "Github" }
# # Nothing to see here, move along #
{ "pile_set_name": "Github" }
.global floorl .type floorl,@function floorl: fldt 8(%esp) 1: mov $0x7,%al 1: fstcw 8(%esp) mov 9(%esp),%ah mov %al,9(%esp) fldcw 8(%esp) frndint mov %ah,9(%esp) fldcw 8(%esp) ret .global ceill .type ceill,@function ceill: fldt 8(%esp) mov $0xb,%al jmp 1b .global truncl .type truncl,@function truncl: fldt 8(%esp) mov $0xf,%al jmp 1b
{ "pile_set_name": "Github" }
/** * @jest-environment node */ /* @flow */ import cardExamples from '../../../website/app/demos/Card/Card/examples'; import cardActionsExamples from '../../../website/app/demos/Card/CardActions/examples'; import cardBlockExamples from '../../../website/app/demos/Card/CardBlock/examples'; import cardDividerExamples from '../../../website/app/demos/Card/CardDivider/examples'; import cardFooterExamples from '../../../website/app/demos/Card/CardFooter/examples'; import cardImageExamples from '../../../website/app/demos/Card/CardImage/examples'; import cardStatusExamples from '../../../website/app/demos/Card/CardStatus/examples'; import cardTitleExamples from '../../../website/app/demos/Card/CardTitle/examples'; import testDemoExamples from '../../../../utils/testDemoExamples'; const examples = [ ...cardExamples, ...cardActionsExamples, ...cardBlockExamples, ...cardDividerExamples, ...cardFooterExamples, ...cardImageExamples, ...cardStatusExamples, ...cardTitleExamples ]; describe('Card', () => { testDemoExamples(examples, { mode: 'ssr' }); });
{ "pile_set_name": "Github" }
using System; using System.ComponentModel; using System.Drawing.Design; using System.Web.UI; namespace AjaxControlToolkit.HtmlEditor.ToolbarButtons { [RequiredScript(typeof(CommonToolkitScripts))] [ClientScriptResource("Sys.Extended.UI.HtmlEditor.ToolbarButtons.JustifyRight", Constants.HtmlEditorJustifyRightButtonName)] public class JustifyRight : EditorToggleButton { protected override void OnPreRender(EventArgs e) { RegisterButtonImages("Ed-AlignRight"); base.OnPreRender(e); } } }
{ "pile_set_name": "Github" }
/* * Copyright 2020 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.config.materials.perforce; import com.thoughtworks.go.domain.materials.RevisionContext; import com.thoughtworks.go.domain.materials.TestSubprocessExecutionContext; import com.thoughtworks.go.domain.materials.ValidationBean; import com.thoughtworks.go.domain.materials.mercurial.StringRevision; import com.thoughtworks.go.domain.materials.perforce.PerforceFixture; import com.thoughtworks.go.helper.P4TestRepo; import com.thoughtworks.go.util.JsonValue; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Test; import java.io.File; import java.util.*; import static com.thoughtworks.go.util.JsonUtils.from; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; public abstract class P4MaterialTestBase extends PerforceFixture { protected static final String VIEW = "//depot/... //something/..."; @Test void shouldValidateCorrectConnection() { P4Material p4Material = p4Fixture.material(VIEW); p4Material.setPassword("secret"); p4Material.setUseTickets(false); ValidationBean validation = p4Material.checkConnection(new TestSubprocessExecutionContext()); assertThat(validation.isValid()).isTrue(); assertThat(StringUtils.isBlank(validation.getError())).isTrue(); } @Test void shouldBeAbleToGetUrlArgument() { P4Material p4Material = new P4Material("localhost:9876", "p4view"); assertThat(p4Material.getUrlArgument().forDisplay()).isEqualTo("localhost:9876"); } @Test void shouldCheckConnection() { P4Material p4Material = new P4Material("localhost:9876", "p4view"); p4Material.setPassword("secret"); p4Material.setUseTickets(false); ValidationBean validation = p4Material.checkConnection(new TestSubprocessExecutionContext()); assertThat(validation.isValid()).isFalse(); assertThat(validation.getError()).contains("Unable to connect to server localhost:9876"); assertThat(validation.getError()).doesNotContain("secret"); } @Test void shouldReplacePasswordUsingStar() { P4Material p4Material = new P4Material("localhost:9876", "p4view"); p4Material.setPassword("secret"); p4Material.setUseTickets(true); try { p4Material.latestModification(clientFolder, new TestSubprocessExecutionContext()); fail("should throw exception because p4 server not exists."); } catch (Exception e) { assertThat(e.getMessage()).doesNotContain("secret"); } } @Test void shouldUpdateToSpecificRevision() { P4Material p4Material = p4Fixture.material(VIEW); updateMaterial(p4Material, new StringRevision("2")); assertThat(clientFolder.listFiles()).hasSize(8); updateMaterial(p4Material, new StringRevision("3")); assertThat(clientFolder.listFiles()).hasSize(7); } @Test void shouldCleanOutRepoWhenMaterialChanges() throws Exception { P4TestRepo secondTestRepo = P4TestRepo.createP4TestRepo(temporaryFolder, clientFolder); try { secondTestRepo.onSetup(); P4Material p4Material = p4Fixture.material(VIEW); updateMaterial(p4Material, new StringRevision("2")); File.createTempFile("temp", "txt", clientFolder); assertThat(clientFolder.listFiles()).hasSize(9); P4Material otherMaterial = secondTestRepo.material("//depot/lib/... //something/..."); otherMaterial.setUsername("cceuser1"); updateMaterial(otherMaterial, new StringRevision("2")); File.createTempFile("temp", "txt", clientFolder); assertThat(clientFolder.listFiles()) .as("Should clean and re-checkout after p4repo changed") .hasSize(3); otherMaterial.setUsername("cceuser"); otherMaterial.setPassword("password"); updateMaterial(otherMaterial, new StringRevision("2")); assertThat(clientFolder.listFiles()) .as("Should clean and re-checkout after user changed") .hasSize(2); assertThat(outputconsumer.getStdOut()).contains("Working directory has changed. Deleting and re-creating it."); } finally { secondTestRepo.stop(); secondTestRepo.onTearDown(); } } @Test void shouldMapDirectoryInRepoToClientRoot() { P4Material p4Material = p4Fixture.material("//depot/lib/... //cws/..."); updateMaterial(p4Material, new StringRevision("2")); assertThat(getContainedFileNames(clientFolder)).contains("junit.jar"); } private List<String> getContainedFileNames(File folder) { List<String> fileNames = new ArrayList(); File[] files = folder.listFiles(); for (File file : files) { fileNames.add(file.getName()); } return fileNames; } @Test void shouldMapDirectoryInRepoToDirectoryUnderClientRoot() { P4Material p4Material = p4Fixture.material("//depot/lib/... //cws/release1/..."); updateMaterial(p4Material, new StringRevision("2")); assertThat(getContainedFileNames(new File(clientFolder, "release1"))).contains("junit.jar"); } @Test void shouldExcludeSpecifiedDirectory() { P4Material p4Material = p4Fixture.material("//depot/... //cws/... \n -//depot/lib/... //cws/release1/..."); updateMaterial(p4Material, new StringRevision("2")); assertThat(new File(clientFolder, "release1").exists()).isFalse(); assertThat(new File(clientFolder, "release1/junit.jar").exists()).isFalse(); } @Test void shouldSupportAsterisk() { P4Material p4Material = p4Fixture.material("//depot/lib/*.jar //cws/*.war"); updateMaterial(p4Material, new StringRevision("2")); File file = new File(clientFolder, "junit.war"); assertThat(file.exists()).isTrue(); } @Test void shouldSupportPercetage() { P4Material p4Material = p4Fixture.material("//depot/lib/%%1.%%2 //cws/%%2.%%1"); updateMaterial(p4Material, new StringRevision("2")); File file = new File(clientFolder, "jar.junit"); assertThat(file.exists()).isTrue(); } @Test void laterDefinitionShouldOveridePreviousOne() { P4Material p4Material = p4Fixture.material( "//depot/src/... //cws/build/... \n //depot/lib/... //cws/build/..."); File file = new File(clientFolder, "build/junit.jar"); File folderNet = new File(clientFolder, "build/net"); updateMaterial(p4Material, new StringRevision("2")); assertThat(folderNet.exists()).isFalse(); assertThat(file.exists()).isTrue(); } @Test void laterDefinitionShouldMergeWithPreviousOneWhenPlusPresent() { P4Material p4Material = p4Fixture.material( "//depot/src/... //cws/build/... \n +//depot/lib/... //cws/build/..."); File file = new File(clientFolder, "build/junit.jar"); File folderNet = new File(clientFolder, "build/net"); updateMaterial(p4Material, new StringRevision("2")); assertThat(folderNet.exists()).isTrue(); assertThat(file.exists()).isTrue(); } @Test void shouldCleanOutRepoWhenViewChanges() { P4Material p4Material = p4Fixture.material(VIEW); updateMaterial(p4Material, new StringRevision("2")); assertThat(clientFolder.listFiles()).hasSize(8); P4Material otherMaterial = p4Fixture.material("//depot/lib/... //something/..."); updateMaterial(otherMaterial, new StringRevision("2")); assertThat(clientFolder.listFiles()).hasSize(2); } private void updateMaterial(P4Material p4Material, StringRevision revision) { p4Material.updateTo(outputconsumer, clientFolder, new RevisionContext(revision), new TestSubprocessExecutionContext()); } @Test void shouldCreateUniqueClientForDifferentFoldersOnTheSameMachine() { P4Material p4Material = p4Fixture.material(VIEW); String name1 = p4Material.clientName(new File("/one-directory/foo/with_underlines")); String name2 = p4Material.clientName(new File("/another-directory/foo/with_underlines")); assertThat(name1).isNotEqualTo(name2); assertThat(name1.matches("[0-9a-zA-Z_\\.\\-]*")).as("Client name should be a legal filename: " + name1).isTrue(); assertThat(name2.matches("[0-9a-zA-Z_\\.\\-]*")).as("Client name should be a legal filename: " + name2).isTrue(); } @Test void hashCodeShouldBeSameWhenP4MaterialEquals() { P4Material p4 = p4Fixture.material("material1"); P4Material anotherP4 = p4Fixture.material("material1"); assertThat(p4).isEqualTo(anotherP4); assertThat(p4.hashCode()).isEqualTo(anotherP4.hashCode()); } @Test void shouldBeAbleToConvertToJson() { P4Material p4Material = p4Fixture.material(VIEW); Map<String, Object> json = new LinkedHashMap<>(); p4Material.toJson(json, new StringRevision("123")); JsonValue jsonValue = from(json); assertThat(jsonValue.getString("scmType")).isEqualTo("Perforce"); assertThat(jsonValue.getString("location")).isEqualTo(p4Material.getServerAndPort()); assertThat(jsonValue.getString("action")).isEqualTo("Modified"); } @Test void shouldLogRepoInfoToConsoleOutWithoutFolder() { P4Material p4Material = p4Fixture.material(VIEW); updateMaterial(p4Material, new StringRevision("2")); String message = format("Start updating %s at revision %s from %s", "files", "2", p4Material.getUrl()); assertThat(outputconsumer.getStdOut()).contains(message); } @Test void shouldGenerateSqlCriteriaMapInSpecificOrder() { Map<String, Object> map = p4Fixture.material("view").getSqlCriteria(); assertThat(map.size()).isEqualTo(4); Iterator<Map.Entry<String, Object>> iter = map.entrySet().iterator(); assertThat(iter.next().getKey()).isEqualTo("type"); assertThat(iter.next().getKey()).isEqualTo("url"); assertThat(iter.next().getKey()).isEqualTo("username"); assertThat(iter.next().getKey()).isEqualTo("view"); } }
{ "pile_set_name": "Github" }
#!/bin/bash set -e npm stop && npm start
{ "pile_set_name": "Github" }
/** ****************************************************************************** * @file rtl_trace.c * @author * @version V1.0.0 * @date 2016-05-17 * @brief This file contains all the functions for log print and mask. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2015, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "ameba_soc.h" SRAM_NOCACHE_DATA_SECTION u32 log_buffer_start; SRAM_NOCACHE_DATA_SECTION u32 log_buffer_end; SRAM_NOCACHE_DATA_SECTION TaskHandle_t log_buffer_thread_handle; #if defined (ARM_CORE_CM4) u32 LOG_PRINTF_BUFFER(const char *fmt) { /* To avoid gcc warnings */ ( void ) fmt; IPC_TypeDef *IPC0 = IPCM0_DEV; u32 write_pointer = IPC0->IPCx_USR[IPC_USER_BUF_LOG_WP]; u32 read_pointer = IPC0->IPCx_USR[IPC_USER_BUF_LOG_RP]; u32 write_pointer_next = 0; write_pointer_next = write_pointer + sizeof(log_buffer_t); if (write_pointer_next > log_buffer_end) { write_pointer_next = log_buffer_start; } /* write pointer catch up with read pointer, wait */ while (1) { read_pointer = IPC0->IPCx_USR[IPC_USER_BUF_LOG_RP]; if (write_pointer_next != read_pointer) break; } /* make sure write pointer buffer is empty */ IPC0->IPCx_USR[IPC_USER_BUF_LOG_WP] = write_pointer_next; //DiagPrintfD("LOG_PRINTF_BUFFER: %x\n", IPC0->IPCx_USR[IPC_USER_BUF_LOG_WP]); return (write_pointer); } u32 LOG_PRINTF_BUFFER_INIT(u32 thread_init) { /* To avoid gcc wanrings */ ( void ) thread_init; IPC_TypeDef *IPC0 = IPCM0_DEV; log_buffer_start = IPC0->IPCx_USR[IPC_USER_BUF_LOG_RP]; if (log_buffer_start == 0) { DBG_8195A("KM0 dont open logbuf \n"); return 0; } log_buffer_end = log_buffer_start + (LOG_BUFFER_NUM - 1) * sizeof(log_buffer_t); ConfigDebugBufferGet = LOG_PRINTF_BUFFER; DBG_8195A("LOG_PRINTF_BUFFER_INIT KM4 %x %x\n", log_buffer_start, log_buffer_end); /* open/close in CmdLogBuf */ ConfigDebugBuffer = 1; return 0; } #else /* reserve one to avoid memory overflow */ SRAM_NOCACHE_DATA_SECTION log_buffer_t log_buffer[LOG_BUFFER_NUM + 1]; static VOID LOG_BUFF_TASK(VOID *Data) { /* To avoid gcc warnings */ ( void ) Data; IPC_TypeDef *IPC0 = IPCM0_DEV; u32 write_pointer = IPC0->IPCx_USR[IPC_USER_BUF_LOG_WP]; u32 read_pointer = IPC0->IPCx_USR[IPC_USER_BUF_LOG_RP]; do { //DBG_8195A("write_pointer:%x read_pointer:%x \n", IPC0->IPCx_USR[IPC_USER_BUF_LOG_WP], // IPC0->IPCx_USR[IPC_USER_BUF_LOG_RP]); /* read pointer catch up with write pointer, wait */ while (1) { write_pointer = IPC0->IPCx_USR[IPC_USER_BUF_LOG_WP]; if ((write_pointer != read_pointer) && (write_pointer != 0)) break; taskYIELD(); } DiagPrintf((const char *)read_pointer); read_pointer = (read_pointer + sizeof(log_buffer_t)); if (read_pointer > log_buffer_end) { read_pointer = log_buffer_start; } IPC0->IPCx_USR[IPC_USER_BUF_LOG_RP] = read_pointer; } while(1); } u32 LOG_PRINTF_BUFFER_INIT(u32 thread_init) { (void) thread_init; #if 0 IPC_TypeDef *IPC0 = IPCM0_DEV; log_buffer_thread_handle = NULL; return 0; /* init read/write pointer */ IPC0->IPCx_USR[IPC_USER_BUF_LOG_WP] = (u32)&log_buffer[0]; /* write_pointer */ IPC0->IPCx_USR[IPC_USER_BUF_LOG_RP] = (u32)&log_buffer[0]; /* read_pointer */ log_buffer_end = (u32)&log_buffer[LOG_BUFFER_NUM-1]; log_buffer_start = (u32)&log_buffer[0]; log_buffer[0].buffer[0]='\0'; DBG_8195A("LOG_PRINTF_BUFFER_INIT %x %x %x\n", IPC0->IPCx_USR[IPC_USER_BUF_LOG_WP], \ IPC0->IPCx_USR[IPC_USER_BUF_LOG_RP], log_buffer_end); if (!thread_init) return 0; /* init thread, low-priority */ if (pdTRUE != xTaskCreate(LOG_BUFF_TASK, (const char * const)"LOGBUFF_TASK", 128, NULL, tskIDLE_PRIORITY + 3 , &log_buffer_thread_handle)) { DiagPrintf("CreateLOGBUFF_TASK Err!!\n"); } #endif return 0; } u32 LOG_BUFF_SUSPEND(void) { if (log_buffer_thread_handle) { vTaskSuspend(log_buffer_thread_handle); } return TRUE; } u32 LOG_BUFF_RESUME(void) { if (log_buffer_thread_handle) { vTaskResume(log_buffer_thread_handle); } return TRUE; } #endif /******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
{ "pile_set_name": "Github" }
<div ng-if="me.input.$dirty" class="field-validation-error" ng-messages="me.input.$error" role="alert"> <!-- Validation based on input type --> <div ng-message="date">Value of {{me.display}} field is not a valid date.</div> <div ng-message="datetimelocal">Value of {{me.display}} field is not a valid date-time.</div> <div ng-message="email">Value of {{me.display}} field is not a valid email.</div> <div ng-message="month">Value of {{me.display}} field is not a valid month.</div> <div ng-message="number">Value of {{me.display}} field is not a valid number.</div> <div ng-message="time">Value of {{me.display}} field is not a valid time.</div> <div ng-message="url">Value of {{me.display}} field is not a valid url.</div> <div ng-message="week">Value of {{me.display}} field is not a valid week.</div> <!-- Validation based on input attributes --> <div ng-message="required">{{me.display}} field is required.</div> <div ng-message="min">{{me.display}} field {{me.minError}}.</div> <div ng-message="max">{{me.display}} field {{me.maxError}}.</div> <div ng-message="minlength">{{me.display}} field {{me.minLengthError}}.</div> <div ng-message="maxlength">{{me.display}} field {{me.maxLengthError}}.</div> <div ng-message="pattern">{{me.patternError}}.</div> </div>
{ "pile_set_name": "Github" }
# # 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. from unittest import mock from oslo_config import cfg import swiftclient.client as sc from heat.common import exception from heat.common import template_format from heat.engine.resources.aws.s3 import s3 from heat.engine import scheduler from heat.tests import common from heat.tests import utils swift_template = ''' { "AWSTemplateFormatVersion" : "2010-09-09", "Description" : "Template to test S3 Bucket resources", "Resources" : { "S3BucketWebsite" : { "Type" : "AWS::S3::Bucket", "DeletionPolicy" : "Delete", "Properties" : { "AccessControl" : "PublicRead", "WebsiteConfiguration" : { "IndexDocument" : "index.html", "ErrorDocument" : "error.html" } } }, "SwiftContainer": { "Type": "OS::Swift::Container", "Properties": { "S3Bucket": {"Ref" : "S3Bucket"}, } }, "S3Bucket" : { "Type" : "AWS::S3::Bucket", "Properties" : { "AccessControl" : "Private" } }, "S3Bucket_with_tags" : { "Type" : "AWS::S3::Bucket", "Properties" : { "Tags" : [{"Key": "greeting", "Value": "hello"}, {"Key": "location", "Value": "here"}] } } } } ''' class s3Test(common.HeatTestCase): def setUp(self): super(s3Test, self).setUp() self.mock_con = mock.Mock(spec=sc.Connection) self.patchobject(s3.S3Bucket, 'client', return_value=self.mock_con) def create_resource(self, t, stack, resource_name): resource_defns = stack.t.resource_definitions(stack) rsrc = s3.S3Bucket('test_resource', resource_defns[resource_name], stack) scheduler.TaskRunner(rsrc.create)() self.assertEqual((rsrc.CREATE, rsrc.COMPLETE), rsrc.state) return rsrc def test_attributes(self): t = template_format.parse(swift_template) stack = utils.parse_stack(t) container_name = utils.PhysName(stack.name, 'test_resource') self.mock_con.put_container.return_value = None self.mock_con.get_auth.return_value = ( 'http://server.test:8080/v_2', None) self.mock_con.delete_container.return_value = None rsrc = self.create_resource(t, stack, 'S3Bucket') ref_id = rsrc.FnGetRefId() self.assertEqual(container_name, ref_id) self.assertEqual('server.test', rsrc.FnGetAtt('DomainName')) url = 'http://server.test:8080/v_2/%s' % ref_id self.assertEqual(url, rsrc.FnGetAtt('WebsiteURL')) self.assertRaises(exception.InvalidTemplateAttribute, rsrc.FnGetAtt, 'Foo') scheduler.TaskRunner(rsrc.delete)() self.mock_con.put_container.assert_called_once_with( container_name, {'X-Container-Write': 'test_tenant:test_username', 'X-Container-Read': 'test_tenant:test_username'} ) self.mock_con.get_auth.assert_called_with() self.assertEqual(2, self.mock_con.get_auth.call_count) self.mock_con.delete_container.assert_called_once_with(container_name) def test_public_read(self): t = template_format.parse(swift_template) properties = t['Resources']['S3Bucket']['Properties'] properties['AccessControl'] = 'PublicRead' stack = utils.parse_stack(t) container_name = utils.PhysName(stack.name, 'test_resource') self.mock_con.put_container.return_value = None self.mock_con.delete_container.return_value = None rsrc = self.create_resource(t, stack, 'S3Bucket') scheduler.TaskRunner(rsrc.delete)() self.mock_con.put_container.assert_called_once_with( utils.PhysName(stack.name, 'test_resource'), {'X-Container-Write': 'test_tenant:test_username', 'X-Container-Read': '.r:*'}) self.mock_con.delete_container.assert_called_once_with(container_name) def test_tags(self): t = template_format.parse(swift_template) stack = utils.parse_stack(t) container_name = utils.PhysName(stack.name, 'test_resource') self.mock_con.put_container.return_value = None self.mock_con.delete_container.return_value = None rsrc = self.create_resource(t, stack, 'S3Bucket_with_tags') scheduler.TaskRunner(rsrc.delete)() self.mock_con.put_container.assert_called_once_with( utils.PhysName(stack.name, 'test_resource'), {'X-Container-Write': 'test_tenant:test_username', 'X-Container-Read': 'test_tenant:test_username', 'X-Container-Meta-S3-Tag-greeting': 'hello', 'X-Container-Meta-S3-Tag-location': 'here'}) self.mock_con.delete_container.assert_called_once_with(container_name) def test_public_read_write(self): t = template_format.parse(swift_template) properties = t['Resources']['S3Bucket']['Properties'] properties['AccessControl'] = 'PublicReadWrite' stack = utils.parse_stack(t) container_name = utils.PhysName(stack.name, 'test_resource') self.mock_con.put_container.return_value = None self.mock_con.delete_container.return_value = None rsrc = self.create_resource(t, stack, 'S3Bucket') scheduler.TaskRunner(rsrc.delete)() self.mock_con.put_container.assert_called_once_with( container_name, {'X-Container-Write': '.r:*', 'X-Container-Read': '.r:*'}) self.mock_con.delete_container.assert_called_once_with(container_name) def test_authenticated_read(self): t = template_format.parse(swift_template) properties = t['Resources']['S3Bucket']['Properties'] properties['AccessControl'] = 'AuthenticatedRead' stack = utils.parse_stack(t) container_name = utils.PhysName(stack.name, 'test_resource') self.mock_con.put_container.return_value = None self.mock_con.delete_container.return_value = None rsrc = self.create_resource(t, stack, 'S3Bucket') scheduler.TaskRunner(rsrc.delete)() self.mock_con.put_container.assert_called_once_with( container_name, {'X-Container-Write': 'test_tenant:test_username', 'X-Container-Read': 'test_tenant'}) self.mock_con.delete_container.assert_called_once_with(container_name) def test_website(self): t = template_format.parse(swift_template) stack = utils.parse_stack(t) container_name = utils.PhysName(stack.name, 'test_resource') self.mock_con.put_container.return_value = None self.mock_con.delete_container.return_value = None rsrc = self.create_resource(t, stack, 'S3BucketWebsite') scheduler.TaskRunner(rsrc.delete)() self.mock_con.put_container.assert_called_once_with( container_name, {'X-Container-Meta-Web-Error': 'error.html', 'X-Container-Meta-Web-Index': 'index.html', 'X-Container-Write': 'test_tenant:test_username', 'X-Container-Read': '.r:*'}) self.mock_con.delete_container.assert_called_once_with(container_name) def test_delete_exception(self): t = template_format.parse(swift_template) stack = utils.parse_stack(t) container_name = utils.PhysName(stack.name, 'test_resource') self.mock_con.put_container.return_value = None self.mock_con.delete_container.side_effect = sc.ClientException( 'Test Delete Failure') rsrc = self.create_resource(t, stack, 'S3Bucket') self.assertRaises(exception.ResourceFailure, scheduler.TaskRunner(rsrc.delete)) self.mock_con.put_container.assert_called_once_with( container_name, {'X-Container-Write': 'test_tenant:test_username', 'X-Container-Read': 'test_tenant:test_username'}) self.mock_con.delete_container.assert_called_once_with(container_name) def test_delete_not_found(self): t = template_format.parse(swift_template) stack = utils.parse_stack(t) container_name = utils.PhysName(stack.name, 'test_resource') self.mock_con.put_container.return_value = None self.mock_con.delete_container.side_effect = sc.ClientException( 'Gone', http_status=404) rsrc = self.create_resource(t, stack, 'S3Bucket') scheduler.TaskRunner(rsrc.delete)() self.mock_con.put_container.assert_called_once_with( container_name, {'X-Container-Write': 'test_tenant:test_username', 'X-Container-Read': 'test_tenant:test_username'}) self.mock_con.delete_container.assert_called_once_with(container_name) def test_delete_conflict_not_empty(self): t = template_format.parse(swift_template) stack = utils.parse_stack(t) container_name = utils.PhysName(stack.name, 'test_resource') self.mock_con.put_container.return_value = None self.mock_con.delete_container.side_effect = sc.ClientException( 'Not empty', http_status=409) self.mock_con.get_container.return_value = ( {'name': container_name}, [{'name': 'test_object'}]) rsrc = self.create_resource(t, stack, 'S3Bucket') deleter = scheduler.TaskRunner(rsrc.delete) ex = self.assertRaises(exception.ResourceFailure, deleter) self.assertIn("ResourceActionNotSupported: resources.test_resource: " "The bucket you tried to delete is not empty", str(ex)) self.mock_con.put_container.assert_called_once_with( container_name, {'X-Container-Write': 'test_tenant:test_username', 'X-Container-Read': 'test_tenant:test_username'}) self.mock_con.delete_container.assert_called_once_with(container_name) self.mock_con.get_container.assert_called_once_with(container_name) def test_delete_conflict_empty(self): cfg.CONF.set_override('action_retry_limit', 0) t = template_format.parse(swift_template) stack = utils.parse_stack(t) container_name = utils.PhysName(stack.name, 'test_resource') self.mock_con.put_container.return_value = None self.mock_con.delete_container.side_effect = sc.ClientException( 'Conflict', http_status=409) self.mock_con.get_container.return_value = ( {'name': container_name}, []) rsrc = self.create_resource(t, stack, 'S3Bucket') deleter = scheduler.TaskRunner(rsrc.delete) ex = self.assertRaises(exception.ResourceFailure, deleter) self.assertIn("Conflict", str(ex)) self.mock_con.put_container.assert_called_once_with( container_name, {'X-Container-Write': 'test_tenant:test_username', 'X-Container-Read': 'test_tenant:test_username'}) self.mock_con.delete_container.assert_called_once_with(container_name) self.mock_con.get_container.assert_called_once_with(container_name) def test_delete_retain(self): t = template_format.parse(swift_template) bucket = t['Resources']['S3Bucket'] bucket['DeletionPolicy'] = 'Retain' stack = utils.parse_stack(t) # first run, with retain policy self.mock_con.put_container.return_value = None rsrc = self.create_resource(t, stack, 'S3Bucket') scheduler.TaskRunner(rsrc.delete)() self.assertEqual((rsrc.DELETE, rsrc.COMPLETE), rsrc.state) self.mock_con.put_container.assert_called_once_with( utils.PhysName(stack.name, 'test_resource'), {'X-Container-Write': 'test_tenant:test_username', 'X-Container-Read': 'test_tenant:test_username'})
{ "pile_set_name": "Github" }
/* * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.glass.events.mac; import java.lang.annotation.Native; import java.util.Map; import com.sun.glass.ui.Window; // https://wiki.mozilla.org/NPAPI:CocoaEventModel // used by Mac OS X impl for handling an NPAPI event sent from plugin to Glass process public class NpapiEvent { // draw @Native final static public int NPCocoaEventDrawRect = 1; // mouse @Native final static public int NPCocoaEventMouseDown = 2; @Native final static public int NPCocoaEventMouseUp = 3; @Native final static public int NPCocoaEventMouseMoved = 4; @Native final static public int NPCocoaEventMouseEntered = 5; @Native final static public int NPCocoaEventMouseExited = 6; @Native final static public int NPCocoaEventMouseDragged = 7; // key @Native final static public int NPCocoaEventKeyDown = 8; @Native final static public int NPCocoaEventKeyUp = 9; @Native final static public int NPCocoaEventFlagsChanged = 10; // focus @Native final static public int NPCocoaEventFocusChanged = 11; @Native final static public int NPCocoaEventWindowFocusChanged = 12; // mouse @Native final static public int NPCocoaEventScrollWheel = 13; // text input @Native final static public int NPCocoaEventTextInput = 14; private native static void _dispatchCocoaNpapiDrawEvent(long windowPtr, int type, long context, double x, double y, double width, double height); private native static void _dispatchCocoaNpapiMouseEvent(long windowPtr, int type, int modifierFlags, double pluginX, double pluginY, int buttonNumber, int clickCount, double deltaX, double deltaY, double deltaZ); private native static void _dispatchCocoaNpapiKeyEvent(long windowPtr, int type, int modifierFlags, String characters, String charactersIgnoringModifiers, boolean isARepeat, int keyCode, boolean needsKeyTyped); private native static void _dispatchCocoaNpapiFocusEvent(long windowPtr, int type, boolean hasFocus); private native static void _dispatchCocoaNpapiTextInputEvent(long windowPtr, int type, String text); final private static boolean getBoolean(Map eventInfo, String key) { boolean value = false; { if (eventInfo.containsKey(key) == true ) { try { value = ((Boolean)eventInfo.get(key)).booleanValue(); } catch (Exception e) { e.printStackTrace(); } } } return value; } final private static int getInt(Map eventInfo, String key) { int value = 0; { if (eventInfo.containsKey(key) == true ) { try { value = ((Integer)eventInfo.get(key)).intValue(); } catch (Exception e) { e.printStackTrace(); } } } return value; } final private static long getLong(Map eventInfo, String key) { long value = 0; { if (eventInfo.containsKey(key) == true ) { try { value = ((Long)eventInfo.get(key)).longValue(); } catch (Exception e) { e.printStackTrace(); } } } return value; } final private static double getDouble(Map eventInfo, String key) { double value = 0; { if (eventInfo.containsKey(key) == true ) { try { value = ((Double)eventInfo.get(key)).doubleValue(); } catch (Exception e) { e.printStackTrace(); } } } return value; } final private static String getString(Map eventInfo, String key) { String value = null; { if (eventInfo.containsKey(key) == true ) { try { value = (String)eventInfo.get(key); } catch (Exception e) { e.printStackTrace(); } } } return value; } public static void dispatchCocoaNpapiEvent(Window window, Map eventInfo) { final long windowPtr = window.getNativeWindow(); //System.err.println(">>>>>>>>>>>>>>>>>>>>>>> eventInfo: "+eventInfo); int type = ((Integer)eventInfo.get("type")).intValue(); switch (type) { case NPCocoaEventDrawRect: { long context = getLong(eventInfo, "context"); double x = getDouble(eventInfo, "x"); double y = getDouble(eventInfo, "y"); double width = getDouble(eventInfo, "width"); double height = getDouble(eventInfo, "height"); _dispatchCocoaNpapiDrawEvent(windowPtr, type, context, x, y, width, height); } break; case NPCocoaEventMouseDown: case NPCocoaEventMouseUp: case NPCocoaEventMouseMoved: case NPCocoaEventMouseEntered: case NPCocoaEventMouseExited: case NPCocoaEventMouseDragged: case NPCocoaEventScrollWheel: { int modifierFlags = getInt(eventInfo, "modifierFlags"); double pluginX = getDouble(eventInfo, "pluginX"); double pluginY = getDouble(eventInfo, "pluginY"); int buttonNumber = getInt(eventInfo, "buttonNumber"); int clickCount = getInt(eventInfo, "clickCount"); double deltaX = getDouble(eventInfo, "deltaX"); double deltaY = getDouble(eventInfo, "deltaY"); double deltaZ = getDouble(eventInfo, "deltaZ"); _dispatchCocoaNpapiMouseEvent(windowPtr, type, modifierFlags, pluginX, pluginY, buttonNumber, clickCount, deltaX, deltaY, deltaZ); } break; case NPCocoaEventKeyDown: case NPCocoaEventKeyUp: case NPCocoaEventFlagsChanged: { int modifierFlags = getInt(eventInfo, "modifierFlags"); String characters = getString(eventInfo, "characters"); String charactersIgnoringModifiers = getString(eventInfo, "charactersIgnoringModifiers"); boolean isARepeat = getBoolean(eventInfo, "isARepeat"); int keyCode = getInt(eventInfo, "keyCode"); boolean needsKeyTyped = getBoolean(eventInfo, "needsKeyTyped"); _dispatchCocoaNpapiKeyEvent(windowPtr, type, modifierFlags, characters, charactersIgnoringModifiers, isARepeat, keyCode, needsKeyTyped); } break; case NPCocoaEventFocusChanged: case NPCocoaEventWindowFocusChanged: { boolean hasFocus = getBoolean(eventInfo, "hasFocus"); _dispatchCocoaNpapiFocusEvent(windowPtr, type, hasFocus); } break; case NPCocoaEventTextInput: { String text = getString(eventInfo, "text"); _dispatchCocoaNpapiTextInputEvent(windowPtr, type, text); } break; } } }
{ "pile_set_name": "Github" }
// Package devlogger provides an implementation of a syslog server to be used // for dev environments. package devlogger import ( "fmt" "strings" "time" "github.com/leveros/go-syslog" "github.com/leveros/leveros/config" "github.com/leveros/leveros/leverutil" "github.com/leveros/leveros/scale" ) // PackageName is the name of this package. const PackageName = "devlogger" var ( // DevLoggerListenPortFlag is the port to listen to for syslog messages. DevLoggerListenPortFlag = config.DeclareString( PackageName, "devLoggerListenPort", "6514") // InstanceIDFlag is the instance ID of the devlogger. Note: This is a // different instance ID than leverutil.InstanceIDFlag because they serve // different things. InstanceIDFlag = config.DeclareString( PackageName, "instanceID", leverutil.RandomID()) // DisableFlag disables the devlogger server. DisableFlag = config.DeclareBool(PackageName, "disable") ) var logger = leverutil.GetLogger(PackageName, "DevLogger") // DevLoggerService is the name of the devlogger internal service. const DevLoggerService = "devlogger" // DevLogger is a syslog server meant to be used only for dev instances of // Lever. It doesn't have the necessary redundancy and safeguards in place for // production use. type DevLogger struct { server *syslog.Server serviceSKA *scale.SelfKeepAlive channel syslog.LogPartsChannel } // NewDevLogger returns a new DevLogger. func NewDevLogger(ownIP string) (*DevLogger, error) { if DisableFlag.Get() { return nil, nil } dl := &DevLogger{ server: syslog.NewServer(), channel: make(syslog.LogPartsChannel), } dl.server.SetFormat(syslog.RFC5424) dl.server.SetHandler(syslog.NewChannelHandler(dl.channel)) dl.server.ListenTCP("0.0.0.0:" + DevLoggerListenPortFlag.Get()) err := dl.server.Boot() if err != nil { return nil, err } go dl.worker() // Register service. instanceID := InstanceIDFlag.Get() serviceAddr := ownIP + ":" + DevLoggerListenPortFlag.Get() serviceTTL := 30 * time.Second err = scale.RegisterServiceLocal( DevLoggerService, instanceID, serviceAddr, serviceTTL) if err != nil { dl.server.Kill() close(dl.channel) return nil, err } dl.serviceSKA = scale.NewServiceSelfKeepAlive(instanceID, serviceTTL/2) return dl, nil } // Close closes the server. func (dl *DevLogger) Close() { dl.serviceSKA.Stop() err := scale.DeregisterService(InstanceIDFlag.Get()) if err != nil { logger.WithFields("err", err).Error( "Error deregistering devlogger service") } dl.server.Kill() close(dl.channel) } func (dl *DevLogger) worker() { for logParts := range dl.channel { // TODO: Do something useful with the log lines. var prefix string tag, ok := logParts["app_name"].(string) if ok { tagParts := strings.Split(tag, "/") if len(tagParts) == 5 { env, service, codeVersion := tagParts[1], tagParts[2], tagParts[3] prefix = fmt.Sprintf( "lever://%s/%s v%s", env, service, codeVersion) } else { logger.WithFields("parts", logParts).Debug( "Could not parse tag") } } else { logger.WithFields("parts", logParts).Debug("Could not parse tag") } logger.WithFields("prefix", prefix).Info(logParts["message"].(string)) } }
{ "pile_set_name": "Github" }
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package arm64 // This order should be strictly consistent to that in a.out.go var cnames7 = []string{ "NONE", "REG", "RSP", "FREG", "VREG", "PAIR", "SHIFT", "EXTREG", "SPR", "COND", "ARNG", "ELEM", "LIST", "ZCON", "ABCON0", "ADDCON0", "ABCON", "AMCON", "ADDCON", "MBCON", "MOVCON", "BITCON", "ADDCON2", "LCON", "MOVCON2", "MOVCON3", "VCON", "FCON", "VCONADDR", "AACON", "LACON", "AECON", "SBRA", "LBRA", "ZAUTO", "NSAUTO_8", "NSAUTO_4", "NSAUTO", "NPAUTO", "NAUTO4K", "PSAUTO_8", "PSAUTO_4", "PSAUTO", "PPAUTO", "UAUTO4K_8", "UAUTO4K_4", "UAUTO4K_2", "UAUTO4K", "UAUTO8K_8", "UAUTO8K_4", "UAUTO8K", "UAUTO16K_8", "UAUTO16K", "UAUTO32K", "LAUTO", "SEXT1", "SEXT2", "SEXT4", "SEXT8", "SEXT16", "LEXT", "ZOREG", "NSOREG_8", "NSOREG_4", "NSOREG", "NPOREG", "NOREG4K", "PSOREG_8", "PSOREG_4", "PSOREG", "PPOREG", "UOREG4K_8", "UOREG4K_4", "UOREG4K_2", "UOREG4K", "UOREG8K_8", "UOREG8K_4", "UOREG8K", "UOREG16K_8", "UOREG16K", "UOREG32K", "LOREG", "ADDR", "GOTADDR", "TLS_LE", "TLS_IE", "ROFF", "GOK", "TEXTSIZE", "NCLASS", }
{ "pile_set_name": "Github" }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.samza.util; import java.util.HashMap; import java.util.Map; import org.apache.samza.config.Config; import org.apache.samza.config.ConfigException; import org.apache.samza.config.JobConfig; import org.apache.samza.config.MapConfig; import org.junit.Test; import static org.junit.Assert.*; public class TestDefaultCoordinatorStreamConfigFactory { DefaultCoordinatorStreamConfigFactory factory = new DefaultCoordinatorStreamConfigFactory(); @Test public void testBuildCoordinatorStreamConfigWithJobName() { Map<String, String> mapConfig = new HashMap<>(); mapConfig.put("job.name", "testName"); mapConfig.put("job.id", "testId"); mapConfig.put("job.coordinator.system", "testSamza"); mapConfig.put("test.only", "nothing"); mapConfig.put("systems.testSamza.test", "test"); Config config = factory.buildCoordinatorStreamConfig(new MapConfig(mapConfig)); Map<String, String> expectedMap = new HashMap<>(); expectedMap.put("job.name", "testName"); expectedMap.put("job.id", "testId"); expectedMap.put("systems.testSamza.test", "test"); expectedMap.put(JobConfig.JOB_COORDINATOR_SYSTEM, "testSamza"); expectedMap.put(JobConfig.MONITOR_PARTITION_CHANGE_FREQUENCY_MS, "300000"); assertEquals(config, new MapConfig(expectedMap)); } @Test(expected = ConfigException.class) public void testBuildCoordinatorStreamConfigWithoutJobName() { Map<String, String> mapConfig = new HashMap<>(); mapConfig.put("job.id", "testId"); mapConfig.put("job.coordinator.system", "testSamza"); mapConfig.put("test.only", "nothing"); mapConfig.put("systems.testSamza.test", "test"); factory.buildCoordinatorStreamConfig(new MapConfig(mapConfig)); } }
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class SyntaxBinderTests : CompilingTestBase { [Fact, WorkItem(544450, "DevDiv")] public void TestBug12780() { string source = @" enum E : byte { A, B } class Program { static void Main() { E? x = 0; System.Console.Write(x); x = (E?) E.B; System.Console.Write(x); } } "; var verifier = CompileAndVerify(source: source, expectedOutput: "AB"); } [Fact] public void TestNullableConversions() { // IntPtr and UIntPtr violate the rules of user-defined conversions for // backwards-compatibility reasons. All of these should compile without error. string source = @" using System; class P { public static void Main() { int? x = 123; long? y = x; V(x.HasValue); V(x.Value == 123); V((int)x == 123); V(y.HasValue); V(y.Value == 123); V((long)y == 123); V((int)y == 123); x = null; y = x; V(x.HasValue); V(y.HasValue); bool caught = false; try { y = (int) y; } catch { caught = true; } V(caught); } static void V(bool b) { Console.Write(b ? 't' : 'f'); } } "; string expectedOutput = @"tttttttfft"; var verifier = CompileAndVerify(source: source, expectedOutput: expectedOutput); } [Fact] public void TestLiftedUserDefinedConversions() { string source = @" struct Conv { public static implicit operator int(Conv c) { return 1; } // DELIBERATE SPEC VIOLATION: We allow 'lifting' even though the // return type is not a non-nullable value type. // UNDONE: Test pointer types public static implicit operator string(Conv c) { return '2'.ToString(); } public static implicit operator double?(Conv c) { return 123.0; } static void Main() { Conv? c = new Conv(); int? i = c; string s = c; double? d = c; V(i.HasValue); V(i == 1); V(s != null); V(s.Length == 1); V(s[0] == '2'); V(d.HasValue); V(d == 123.0); c = null; i = c; s = c; d = c; V(!i.HasValue); V(s == null); V(!d.HasValue); } static void V(bool f) { System.Console.Write(f ? 't' : 'f'); } } "; string expectedOutput = @"tttttttttt"; var verifier = CompileAndVerify(source: source, expectedOutput: expectedOutput); } [Fact, WorkItem(529279, "DevDiv")] public void TestNullableWithGenericConstraints01() { string source = @" class GenC<T, U> where T : struct, U where U : class { public void Test(T t) { T? nt = t; U valueUn = nt; System.Console.WriteLine(valueUn.ToString()); } } interface I1 { } struct S1 : I1 { public override string ToString() { return ""Hola""; } } static class Program { static void Main() { (new GenC<S1, I1>()).Test(default(S1)); } }"; CompileAndVerify(source, expectedOutput: "Hola"); } [Fact, WorkItem(543996, "DevDiv")] public void TestNonLiftedUDCOnStruct() { string source = @"using System; struct A { public C CFld; } class C { public A AFld; public static implicit operator A(C c) { return c.AFld; } public static explicit operator C(A a) { return a.CFld; } } public class Test { public static void Main() { A a = new A(); a.CFld = new C(); a.CFld.AFld = a; C c = a.CFld; A? nubA = c; // Assert here Console.Write(nubA.HasValue && nubA.Value.CFld == c); C nubC = (C)nubA; Console.Write(nubC.AFld.CFld == c); } } "; CompileAndVerify(source, expectedOutput: "TrueTrue"); } [Fact, WorkItem(543997, "DevDiv")] public void TestImplicitLiftedUDCOnStruct() { string source = @"using System; namespace Test { static class Program { static void Main() { S.v = 0; S? S2 = 123; // not lifted, int=>int?, int?=>S, S=>S? Console.WriteLine(S.v == 123); } } public struct S { public static int v; // s == null, return v = -1 public static implicit operator S(int? s) { Console.Write(""Imp S::int? -> S ""); S ss = new S(); S.v = s ?? -1; return ss; } } } "; CompileAndVerify(source, expectedOutput: "Imp S::int? -> S True"); } [Fact] public void TestExplicitUnliftedUDC() { string source = @" using System; namespace Test { static class Program { static void Main() { int? i = 123; C c = (C)i; Console.WriteLine(c.v == 123 ? 't' : 'f'); } } public class C { public readonly int v; public C(int v) { this.v = v; } public static implicit operator C(int v) { Console.Write(v); return new C(v); } } } "; CompileAndVerify(source, expectedOutput: "123t"); } [Fact, WorkItem(545091, "DevDiv")] public void TestImplicitUDCInNullCoalescingOperand() { string source = @"using System; class C { public static implicit operator C(string s) { Console.Write(""implicit ""); return new C(); } public override string ToString() { return ""C""; } } class A { static void Main() { var ret = ""str"" ?? new C(); Console.Write(ret.GetType()); } } "; CompileAndVerify(source, expectedOutput: "implicit C"); } [WorkItem(545377, "DevDiv")] [Fact] public void TestLiftedVsUnlifted() { // The correct behaviour here is to choose operator 2. Binary operator overload // resolution should determine that the best built-in addition operator is // lifted int + int, which has signature int? + int? --> int?. However, the // native compiler gets this wrong. The native compiler, pretends // that there are *three* lifted operators: int + int? --> int?, int? + int --> int?, // and int? + int? --> int?. Therefore the native compiler decides that the // int? + int --> int operator is the best, because it is the applicable operator // with the most specific types, and therefore chooses operator 1. // // This does not match the specification. // It seems reasonable that if someone has done this very strange thing of making // conversions S --> int and S --> int?, that they probably intend for the // lifted operation to use the conversion specifically designed for nullables. // // Roslyn matches the specification and takes the break from the native compiler. // See the next test case for more thoughts on this. string source = @" using System; public struct S { public static implicit operator int(S n) // 1 native compiler { Console.WriteLine(1); return 0; } public static implicit operator int?(S n) // 2 Roslyn compiler { Console.WriteLine(2); return null; } public static void Main() { int? qa = 5; S b = default(S); var sum = qa + b; } } "; CompileAndVerify(source, expectedOutput: "2"); } [WorkItem(545377, "DevDiv")] [Fact] public void TestLiftedVsUnlifted_Combinations() { // The point of this test is to show that Roslyn and the native compiler // agree on resolution of *conversions* but do not agree on resolution // of *binary operators*. That is, we wish to show that we are isolating // the breaking change to the binary operator overload resolution, and not // to the conversion resolution code. See the previous bug for details. string source = @" using System; struct S___A { public static implicit operator int(S___A n) { Console.Write('A'); return 0; } } struct S__B_ { public static implicit operator int(S__B_? n) { Console.Write('B'); return 0; } } struct S__BA { public static implicit operator int(S__BA? n) { Console.Write('B'); return 0; } public static implicit operator int(S__BA n) { Console.Write('A'); return 0; } } struct S_C__ { public static implicit operator int?(S_C__ n) { Console.Write('C'); return 0; } } struct S_C_A { public static implicit operator int?(S_C_A n) { Console.Write('C'); return 0; } public static implicit operator int(S_C_A n) { Console.Write('A'); return 0; } } struct S_CB_ { public static implicit operator int?(S_CB_ n) { Console.Write('C'); return 0; } public static implicit operator int(S_CB_? n) { Console.Write('B'); return 0; } } struct S_CBA { public static implicit operator int?(S_CBA n) { Console.Write('C'); return 0; } public static implicit operator int(S_CBA? n) { Console.Write('B'); return 0; } public static implicit operator int(S_CBA n) { Console.Write('A'); return 0; } } struct SD___ { public static implicit operator int?(SD___? n){ Console.Write('D'); return 0; } } struct SD__A { public static implicit operator int?(SD__A? n){ Console.Write('D'); return 0; } public static implicit operator int(SD__A n) { Console.Write('A'); return 0; } } struct SD_B_ { public static implicit operator int?(SD_B_? n){ Console.Write('D'); return 0; } public static implicit operator int(SD_B_? n) { Console.Write('B'); return 0; } } struct SD_BA { public static implicit operator int?(SD_BA? n){ Console.Write('D'); return 0; } public static implicit operator int(SD_BA? n) { Console.Write('B'); return 0; } public static implicit operator int(SD_BA n) { Console.Write('A'); return 0; } } struct SDC__ { public static implicit operator int?(SDC__? n){ Console.Write('D'); return 0; } public static implicit operator int?(SDC__ n) { Console.Write('C'); return 0; } } struct SDC_A { public static implicit operator int?(SDC_A? n){ Console.Write('D'); return 0; } public static implicit operator int?(SDC_A n) { Console.Write('C'); return 0; } public static implicit operator int(SDC_A n) { Console.Write('A'); return 0; } } struct SDCB_ { public static implicit operator int?(SDCB_? n){ Console.Write('D'); return 0; } public static implicit operator int?(SDCB_ n) { Console.Write('C'); return 0; } public static implicit operator int(SDCB_? n) { Console.Write('B'); return 0; } } struct SDCBA { public static implicit operator int?(SDCBA? n){ Console.Write('D'); return 0; } public static implicit operator int?(SDCBA n) { Console.Write('C'); return 0; } public static implicit operator int(SDCBA? n) { Console.Write('B'); return 0; } public static implicit operator int(SDCBA n) { Console.Write('A'); return 0; } } class Program { static S___A s___a1; static S__B_ s__b_1; static S__BA s__ba1; static S_C__ s_c__1; static S_C_A s_c_a1; static S_CB_ s_cb_1; static S_CBA s_cba1; static SD___ sd___1; static SD__A sd__a1; static SD_B_ sd_b_1; static SD_BA sd_ba1; static SDC__ sdc__1; static SDC_A sdc_a1; static SDCB_ sdcb_1; static SDCBA sdcba1; static S___A? s___a2; static S__B_? s__b_2; static S__BA? s__ba2; static S_C__? s_c__2; static S_C_A? s_c_a2; static S_CB_? s_cb_2; static S_CBA? s_cba2; static SD___? sd___2; static SD__A? sd__a2; static SD_B_? sd_b_2; static SD_BA? sd_ba2; static SDC__? sdc__2; static SDC_A? sdc_a2; static SDCB_? sdcb_2; static SDCBA? sdcba2; static int i1 = 0; static int? i2 = 0; static void Main() { TestConversions(); Console.WriteLine(); TestAdditions(); } static void TestConversions() { i1 = s___a1; i1 = s__b_1; i1 = s__ba1; // i1 = s_c__1; i1 = s_c_a1; i1 = s_cb_1; i1 = s_cba1; // i1 = sd___1; i1 = sd__a1; i1 = sd_b_1; i1 = sd_ba1; // i1 = sdc__1; i1 = sdc_a1; i1 = sdcb_1; i1 = sdcba1; // i1 = s___a2; i1 = s__b_2; i1 = s__ba2; // i1 = s_c__2; // i1 = s_c_a2; i1 = s_cb_2; i1 = s_cba2; //i1 = sd___2; //i1 = sd__a2; i1 = sd_b_2; i1 = sd_ba2; //i1 = sdc__2; //i1 = sdc_a2; i1 = sdcb_2; i1 = sdcba2; i2 = s___a1; i2 = s__b_1; i2 = s__ba1; i2 = s_c__1; i2 = s_c_a1; i2 = s_cb_1; i2 = s_cba1; i2 = sd___1; i2 = sd__a1; i2 = sd_b_1; i2 = sd_ba1; i2 = sdc__1; i2 = sdc_a1; i2 = sdcb_1; i2 = sdcba1; i2 = s___a2; i2 = s__b_2; i2 = s__ba2; i2 = s_c__2; i2 = s_c_a2; //i2 = s_cb_2; //i2 = s_cba2; i2 = sd___2; i2 = sd__a2; i2 = sd_b_2; i2 = sd_ba2; i2 = sdc__2; i2 = sdc_a2; i2 = sdcb_2; i2 = sdcba2; } static void TestAdditions() { i2 = i1 + s___a1; i2 = i1 + s__b_1; i2 = i1 + s__ba1; i2 = i1 + s_c__1; i2 = i1 + s_c_a1; i2 = i1 + s_cb_1; i2 = i1 + s_cba1; i2 = i1 + sd___1; i2 = i1 + sd__a1; i2 = i1 + sd_b_1; i2 = i1 + sd_ba1; i2 = i1 + sdc__1; i2 = i1 + sdc_a1; i2 = i1 + sdcb_1; i2 = i1 + sdcba1; i2 = i1 + s___a2; i2 = i1 + s__b_2; i2 = i1 + s__ba2; i2 = i1 + s_c__2; i2 = i1 + s_c_a2; i2 = i1 + s_cb_2; i2 = i1 + s_cba2; i2 = i1 + sd___2; i2 = i1 + sd__a2; i2 = i1 + sd_b_2; i2 = i1 + sd_ba2; i2 = i1 + sdc__2; i2 = i1 + sdc_a2; i2 = i1 + sdcb_2; i2 = i1 + sdcba2; i2 = i2 + s___a1; i2 = i2 + s__b_1; i2 = i2 + s__ba1; i2 = i2 + s_c__1; i2 = i2 + s_c_a1; i2 = i2 + s_cb_1; i2 = i2 + s_cba1; i2 = i2 + sd___1; i2 = i2 + sd__a1; i2 = i2 + sd_b_1; i2 = i2 + sd_ba1; i2 = i2 + sdc__1; i2 = i2 + sdc_a1; i2 = i2 + sdcb_1; i2 = i2 + sdcba1; i2 = i2 + s___a2; i2 = i2 + s__b_2; i2 = i2 + s__ba2; i2 = i2 + s_c__2; i2 = i2 + s_c_a2; // i2 = i2 + s_cb_2; // Native compiler allows these because it actually converts to int, // i2 = i2 + s_cba2; // not int?, which is not ambiguous. Roslyn takes the breaking change. i2 = i2 + sd___2; i2 = i2 + sd__a2; i2 = i2 + sd_b_2; i2 = i2 + sd_ba2; i2 = i2 + sdc__2; i2 = i2 + sdc_a2; i2 = i2 + sdcb_2; i2 = i2 + sdcba2; } } "; var compilation = CreateCompilationWithMscorlib(source, options: TestOptions.ReleaseExe.WithWarningLevel(0)); // Roslyn and native compiler both produce ABAABAABAABABBBBBBBBABACCCCDADACCCCBBDDDDDDDD // for straight conversions. // Because Roslyn (correctly) prefers converting to int? instead of int when doing lifted addition, // native compiler produces ABACABADABACABABBBBDDBBDDBBABACABADABACABABBDDBBDDBB for additions. // Roslyn compiler produces ABACABADABACABABBBBDDBBDDBBABACCCCDADACCCCBBDDDDDDDD. That is, // preference is given to int?-returning conversions C and D over int-returning A and B. string expected = @"ABAABAABAABABBBBBBBBABACCCCDADACCCCBBDDDDDDDD ABACABADABACABABBBBDDBBDDBBABACCCCDADACCCCBBDDDDDDDD"; CompileAndVerify(compilation, expectedOutput: expected); } [Fact] [WorkItem(1084278, "DevDiv")] public void NullableConversionFromFloatingPointConst() { var source = @" class C { void Use(int? p) { } void Test() { int? i; // double checks i = (int?)3.5d; i = (int?)double.MaxValue; i = (int?)double.NaN; i = (int?)double.NegativeInfinity; i = (int?)double.PositiveInfinity; // float checks i = (int?)3.5d; i = (int?)float.MaxValue; i = (int?)float.NaN; i = (int?)float.NegativeInfinity; i = (int?)float.PositiveInfinity; Use(i); unchecked { // double checks i = (int?)3.5d; i = (int?)double.MaxValue; i = (int?)double.NaN; i = (int?)double.NegativeInfinity; i = (int?)double.PositiveInfinity; // float checks i = (int?)3.5d; i = (int?)float.MaxValue; i = (int?)float.NaN; i = (int?)float.NegativeInfinity; i = (int?)float.PositiveInfinity; } } } "; var compilation = CreateCompilationWithMscorlib(source); compilation.VerifyDiagnostics( // (15,13): error CS0030: Cannot convert type 'double' to 'int?' // i = (int?)double.MaxValue; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)double.MaxValue").WithArguments("double", "int?").WithLocation(15, 13), // (16,13): error CS0030: Cannot convert type 'double' to 'int?' // i = (int?)double.NaN; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)double.NaN").WithArguments("double", "int?").WithLocation(16, 13), // (17,13): error CS0030: Cannot convert type 'double' to 'int?' // i = (int?)double.NegativeInfinity; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)double.NegativeInfinity").WithArguments("double", "int?").WithLocation(17, 13), // (18,13): error CS0030: Cannot convert type 'double' to 'int?' // i = (int?)double.PositiveInfinity; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)double.PositiveInfinity").WithArguments("double", "int?").WithLocation(18, 13), // (22,13): error CS0030: Cannot convert type 'float' to 'int?' // i = (int?)float.MaxValue; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)float.MaxValue").WithArguments("float", "int?").WithLocation(22, 13), // (23,13): error CS0030: Cannot convert type 'float' to 'int?' // i = (int?)float.NaN; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)float.NaN").WithArguments("float", "int?").WithLocation(23, 13), // (24,13): error CS0030: Cannot convert type 'float' to 'int?' // i = (int?)float.NegativeInfinity; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)float.NegativeInfinity").WithArguments("float", "int?").WithLocation(24, 13), // (25,13): error CS0030: Cannot convert type 'float' to 'int?' // i = (int?)float.PositiveInfinity; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)float.PositiveInfinity").WithArguments("float", "int?").WithLocation(25, 13)); var syntaxTree = compilation.SyntaxTrees.First(); var target = syntaxTree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().ToList()[2]; var operand = target.Expression; Assert.Equal("double.NaN", operand.ToFullString()); // Note: there is a valid conversion here at the type level. It's the process of evaluating the conversion, which for // constants happens at compile time, that triggers the error. HashSet<DiagnosticInfo> unused = null; var bag = DiagnosticBag.GetInstance(); var nullableIntType = compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(compilation.GetSpecialType(SpecialType.System_Int32)); var conversion = compilation.Conversions.ClassifyConversionFromExpression( compilation.GetBinder(target).BindExpression(operand, bag), nullableIntType, ref unused); Assert.True(conversion.IsExplicit && conversion.IsNullable); } } }
{ "pile_set_name": "Github" }
-- Copyright (C) 1996 Morgan Kaufmann Publishers, Inc -- This file is part of VESTs (Vhdl tESTs). -- VESTs is free software; you can redistribute it and/or modify it -- under the terms of the GNU General Public License as published by the -- Free Software Foundation; either version 2 of the License, or (at -- your option) any later version. -- VESTs is distributed in the hope that it will be useful, but WITHOUT -- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -- FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- for more details. -- You should have received a copy of the GNU General Public License -- along with VESTs; if not, write to the Free Software Foundation, -- Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- --------------------------------------------------------------------- -- -- $Id: ch_19_fork-b.vhd,v 1.2 2001-10-26 16:29:36 paw Exp $ -- $Revision: 1.2 $ -- -- --------------------------------------------------------------------- architecture behavior of fork is begin forker : process variable cumulative_probabilities : probability_vector(1 to probabilities'length); variable destination : positive range out_arc'range; variable probabilities_index : positive range probabilities'range; variable number_of_tokens_forked : natural := 0; type counter_array is array (positive range out_arc'range) of natural; variable number_forked_to_destination : counter_array := (others => 0); variable random_info : random_info_record; variable random_number : real; type transaction_vector is array (positive range <>) of boolean; variable out_arc_transaction_driving_value : transaction_vector(out_arc'range) := (others => false); use std.textio.all; file info_file : text; variable L : line; procedure write_summary is begin write(L, string'("Summary information for fork ")); write(L, name); write(L, string'(" up to time ")); write(L, now, unit => time_unit); writeline(info_file, L); write(L, string'(" Number of tokens forked = ")); write(L, natural(number_of_tokens_forked)); writeline(info_file, L); for destination in out_arc'range loop write(L, string'(" Number to output(")); write(L, destination); write(L, string'(") = ")); write(L, number_forked_to_destination(destination)); write(L, string'(" (")); write(L, real(number_forked_to_destination(destination)) / real(number_of_tokens_forked), digits => 4); write(L, ')'); writeline(info_file, L); end loop; writeline(info_file, L); end write_summary; procedure write_trace is begin write(L, string'("Fork ")); write(L, name); write(L, string'(": at ")); write(L, now, unit => time_unit); write(L, string'(" forked to output ")); write(L, destination); write(L, ' '); write(L, in_arc.token, time_unit); writeline(info_file, L); end write_trace; begin assert probabilities'length = out_arc'length - 1 report "incorrent number of probabilities - should be " & integer'image(out_arc'length - 1) severity failure; cumulative_probabilities := probabilities; for index in 2 to cumulative_probabilities'length loop cumulative_probabilities(index) := cumulative_probabilities(index - 1) + cumulative_probabilities(index); end loop; init_uniform( random_info, lower_bound => 0.0, upper_bound => 1.0, seed => seed ); file_open(info_file, info_file_name, write_mode); loop wait on info_detail'transaction, in_arc; if info_detail'active and info_detail = summary then write_summary; end if; if in_arc'event then generate_random(random_info, random_number); destination := out_arc'left; for index in 1 to cumulative_probabilities'length loop exit when random_number < cumulative_probabilities(index); if out_arc'ascending then destination := destination + 1; else destination := destination - 1; end if; end loop; out_arc(destination) <= arc_type'( transaction => not out_arc_transaction_driving_value(destination), token => in_arc.token ); out_arc_transaction_driving_value(destination) := not out_arc_transaction_driving_value(destination); number_of_tokens_forked := number_of_tokens_forked + 1; number_forked_to_destination(destination) := number_forked_to_destination(destination) + 1; if info_detail = trace then write_trace; end if; end if; end loop; end process forker; end behavior;
{ "pile_set_name": "Github" }
'use strict'; var GetIntrinsic = require('../GetIntrinsic'); var $ArrayPrototype = GetIntrinsic('%Array.prototype%'); var $RangeError = GetIntrinsic('%RangeError%'); var $SyntaxError = GetIntrinsic('%SyntaxError%'); var $TypeError = GetIntrinsic('%TypeError%'); var IsInteger = require('./IsInteger'); var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1; var $setProto = GetIntrinsic('%Object.setPrototypeOf%', true) || ( // eslint-disable-next-line no-proto, no-negated-condition [].__proto__ !== $ArrayPrototype ? null : function (O, proto) { O.__proto__ = proto; // eslint-disable-line no-proto, no-param-reassign return O; } ); // https://www.ecma-international.org/ecma-262/6.0/#sec-arraycreate module.exports = function ArrayCreate(length) { if (!IsInteger(length) || length < 0) { throw new $TypeError('Assertion failed: `length` must be an integer Number >= 0'); } if (length > MAX_ARRAY_LENGTH) { throw new $RangeError('length is greater than (2**32 - 1)'); } var proto = arguments.length > 1 ? arguments[1] : $ArrayPrototype; var A = []; // steps 5 - 7, and 9 if (proto !== $ArrayPrototype) { // step 8 if (!$setProto) { throw new $SyntaxError('ArrayCreate: a `proto` argument that is not `Array.prototype` is not supported in an environment that does not support setting the [[Prototype]]'); } $setProto(A, proto); } if (length !== 0) { // bypasses the need for step 2 A.length = length; } /* step 10, the above as a shortcut for the below OrdinaryDefineOwnProperty(A, 'length', { '[[Configurable]]': false, '[[Enumerable]]': false, '[[Value]]': length, '[[Writable]]': true }); */ return A; };
{ "pile_set_name": "Github" }
# @summary # Installs `mod_rewrite`. # # @see https://httpd.apache.org/docs/current/mod/mod_rewrite.html for additional documentation. # class apache::mod::rewrite { include ::apache::params ::apache::mod { 'rewrite': } }
{ "pile_set_name": "Github" }
'use strict'; const cluster = require('cluster') const cp = require('child_process') const path = require('path') const len = require('os').cpus().length let agentWorker if(cluster.isMaster) { let c = 0 cluster.on('online', worker => { console.log('[master] launch webWorker id:%d succ', worker.id) if(!worker._isRestarted) { if(++c == len) agentWorker.send({action: 'load:conf'}) } else { // 二次fork的进程 agentWorker.send({action: 'load:conf', fromId: worker.id}) } }) cluster.on('exit', worker => { console.log('[master] webWorker id:%d died', worker.id) let nWorker = startWebWorker() // 标识这个worker是二次fork的 nWorker._isRestarted = true }) cluster.on('message', webWorkerMsgHandler) agentWorker = startAgentWorker() for(let i=0; i<len; i++) startWebWorker() } function startWebWorker() { cluster.setupMaster({ exec: path.resolve('./web.js') }) let worker = cluster.fork() return worker } function startAgentWorker() { let worker = cp.fork(path.resolve('./agent.js')) worker.on('message', agentMessageHandler) worker.on('exit', () => { console.log('[master] agentWorker died') agentWorker = startAgentWorker() }) console.log(`[master] launch agentWorker succ`) return worker } function webWorkerMsgHandler(worker, msg) { console.log(`[master] received from web, msg ${JSON.stringify(msg)}`) let { action } = msg switch(action) { case 'update:conf': case 'retry:conf': msg.fromId = worker.id agentWorker.send(msg) break default: break } } function agentMessageHandler(msg) { console.log(`[master] received from agent, msg ${JSON.stringify(msg)}`) let { action } = msg switch(action) { case 'load:conf:succ': if(msg.conf) broadcast({action: action, conf: msg.conf}, msg.fromId) break case 'load:conf:fail': // 拉取不到配置信息,直接杀死进程,让进程管理器去重启 console.error('[master]', msg.error) process.exit() break case 'retry:conf:succ': case 'update:conf:succ': if(msg.conf) broadcast(msg) break case 'retry:conf:fail': case 'update:conf:fail': if(msg.fromId != undefined) broadcast(msg, msg.fromId) break default: break } } function broadcast(msg, workerId) { if(workerId) { cluster.workers[workerId].send(msg) return } let webWorkers = getWorkers() for(let i=0; i<webWorkers.length; i++) webWorkers[i].send(msg) } function getWorkers() { let arr = [] for(let id in cluster.workers) { let worker = cluster.workers[id] arr.push(worker) } return arr }
{ "pile_set_name": "Github" }
#include <bits/stdc++.h> using namespace std; void debug_out() { cerr << endl; } template <typename H, typename... T> void debug_out(H h, T... t) { cerr << " " << to_string(h); debug_out(t...); } #ifdef LOCAL #define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__) #else #define debug(...) // #endif long long solve(vector<vector<int>> &b, int k) { int n = b.size(), m = b[0].size(); vector<int> s(m + 1); long long ans = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { s[j + 1] = b[i][j]; s[j + 1] += s[j]; } for (int j = 0; j + k <= m; j++) { if ((s[j + k] - s[j]) == 0) ans++; } } return ans; } int main() { #ifndef LOCAL #define endl '\n' ios_base::sync_with_stdio(false); cin.tie(NULL); #endif int n, m, k; cin >> n >> m >> k; vector<vector<int>> b(n, vector<int>(m)); for (auto &it : b) for (auto &i : it) { char t; cin >> t; i = (t == '*'); } long long ans = solve(b, k); vector<vector<int>> bb(m, vector<int>(n)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { bb[j][i] = b[i][j]; } } if (k > 1) ans += solve(bb, k); cout << ans << endl; return 0; }
{ "pile_set_name": "Github" }
'use strict'; module.exports = function (str) { return typeof str === 'string' ? str.replace(/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]/g, '') : str; };
{ "pile_set_name": "Github" }
package com.sksamuel.elastic4s.requests.searches.aggs import com.sksamuel.elastic4s.requests.searches.sort.Sort import com.sksamuel.exts.OptionImplicits._ case class Metric() case class TopMetricsAggregation(name: String, metrics: List[String] = Nil, size: Option[Int] = None, sort: Option[Sort] = None, subaggs: Seq[AbstractAggregation] = Nil, metadata: Map[String, AnyRef] = Map.empty) extends Aggregation { type T = TopMetricsAggregation def withMetrics(field: String, fields: String*): TopMetricsAggregation = copy(metrics = (field +: fields).toList) def withMetrics(fields: Iterable[String]): TopMetricsAggregation = copy(metrics = fields.toList) def withSize(size: Int): TopMetricsAggregation = copy(size = size.some) def withSort(sort: Sort): TopMetricsAggregation = copy(sort = sort.some) override def subAggregations(aggs: Iterable[AbstractAggregation]): T = copy(subaggs = aggs.toSeq) override def metadata(map: Map[String, AnyRef]): T = copy(metadata = map) }
{ "pile_set_name": "Github" }
<html> <!-- https://bugzilla.mozilla.org/show_bug.cgi?id=467672 --> <head> <title>Test for Bug 467672</title> <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> <script type="text/javascript" src="/tests/SimpleTest/WindowSnapshot.js"></script> <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" /> </head> <body> <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=467672">Mozilla Bug 467672</a> <pre id="test"> <script type="text/javascript"> /** Test for Bug 467672 **/ var passes = [ // bug 467672 tests (Arabic and Persian) {prefix: "bug467672", file: 1, bidiNumeralValue: 1, op: "=="}, ]; </script> <script type="text/javascript" src="bidi_numeral_test.js"></script> </pre> </body> </html>
{ "pile_set_name": "Github" }
menuconfig BR2_PACKAGE_GST1_PLUGINS_BAD bool "gst1-plugins-bad" select BR2_PACKAGE_GST1_PLUGINS_BASE help A set of plug-ins for GStreamer that may be of poor quality or lacking some features. http://gstreamer.freedesktop.org/ if BR2_PACKAGE_GST1_PLUGINS_BAD comment "dependency-less plugins" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_ACCURIP bool "accurip" help Accurip plugin config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_ADPCMDEC bool "adpcmdec" help ADPCM decoder config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_ADPCMENC bool "adpcmenc" help ADPCM encoder config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_AIFF bool "aiff" help Create and parse Audio interchange File Format (AIFF) files config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_ASFMUX bool "asfmux" help ASF Muxer Plugin config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_AUDIOFXBAD bool "audiofxbad" help Audio filters plugin config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_AUDIOMIXER bool "audiomixer" help Audio mixer plugin config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_COMPOSITOR bool "compositor" help Video compositor plugin config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_AUDIOVISUALIZERS bool "audiovisualizers" help Creates video visualizations of audio input config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_AUTOCONVERT bool "autoconvert" help Selects convertor element based on caps config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_BAYER bool "bayer" help Elements to convert Bayer images config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_CAMERABIN2 bool "camerabin2" help Take image snapshots and record movies from camera config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_CDXAPARSE bool "cdxaparse" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_COLOREFFECTS bool "coloreffects" help Color Look-up Table filters config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_DATAURISRC bool "dataurisrc" help data: URI source config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_DCCP bool "dccp" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_DEBUGUTILS bool "debugutils" help Collection of elements that may or may not be useful for debugging config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_DVBSUBOVERLAY bool "dvdsuboverlay" help DVB subtitle renderer plugin config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_DVDSPU bool "dvdspu" help DVD Sub-picture Overlay element config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_FACEOVERLAY bool "faceoverlay" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_FESTIVAL bool "festival" help Synthesizes plain text into audio config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_FIELDANALYSIS bool "fieldanalysis" help Video field analysis config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_FREEVERB bool "freeverb" help Reverberation/room effect config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_FREI0R bool "frei0r" help frei0r plugin library config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_GAUDIEFFECTS bool "gaudieffects" help Gaudi video effects config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_GEOMETRICTRANSFORM bool "geometrictransform" help Various geometric image transform elements config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_GDP bool "gdp" help Payload/depayload GDP packets config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_HDVPARSE bool "hdvparse" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_ID3TAG bool "id3tag" help ID3 v1 and v2 muxing plugin config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_INTER bool "inter" help plugin for inter-pipeline communication config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_INTERLACE bool "interlace" help Create an interlaced video stream config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_IVFPARSE bool "ivfparse" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_IVTC bool "ivtc" help Inverse Telecine plugin config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_JP2KDECIMATOR bool "jp2kdecimator" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_JPEGFORMAT bool "jpegformat" help JPEG interchange format plugin config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_LIBRFB bool "librfb" help Connects to a VNC server and decodes RFB stream config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_LIVEADDER bool "liveadder" help Adds multiple live discontinuous streams config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_MIDI bool "midi" help MIDI plugin config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_MPEGDEMUX bool "mpegdemux" help MPEG-PS demuxer config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_MPEGTSDEMUX bool "mpegtsdemux" help MPEG TS demuxer config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_MPEGTSMUX bool "mpegtsmux" help MPEG-TS muxer config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_MPEGPSMUX bool "mpegpsmux" help MPEG-PS muxer config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_MVE bool "mve" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_MXF bool "mxf" help MXF plugin library config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_NUVDEMUX bool "nuvdemux" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_PATCHDETECT bool "patchdetect" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_PCAPPARSE bool "pcapparse" help Element parsing raw pcap streams config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_PNM bool "pnm" help PNM plugin config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_RAWPARSE bool "rawparse" help Parses byte streams into raw frames config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_REAL bool "real" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_REMOVESILENCE bool "removesilence" help Removes silence from an audio stream config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_SDI bool "sdi" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_SDP bool "sdp" help configure streaming sessions using SDP config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_SEGMENTCLIP bool "segmentclip" help Segment clip elements config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_SIREN bool "siren" help Siren encoder/decoder/payloader/depayloader plugins config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_SMOOTH bool "smooth" help Apply a smooth filter to an image config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_SPEED bool "speed" help Set speed/pitch on audio/raw streams (resampler) config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_SUBENC bool "subenc" help subtitle encoders config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_STEREO bool "stereo" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_TTA bool "tta" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_VIDEOFILTERS bool "videofilters" help Video filters in gst-plugins-bad config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_VIDEOMEASURE bool "videomeasure" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_VIDEOPARSERS bool "videoparsers" help videoparsers config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_VIDEOSIGNAL bool "videosignal" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_VMNC bool "vmnc" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_Y4M bool "y4m" help Demuxes/decodes YUV4MPEG streams config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_YADIF bool "yadif" help YADIF deinterlacing filter comment "plugins with external dependencies" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_SHM bool "shm" help shared memory sink source config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_VCD bool "vcd" config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_APEXSINK bool "apexsink" select BR2_PACKAGE_OPENSSL config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_ASSRENDER bool "assrender" select BR2_PACKAGE_LIBASS config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_VOAACENC bool "voaacenc" select BR2_PACKAGE_VO_AACENC config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_BZ2 bool "bz2" select BR2_PACKAGE_BZIP2 help Compress or decompress streams config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_CURL bool "curl" select BR2_PACKAGE_LIBCURL help libcurl-based elements config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_DASH bool "dash" select BR2_PACKAGE_LIBXML2 help DASH demuxer plugin config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_DECKLINK depends on BR2_INSTALL_LIBSTDCPP bool "decklink" help Blackmagic Decklink plugin comment "decklink needs a toolchain w/ C++" depends on !BR2_INSTALL_LIBSTDCPP config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_DIRECTFB bool "directfb" select BR2_PACKAGE_DIRECTFB depends on BR2_TOOLCHAIN_HAS_THREADS depends on BR2_INSTALL_LIBSTDCPP config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_WAYLAND bool "wayland" depends on !BR2_avr32 # wayland depends on !BR2_STATIC_LIBS # wayland depends on BR2_TOOLCHAIN_HAS_THREADS # wayland select BR2_PACKAGE_WAYLAND help Wayland Video Sink config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_WEBP bool "webp" select BR2_PACKAGE_WEBP help Webp image format plugin config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_FAAD bool "faad" select BR2_PACKAGE_FAAD2 help Free AAC Decoder (FAAD) config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_FBDEV bool "fbdev" help Linux framebuffer video sink config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_LIBMMS bool "libmms" depends on BR2_USE_WCHAR # libmms -> libglib2 depends on BR2_TOOLCHAIN_HAS_THREADS # libmms -> libglib2 select BR2_PACKAGE_LIBMMS help Microsoft Multi Media Server streaming protocol support comment "libmms needs a toolchain w/ wchar, threads" depends on !BR2_USE_WCHAR || !BR2_TOOLCHAIN_HAS_THREADS config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_MPEG2ENC bool "mpeg2enc" select BR2_PACKAGE_LIBMPEG2 help High-quality MPEG-1/2 video encoder config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_MPG123 bool "mpg123" select BR2_PACKAGE_MPG123 depends on BR2_USE_MMU # mpg123 help mp3 decoding based on the mpg123 library config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_MUSEPACK bool "musepack" select BR2_PACKAGE_MUSEPACK config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_NEON bool "neon" select BR2_PACKAGE_NEON help lib neon http client src config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_OPENCV bool "opencv" depends on BR2_INSTALL_LIBSTDCPP depends on BR2_TOOLCHAIN_HAS_THREADS_NPTL select BR2_PACKAGE_OPENCV # Remove the following opencv modules when gstreamer fixes the # problem of including the old "cv.h" header # bug: https://bugzilla.gnome.org/show_bug.cgi?id=725163 select BR2_PACKAGE_OPENCV_LIB_CALIB3D select BR2_PACKAGE_OPENCV_LIB_CONTRIB select BR2_PACKAGE_OPENCV_LIB_FEATURES2D select BR2_PACKAGE_OPENCV_LIB_FLANN select BR2_PACKAGE_OPENCV_LIB_IMGPROC select BR2_PACKAGE_OPENCV_LIB_LEGACY select BR2_PACKAGE_OPENCV_LIB_ML select BR2_PACKAGE_OPENCV_LIB_OBJDETECT select BR2_PACKAGE_OPENCV_LIB_VIDEO help GStreamer OpenCV Plugins comment "opencv plugin needs a toolchain w/ C++, NPTL" depends on !BR2_INSTALL_LIBSTDCPP || !BR2_TOOLCHAIN_HAS_THREADS_NPTL config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_OPUS bool "opus" select BR2_PACKAGE_OPUS help OPUS plugin library config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_RSVG bool "rsvg" depends on BR2_INSTALL_LIBSTDCPP depends on BR2_USE_WCHAR # librsvg -> glib2 depends on BR2_TOOLCHAIN_HAS_THREADS # librsvg -> glib2 select BR2_PACKAGE_LIBRSVG help RSVG plugin library comment "rsvg plugin needs a toolchain w/ C++, wchar, threads" depends on !BR2_INSTALL_LIBSTDCPP || !BR2_USE_WCHAR || \ !BR2_TOOLCHAIN_HAS_THREADS config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_SDL bool "sdl" select BR2_PACKAGE_SDL config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_SNDFILE bool "sndfile" select BR2_PACKAGE_LIBSNDFILE depends on BR2_LARGEFILE comment "sndfile plugin needs a toolchain w/ largefile" depends on !BR2_LARGEFILE config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_DVB bool "dvb" select BR2_PACKAGE_DTV_SCAN_TABLES help DVB elements config BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_HLS bool "hls" select BR2_PACKAGE_GNUTLS help Fragmented streaming plugins endif
{ "pile_set_name": "Github" }
# Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Disabling obfuscation is useful if you collect stack traces from production crashes # (unless you are using a system that supports de-obfuscate the stack traces). -dontobfuscate # React Native # Keep our interfaces so they can be used by other ProGuard rules. # See http://sourceforge.net/p/proguard/bugs/466/ -keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStrip -keep,allowobfuscation @interface com.facebook.proguard.annotations.KeepGettersAndSetters -keep,allowobfuscation @interface com.facebook.common.internal.DoNotStrip # Do not strip any method/class that is annotated with @DoNotStrip -keep @com.facebook.proguard.annotations.DoNotStrip class * -keep @com.facebook.common.internal.DoNotStrip class * -keepclassmembers class * { @com.facebook.proguard.annotations.DoNotStrip *; @com.facebook.common.internal.DoNotStrip *; } -keepclassmembers @com.facebook.proguard.annotations.KeepGettersAndSetters class * { void set*(***); *** get*(); } -keep class * extends com.facebook.react.bridge.JavaScriptModule { *; } -keep class * extends com.facebook.react.bridge.NativeModule { *; } -keepclassmembers,includedescriptorclasses class * { native <methods>; } -keepclassmembers class * { @com.facebook.react.uimanager.UIProp <fields>; } -keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactProp <methods>; } -keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactPropGroup <methods>; } -dontwarn com.facebook.react.** # TextLayoutBuilder uses a non-public Android constructor within StaticLayout. # See libs/proxy/src/main/java/com/facebook/fbui/textlayoutbuilder/proxy for details. -dontwarn android.text.StaticLayout # okhttp -keepattributes Signature -keepattributes *Annotation* -keep class okhttp3.** { *; } -keep interface okhttp3.** { *; } -dontwarn okhttp3.** # okio -keep class sun.misc.Unsafe { *; } -dontwarn java.nio.file.* -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement -dontwarn okio.**
{ "pile_set_name": "Github" }
# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors. # # 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. """Tests for LibrispeechLm dataset builder.""" from tensorflow_datasets import testing from tensorflow_datasets.text import librispeech_lm class LibrispeechLmTest(testing.DatasetBuilderTestCase): DATASET_CLASS = librispeech_lm.LibrispeechLm SPLITS = { "train": 4, # Number of fake train examples. } DL_DOWNLOAD_RESULT = "librispeech-lm-norm.txt.gz" if __name__ == "__main__": testing.test_main()
{ "pile_set_name": "Github" }
<?php namespace oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2; use un\unece\uncefact\data\specification\UnqualifiedDataTypesSchemaModule\_2; /** * @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2 * @xmlType TextType * @xmlName OutstandingReasonType * @var oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2\OutstandingReasonType */ class OutstandingReasonType extends _2\TextType { } // end class OutstandingReasonType
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.4.2_17) on Wed Jun 17 16:17:32 BST 2009 --> <TITLE> org.apache.jmeter.protocol.ldap.sampler Class Hierarchy (Apache JMeter API) </TITLE> <LINK REL="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title = "org.apache.jmeter.protocol.ldap.sampler Class Hierarchy (Apache JMeter API)"; } </SCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"><A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"><A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"><FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp; </TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"><A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"><A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"><A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <b>Apache JMeter</b></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../org/apache/jmeter/protocol/ldap/control/gui/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../../org/apache/jmeter/protocol/mail/sampler/package-tree.html"><B>NEXT</B></A></FONT> </TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp; <SCRIPT type="text/javascript"> <!-- if (window == top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> Hierarchy For Package org.apache.jmeter.protocol.ldap.sampler </H2> </CENTER> <DL> <DT><B>Package Hierarchies:</B> <DD><A HREF="../../../../../../overview-tree.html">All Packages</A> </DL> <HR> <H2> Class Hierarchy </H2> <UL> <LI TYPE="circle">class java.lang.<A HREF="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html" title="class or interface in java.lang"><B>Object</B></A> <UL> <LI TYPE="circle">class org.apache.jmeter.testelement.<A HREF="../../../../../../org/apache/jmeter/testelement/AbstractTestElement.html" title="class in org.apache.jmeter.testelement"><B>AbstractTestElement</B></A> (implements java.io.<A HREF="http://java.sun.com/j2se/1.4.2/docs/api/java/io/Serializable.html" title="class or interface in java.io">Serializable</A>, org.apache.jmeter.testelement.<A HREF="../../../../../../org/apache/jmeter/testelement/TestElement.html" title="interface in org.apache.jmeter.testelement">TestElement</A>) <UL> <LI TYPE="circle">class org.apache.jmeter.samplers.<A HREF="../../../../../../org/apache/jmeter/samplers/AbstractSampler.html" title="class in org.apache.jmeter.samplers"><B>AbstractSampler</B></A> (implements org.apache.jmeter.samplers.<A HREF="../../../../../../org/apache/jmeter/samplers/Sampler.html" title="interface in org.apache.jmeter.samplers">Sampler</A>) <UL> <LI TYPE="circle">class org.apache.jmeter.protocol.ldap.sampler.<A HREF="../../../../../../org/apache/jmeter/protocol/ldap/sampler/LDAPExtSampler.html" title="class in org.apache.jmeter.protocol.ldap.sampler"><B>LDAPExtSampler</B></A> (implements org.apache.jmeter.testelement.<A HREF="../../../../../../org/apache/jmeter/testelement/TestListener.html" title="interface in org.apache.jmeter.testelement">TestListener</A>) <LI TYPE="circle">class org.apache.jmeter.protocol.ldap.sampler.<A HREF="../../../../../../org/apache/jmeter/protocol/ldap/sampler/LDAPSampler.html" title="class in org.apache.jmeter.protocol.ldap.sampler"><B>LDAPSampler</B></A> </UL> </UL> <LI TYPE="circle">class org.apache.jmeter.protocol.ldap.sampler.<A HREF="../../../../../../org/apache/jmeter/protocol/ldap/sampler/LdapClient.html" title="class in org.apache.jmeter.protocol.ldap.sampler"><B>LdapClient</B></A> <LI TYPE="circle">class org.apache.jmeter.protocol.ldap.sampler.<A HREF="../../../../../../org/apache/jmeter/protocol/ldap/sampler/LdapExtClient.html" title="class in org.apache.jmeter.protocol.ldap.sampler"><B>LdapExtClient</B></A> </UL> </UL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"><A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"><A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"><FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp; </TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"><A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"><A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"><A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <b>Apache JMeter</b></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../org/apache/jmeter/protocol/ldap/control/gui/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../../org/apache/jmeter/protocol/mail/sampler/package-tree.html"><B>NEXT</B></A></FONT> </TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp; <SCRIPT type="text/javascript"> <!-- if (window == top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#xA9; 1998-2009 Apache Software Foundation. All Rights Reserved. </BODY> </HTML>
{ "pile_set_name": "Github" }
open Infix; open RResult; let rec show = item => switch item { | `Ident(text) => "Ident<" ++ text ++ ">" | `Number(n) => "Number<" ++ string_of_float(n) ++ ">" | `String(s) => "String<" ++ s ++ ">" | `List(items) => "[" ++ String.concat(", ", List.map(show, items)) ++ "]" }; let rec getNamedIdent = items => switch items { | [] => (None, None) | [`List([`Ident("name"), `Ident(s)]), ...rest] => let (public, _) = getNamedIdent(rest); (public, Some(s)) | [`List([`Ident("name"), ..._]), ...rest] => getNamedIdent(rest) | [`List([`Ident("public_name"), `Ident(s)]), ...rest] => let (_, private) = getNamedIdent(rest); (Some(s), private) | [`List([`Ident("public_name"), ..._]), ...rest] => getNamedIdent(rest) | [_, ...rest] => getNamedIdent(rest) }; let rec getModules = items => switch items { | [] => None | [`List([`Ident("modules"), ...modules]), ..._] => Some(modules->Belt.List.keepMap(item => switch item { | `Ident(name) => Some(name) | _ => None })) | [_, ...rest] => getModules(rest) } let isUnwrapped = items => { let rec loop = items => switch items { | [] => false | [`List([`Ident("wrapped"), `Ident("false")]), ..._] => true | [_, ...rest] => loop(rest) }; loop(items) }; let includeRecursive = items => { // (include_subdirs unqualified) let rec loop = items => switch items { | [] => false | [`List([`Ident("include_subdirs"), `Ident("unqualified")]), ..._] => true | [_, ...rest] => loop(rest) }; loop(items) }; let getLibsAndBinaries = jbuildConfig => { jbuildConfig->Belt.List.keepMap(item => switch item { // Handle the case where there's only one thing and it's a (name _) or a (public_name _) | `List([`Ident("library"), ...[`List([`Ident(_), _])] as library]) | `List([`Ident("library"), `List(library)]) | `List([`Ident("library"), ...library]) => { let (public, private) = getNamedIdent(library) let modules = getModules(library); Some((isUnwrapped(library) ? `UnwrappedLibrary : `Library, public, private, modules)) } // Handle the case where there's only one thing and it's a (name _) or a (public_name _) | `List([`Ident("executable"), ...[`List([`Ident(_), _])] as executable]) | `List([`Ident("executable"), `List(executable)]) | `List([`Ident("executable"), ...executable]) => { let (public, private) = getNamedIdent(executable) let modules = getModules(executable); Some((`Binary, public, private, modules)) } | _ => None }) }; let findLibraryName = jbuildConfig => { let rec loop = items => switch items { | [] => None | [`List([`Ident("library"), `List(items)]), ..._] | [`List([`Ident("library"), ...items]), ..._] => /* Log.log("Found a library!"); Log.log(String.concat("\n", List.map(show, items))); */ switch (getNamedIdent(items)) { | (_, Some(priv)) => Some(priv) | (public, _) => public } | [_, ...rest] => { loop(rest) } }; loop(jbuildConfig) }; let hasIncludeSubdirs = jbuildConfig => { let rec loop = items => switch items { | [] => false | [`List([`Ident("include_subdirs"), `Ident("unqualified")]), ..._] => true | [_, ...rest] => loop(rest) }; loop(jbuildConfig) }; /* (include_subdirs unqualified) */ let findExecutableName = jbuildConfig => { let rec loop = items => switch items { | [] => None | [`List([`Ident("executable"), `List(items)]), ..._] | [`List([`Ident("executable"), ...items]), ..._] => switch (getNamedIdent(items)) { | (_, Some(priv)) => Some(priv) | (public, _) => public } | [_, ...rest] => { loop(rest) } }; loop(jbuildConfig) }; let findName = jbuildConfig => { switch (findLibraryName(jbuildConfig)) { | Some(name) => `Library(name) | None => switch (findExecutableName(jbuildConfig)) { | Some(name) => `Executable(name) | None => `NoName } } }; /** (jbuild_version 1) (library ((name MarkdownReasonReactFolx) (public_name markdown-reason-react) (libraries (reason)))) */ let fail = (msg) => failwith(msg); let parseString = (text, pos) => { /* let i = ref(pos); */ let buffer = Buffer.create(String.length(text)); let ln = String.length(text); let rec loop = (i) => i >= ln ? fail("Unterminated string") : ( switch text.[i] { | '"' => i + 1 | '\\' => i + 1 >= ln ? fail("Unterminated string") : ( switch text.[i + 1] { | '/' => Buffer.add_char(buffer, '/'); loop(i + 2) | 'f' => Buffer.add_char(buffer, '\012'); loop(i + 2) | _ => Buffer.add_string(buffer, Scanf.unescaped(String.sub(text, i, 2))); loop(i + 2) } ) | c => Buffer.add_char(buffer, c); loop(i + 1) } ); let final = loop(pos); (Buffer.contents(buffer), final) }; let rec skipComment = (raw, ln, i) => i >= ln ? i : switch (raw.[i]) { | '\n' | '\r' => i + 1 | _ => skipComment(raw, ln, i + 1) }; let rec skipWhite = (raw, ln, i) => i >= ln ? i : switch (raw.[i]) { | ' ' | '\n' | '\r' | '\t' => skipWhite(raw, ln, i + 1) | ';' => skipWhite(raw, ln, skipComment(raw, ln, i + 1)) | _ => i }; let rec parseIdent = (raw, ln, i) => i >= ln ? i : switch (raw.[i]) { | 'a'..'z' | 'A'..'Z' | '_' | '-' | '.' | '0'..'9' => parseIdent(raw, ln, i + 1) | _ => i }; let rec parseInt = (raw, ln, i) => i >= ln ? i : switch (raw.[i]) { | '0'..'9' => parseInt(raw, ln, i + 1) | _ => i }; let parseNumber = (raw, ln, i) => i >= ln ? i : { let i = parseInt(raw, ln, i); if (i < ln && raw.[i] == '.') { parseInt(raw, ln, i + 1) } else { i } }; let rec atomToString = atom => switch atom { | `Ident(n) => n | `List(items) => "[" ++ (String.concat(", ", List.map(atomToString, items))) ++ "]" | `Number(n) => string_of_float(n) | `String(s) => "\"" ++ String.escaped(s) ++ "\"" }; let rec parseAtom = (raw, ln, i) => switch (raw.[i]) { | '%' => if(raw.[i + 1] === '{') { let (lst, i) = parseList(~term='}', raw, ln, i + 2); (List.hd(lst), i); } else { let last = parseIdent(raw, ln, i + 1); (`Ident(String.sub(raw, i, last - i)), last); } | '0'..'9' => let last = parseNumber(raw, ln, i + 1); (`Number(float_of_string(String.sub(raw, i, last - i))), last) | '"' => let (text, last) = parseString(raw, i + 1); (`String(text), last) | '(' => { let (items, i) = parseList(raw, ln, i + 1); (`List(items), i) } /* Any other ASCII chars */ | '!'..'~' => let last = parseIdent(raw, ln, i + 1); (`Ident(String.sub(raw, i, last - i)), last); | _ => failwith("Unexpected char: " ++ String.sub(raw, i, 1) ++ " at " ++ string_of_int(i)) } and parseList = (~term=')', raw, ln, i) => { let i = skipWhite(raw, ln, i); i >= ln ? ([], i) : switch (raw.[i]) { | x when x === term => ([], i + 1) | _ => let (item, i) = parseAtom(raw, ln, i); let (rest, i) = parseList(~term, raw, ln, i); ([item, ...rest], i) } }; let parse = raw => { let ln = String.length(raw); let rec loop = i => { let i = skipWhite(raw, ln, i); i >= ln ? [] : { let (atom, i) = parseAtom(raw, ln, i); [atom, ...loop(i)] } }; loop(0) }; let readFromDir = (dirPath) => { let filePath = dirPath /+ "dune"; switch (Files.readFileResult(filePath)) { | Ok(x) => Ok((filePath, x)) | Error(_) => let filePath = dirPath /+ "jbuild"; switch (Files.readFileResult(filePath)) { | Ok(x) => Ok((filePath, x)) | Error(x) => Error(x) } }; };
{ "pile_set_name": "Github" }
# sorted-union-stream Get the union of two sorted streams ``` npm install sorted-union-stream ``` [![build status](https://secure.travis-ci.org/mafintosh/sorted-union-stream.png)](http://travis-ci.org/mafintosh/sorted-union-stream) ## Usage ``` js var union = require('sorted-union-stream') var from = require('from2-array') // es.readArray converts an array into a stream var sorted1 = from.obj([1,10,24,42,43,50,55]) var sorted2 = from.obj([10,42,53,55,60]) // combine the two streams into a single sorted stream var u = union(sorted1, sorted2) u.on('data', function(data) { console.log(data) }) u.on('end', function() { console.log('no more data') }) ``` Running the above example will print ``` 1 10 24 42 43 50 53 55 60 no more data ``` ## Streaming objects If you are streaming objects sorting is based on `.key`. If this property is not present you should add a `toKey` function as the third parameter. `toKey` should return an key representation of the data that can be used to compare objects. _The keys MUST be sorted_ ``` js var sorted1 = from.obj([{foo:'a'}, {foo:'b'}, {foo:'c'}]) var sorted2 = from.obj([{foo:'b'}, {foo:'d'}]) var u = union(sorted1, sorted2, function(data) { return data.foo // the foo property is sorted }) union.on('data', function(data) { console.log(data) }); ``` Running the above will print ``` {foo:'a'} {foo:'b'} {foo:'c'} {foo:'d'} ``` ## License MIT
{ "pile_set_name": "Github" }
Prism.languages.icon = { 'comment': /#.*/, 'string': { pattern: /(["'])(?:(?!\1)[^\\\r\n_]|\\.|_(?!\1)(?:\r\n|[\s\S]))*\1/, greedy: true }, 'number': /\b(?:\d+r[a-z\d]+|\d+(?:\.\d+)?(?:e[+-]?\d+)?)\b|\.\d+\b/i, 'builtin-keyword': { pattern: /&(?:allocated|ascii|clock|collections|cset|current|date|dateline|digits|dump|e|error(?:number|text|value)?|errout|fail|features|file|host|input|lcase|letters|level|line|main|null|output|phi|pi|pos|progname|random|regions|source|storage|subject|time|trace|ucase|version)\b/, alias: 'variable' }, 'directive': { pattern: /\$\w+/, alias: 'builtin' }, 'keyword': /\b(?:break|by|case|create|default|do|else|end|every|fail|global|if|initial|invocable|link|local|next|not|of|procedure|record|repeat|return|static|suspend|then|to|until|while)\b/, 'function': /(?!\d)\w+(?=\s*[({]|\s*!\s*\[)/, 'operator': /[+-]:(?!=)|(?:[\/?@^%&]|\+\+?|--?|==?=?|~==?=?|\*\*?|\|\|\|?|<(?:->?|<?=?)|>>?=?)(?::=)?|:(?:=:?)?|[!.\\|~]/, 'punctuation': /[\[\](){},;]/ };
{ "pile_set_name": "Github" }
//============================================================================= /** * @file test_dynunion.h * * Header file for class to test DynUnion. * * @author Jeff Parsons <[email protected]> */ //============================================================================= #if !defined (TEST_DYNUNION_H) #define TEST_DYNUNION_H #include "tao/ORB.h" class Test_DynUnion { public: Test_DynUnion (CORBA::ORB_var orb, int debug); ~Test_DynUnion (void); const char* test_name (void) const; int run_test (void); private: CORBA::ORB_var orb_; char* test_name_; CORBA::ULong error_count_; int debug_; }; #endif /* TEST_DYNUNION_H */
{ "pile_set_name": "Github" }
/* * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifndef OSSL_CRYPTO_ERR_H # define OSSL_CRYPTO_ERR_H int err_load_crypto_strings_int(void); void err_cleanup(void); void err_delete_thread_state(void); int err_shelve_state(void **); void err_unshelve_state(void *); #endif
{ "pile_set_name": "Github" }
#!/bin/bash # # Run a Curl command as a given ArchivesSpace user # # Non-portable! Just for development purposes... user=$1 pass=$2 # Pick out the last URL base on the command line (yuck) url=$(echo $* | sed 's|^.*\(http://[^/]*\).*|\1|g') echo "URL $url" # It gets worse :) session=$(curl -s -F password="$pass" "$url/users/$user/login" | sed 's|.*"session":"\([a-z0-9]*\)".*|\1|g') # throw out the username and password shift 2 echo "Session $session" # and pass the rest to Curl echo "curl -H \"X-ArchivesSpace-Session: $session\" ${1+\"$@\"}" exec curl -H "X-ArchivesSpace-Session: $session" ${1+"$@"}
{ "pile_set_name": "Github" }
eclipse.preferences.version=1 encoding/<project>=UTF-8
{ "pile_set_name": "Github" }
/* bt819.h - bt819 notifications Copyright (C) 2009 Hans Verkuil ([email protected]) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef _BT819_H_ #define _BT819_H_ #include <linux/ioctl.h> /* v4l2_device notifications. */ /* Needed to reset the FIFO buffer when changing the input or the video standard. */ #define BT819_FIFO_RESET_LOW _IO('b', 0) #define BT819_FIFO_RESET_HIGH _IO('b', 1) #endif
{ "pile_set_name": "Github" }
ISO-10303-21; HEADER; /* Generated by software containing ST-Developer * from STEP Tools, Inc. (www.steptools.com) */ FILE_DESCRIPTION( /* description */ (''), /* implementation_level */ '2;1'); FILE_NAME( /* name */ 'C:/Downloads/Da Vinci 3D printer/renders/Belt printer/White Knight Fu sion files/2-Roller_Insert v1 v3.step', /* time_stamp */ '2019-09-14T12:51:33-04:00', /* author */ (''), /* organization */ (''), /* preprocessor_version */ 'ST-DEVELOPER v18', /* originating_system */ 'Autodesk Translation Framework v8.6.0.1094', /* authorisation */ ''); FILE_SCHEMA (('AUTOMOTIVE_DESIGN { 1 0 10303 214 3 1 1 }')); ENDSEC; DATA; #10=MECHANICAL_DESIGN_GEOMETRIC_PRESENTATION_REPRESENTATION('',(#13),#125); #11=SHAPE_REPRESENTATION_RELATIONSHIP('SRR','None',#132,#12); #12=ADVANCED_BREP_SHAPE_REPRESENTATION('',(#14),#124); #13=STYLED_ITEM('',(#142),#14); #14=MANIFOLD_SOLID_BREP('Roller Insert',#65); #15=FACE_BOUND('',#26,.T.); #16=FACE_BOUND('',#28,.T.); #17=PLANE('',#85); #18=PLANE('',#86); #19=FACE_OUTER_BOUND('',#23,.T.); #20=FACE_OUTER_BOUND('',#24,.T.); #21=FACE_OUTER_BOUND('',#25,.T.); #22=FACE_OUTER_BOUND('',#27,.T.); #23=EDGE_LOOP('',(#47,#48,#49,#50)); #24=EDGE_LOOP('',(#51,#52,#53,#54)); #25=EDGE_LOOP('',(#55)); #26=EDGE_LOOP('',(#56)); #27=EDGE_LOOP('',(#57)); #28=EDGE_LOOP('',(#58)); #29=LINE('',#112,#31); #30=LINE('',#118,#32); #31=VECTOR('',#93,6.45); #32=VECTOR('',#100,34.925); #33=CIRCLE('',#80,6.45); #34=CIRCLE('',#81,6.45); #35=CIRCLE('',#83,34.925); #36=CIRCLE('',#84,34.925); #37=VERTEX_POINT('',#109); #38=VERTEX_POINT('',#111); #39=VERTEX_POINT('',#115); #40=VERTEX_POINT('',#117); #41=EDGE_CURVE('',#37,#37,#33,.T.); #42=EDGE_CURVE('',#37,#38,#29,.T.); #43=EDGE_CURVE('',#38,#38,#34,.T.); #44=EDGE_CURVE('',#39,#39,#35,.T.); #45=EDGE_CURVE('',#39,#40,#30,.T.); #46=EDGE_CURVE('',#40,#40,#36,.T.); #47=ORIENTED_EDGE('',*,*,#41,.F.); #48=ORIENTED_EDGE('',*,*,#42,.T.); #49=ORIENTED_EDGE('',*,*,#43,.F.); #50=ORIENTED_EDGE('',*,*,#42,.F.); #51=ORIENTED_EDGE('',*,*,#44,.F.); #52=ORIENTED_EDGE('',*,*,#45,.T.); #53=ORIENTED_EDGE('',*,*,#46,.T.); #54=ORIENTED_EDGE('',*,*,#45,.F.); #55=ORIENTED_EDGE('',*,*,#44,.T.); #56=ORIENTED_EDGE('',*,*,#41,.T.); #57=ORIENTED_EDGE('',*,*,#46,.F.); #58=ORIENTED_EDGE('',*,*,#43,.T.); #59=CYLINDRICAL_SURFACE('',#79,6.45); #60=CYLINDRICAL_SURFACE('',#82,34.925); #61=ADVANCED_FACE('',(#19),#59,.F.); #62=ADVANCED_FACE('',(#20),#60,.T.); #63=ADVANCED_FACE('',(#21,#15),#17,.T.); #64=ADVANCED_FACE('',(#22,#16),#18,.F.); #65=CLOSED_SHELL('',(#61,#62,#63,#64)); #66=DERIVED_UNIT_ELEMENT(#68,1.); #67=DERIVED_UNIT_ELEMENT(#127,3.); #68=( MASS_UNIT() NAMED_UNIT(*) SI_UNIT(.KILO.,.GRAM.) ); #69=DERIVED_UNIT((#66,#67)); #70=MEASURE_REPRESENTATION_ITEM('density measure', POSITIVE_RATIO_MEASURE(7850.),#69); #71=PROPERTY_DEFINITION_REPRESENTATION(#76,#73); #72=PROPERTY_DEFINITION_REPRESENTATION(#77,#74); #73=REPRESENTATION('material name',(#75),#124); #74=REPRESENTATION('density',(#70),#124); #75=DESCRIPTIVE_REPRESENTATION_ITEM('Steel','Steel'); #76=PROPERTY_DEFINITION('material property','material name',#134); #77=PROPERTY_DEFINITION('material property','density of part',#134); #78=AXIS2_PLACEMENT_3D('placement',#107,#87,#88); #79=AXIS2_PLACEMENT_3D('',#108,#89,#90); #80=AXIS2_PLACEMENT_3D('',#110,#91,#92); #81=AXIS2_PLACEMENT_3D('',#113,#94,#95); #82=AXIS2_PLACEMENT_3D('',#114,#96,#97); #83=AXIS2_PLACEMENT_3D('',#116,#98,#99); #84=AXIS2_PLACEMENT_3D('',#119,#101,#102); #85=AXIS2_PLACEMENT_3D('',#120,#103,#104); #86=AXIS2_PLACEMENT_3D('',#121,#105,#106); #87=DIRECTION('axis',(0.,0.,1.)); #88=DIRECTION('refdir',(1.,0.,0.)); #89=DIRECTION('center_axis',(0.,0.,-1.)); #90=DIRECTION('ref_axis',(-1.,0.,0.)); #91=DIRECTION('center_axis',(0.,0.,-1.)); #92=DIRECTION('ref_axis',(-1.,0.,0.)); #93=DIRECTION('',(0.,0.,-1.)); #94=DIRECTION('center_axis',(0.,0.,1.)); #95=DIRECTION('ref_axis',(-1.,0.,0.)); #96=DIRECTION('center_axis',(0.,0.,1.)); #97=DIRECTION('ref_axis',(1.,0.,0.)); #98=DIRECTION('center_axis',(0.,0.,1.)); #99=DIRECTION('ref_axis',(1.,0.,0.)); #100=DIRECTION('',(0.,0.,-1.)); #101=DIRECTION('center_axis',(0.,0.,1.)); #102=DIRECTION('ref_axis',(1.,0.,0.)); #103=DIRECTION('center_axis',(0.,0.,1.)); #104=DIRECTION('ref_axis',(1.,0.,0.)); #105=DIRECTION('center_axis',(0.,0.,1.)); #106=DIRECTION('ref_axis',(1.,0.,0.)); #107=CARTESIAN_POINT('',(0.,0.,0.)); #108=CARTESIAN_POINT('Origin',(0.,0.,12.7)); #109=CARTESIAN_POINT('',(6.45,7.89897185450043E-16,12.7)); #110=CARTESIAN_POINT('Origin',(0.,0.,12.7)); #111=CARTESIAN_POINT('',(6.45,7.89897185450043E-16,0.)); #112=CARTESIAN_POINT('',(6.45,-7.89897185450043E-16,12.7)); #113=CARTESIAN_POINT('Origin',(0.,0.,0.)); #114=CARTESIAN_POINT('Origin',(0.,0.,0.)); #115=CARTESIAN_POINT('',(-34.925,-4.27707894602213E-15,12.7)); #116=CARTESIAN_POINT('Origin',(0.,0.,12.7)); #117=CARTESIAN_POINT('',(-34.925,-4.27707894602213E-15,0.)); #118=CARTESIAN_POINT('',(-34.925,-4.27707894602213E-15,0.)); #119=CARTESIAN_POINT('Origin',(0.,0.,0.)); #120=CARTESIAN_POINT('Origin',(0.,0.,12.7)); #121=CARTESIAN_POINT('Origin',(0.,0.,0.)); #122=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(0.01),#126, 'DISTANCE_ACCURACY_VALUE', 'Maximum model space distance between geometric entities at asserted c onnectivities'); #123=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(0.01),#126, 'DISTANCE_ACCURACY_VALUE', 'Maximum model space distance between geometric entities at asserted c onnectivities'); #124=( GEOMETRIC_REPRESENTATION_CONTEXT(3) GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#122)) GLOBAL_UNIT_ASSIGNED_CONTEXT((#126,#128,#129)) REPRESENTATION_CONTEXT('','3D') ); #125=( GEOMETRIC_REPRESENTATION_CONTEXT(3) GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#123)) GLOBAL_UNIT_ASSIGNED_CONTEXT((#126,#128,#129)) REPRESENTATION_CONTEXT('','3D') ); #126=( LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT(.MILLI.,.METRE.) ); #127=( LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT($,.METRE.) ); #128=( NAMED_UNIT(*) PLANE_ANGLE_UNIT() SI_UNIT($,.RADIAN.) ); #129=( NAMED_UNIT(*) SI_UNIT($,.STERADIAN.) SOLID_ANGLE_UNIT() ); #130=SHAPE_DEFINITION_REPRESENTATION(#131,#132); #131=PRODUCT_DEFINITION_SHAPE('',$,#134); #132=SHAPE_REPRESENTATION('',(#78),#124); #133=PRODUCT_DEFINITION_CONTEXT('part definition',#138,'design'); #134=PRODUCT_DEFINITION('2-Roller_Insert v1','2-Roller_Insert v1 v3',#135, #133); #135=PRODUCT_DEFINITION_FORMATION('',$,#140); #136=PRODUCT_RELATED_PRODUCT_CATEGORY('2-Roller_Insert v1 v3', '2-Roller_Insert v1 v3',(#140)); #137=APPLICATION_PROTOCOL_DEFINITION('international standard', 'automotive_design',2009,#138); #138=APPLICATION_CONTEXT( 'Core Data for Automotive Mechanical Design Process'); #139=PRODUCT_CONTEXT('part definition',#138,'mechanical'); #140=PRODUCT('2-Roller_Insert v1','2-Roller_Insert v1 v3',$,(#139)); #141=PRESENTATION_STYLE_ASSIGNMENT((#143)); #142=PRESENTATION_STYLE_ASSIGNMENT((#144)); #143=SURFACE_STYLE_USAGE(.BOTH.,#145); #144=SURFACE_STYLE_USAGE(.BOTH.,#146); #145=SURFACE_SIDE_STYLE('',(#147)); #146=SURFACE_SIDE_STYLE('',(#148)); #147=SURFACE_STYLE_FILL_AREA(#149); #148=SURFACE_STYLE_FILL_AREA(#150); #149=FILL_AREA_STYLE('Steel - Satin',(#151)); #150=FILL_AREA_STYLE('Plastic - Translucent Glossy (Blue)',(#152)); #151=FILL_AREA_STYLE_COLOUR('Steel - Satin',#153); #152=FILL_AREA_STYLE_COLOUR('Plastic - Translucent Glossy (Blue)',#154); #153=COLOUR_RGB('Steel - Satin',0.627450980392157,0.627450980392157,0.627450980392157); #154=COLOUR_RGB('Plastic - Translucent Glossy (Blue)',0.188235294117647, 0.231372549019608,0.588235294117647); ENDSEC; END-ISO-10303-21;
{ "pile_set_name": "Github" }
alter_onetable_stmt ::= 'ALTER' 'TABLE' table_name 'ADD' 'CONSTRAINT' constraint_name constraint_elem opt_validate_behavior | 'ALTER' 'TABLE' 'IF' 'EXISTS' table_name 'ADD' 'CONSTRAINT' constraint_name constraint_elem opt_validate_behavior
{ "pile_set_name": "Github" }
/* * Copyright (c) 2016-2019 "Neo4j Sweden, AB" [https://neo4j.com] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Attribution Notice under the terms of the Apache License 2.0 * * This work was created by the collective efforts of the openCypher community. * Without limiting the terms of Section 6, any Derivative Work that is not * approved by the public consensus process of the openCypher Implementers Group * should not be described as “Cypher” (and Cypher® is a registered trademark of * Neo4j Inc.) or as "openCypher". Extensions by implementers or prototypes or * proposals for change that have been documented or implemented should only be * described as "implementation extensions to Cypher" or as "proposed changes to * Cypher that are not yet approved by the openCypher community". */ package org.opencypher.okapi.logical.impl import org.opencypher.okapi.api.types.{CTBoolean, CTRelationship} import org.opencypher.okapi.impl.exception.IllegalArgumentException import org.opencypher.okapi.ir.api.block.Block import org.opencypher.okapi.ir.api.expr.{Expr, HasType, Ors} import org.opencypher.okapi.ir.api.pattern.Pattern import org.opencypher.okapi.ir.api.{IRField, RelType} import org.opencypher.okapi.ir.impl.util.VarConverters.toVar case class SolvedQueryModel( fields: Set[IRField], predicates: Set[Expr] = Set.empty ) { // extension def withField(f: IRField): SolvedQueryModel = copy(fields = fields + f) def withFields(fs: IRField*): SolvedQueryModel = copy(fields = fields ++ fs) def withPredicate(pred: Expr): SolvedQueryModel = copy(predicates = predicates + pred) def withPredicates(preds: Expr*): SolvedQueryModel = copy(predicates = predicates ++ preds) def ++(other: SolvedQueryModel): SolvedQueryModel = copy(fields ++ other.fields, predicates ++ other.predicates) // containment def contains(blocks: Block*): Boolean = contains(blocks.toSet) def contains(blocks: Set[Block]): Boolean = blocks.forall(contains) def contains(block: Block): Boolean = { val bindsFields = block.binds.fields subsetOf fields val preds = block.where subsetOf predicates bindsFields && preds } def solves(f: IRField): Boolean = fields(f) def solves(p: Pattern): Boolean = p.fields.subsetOf(fields) def solveRelationship(r: IRField): SolvedQueryModel = { r.cypherType match { case CTRelationship(types, _) if types.isEmpty => withField(r) case CTRelationship(types, _) => val predicate = if (types.size == 1) HasType(r, RelType(types.head)) else Ors(types.map(t => HasType(r, RelType(t))).toSeq: _*) withField(r).withPredicate(predicate) case _ => throw IllegalArgumentException("a relationship variable", r) } } } object SolvedQueryModel { def empty: SolvedQueryModel = SolvedQueryModel(Set.empty, Set.empty) }
{ "pile_set_name": "Github" }
enum = foo();
{ "pile_set_name": "Github" }
(* Correctness proof for flat_to_clos *) open preamble semanticPrimitivesTheory semanticPrimitivesPropsTheory flatLangTheory flatSemTheory flatPropsTheory backendPropsTheory closLangTheory closSemTheory closPropsTheory flat_to_closTheory; local open helperLib in end; val _ = new_theory"flat_to_closProof" val _ = set_grammar_ancestry ["misc","ffi","flatProps","closProps", "flat_to_clos","backendProps","backend_common"]; Theorem LIST_REL_EL: (* TODO: move *) !xs ys r. LIST_REL r xs ys <=> (LENGTH xs = LENGTH ys) /\ !n. n < LENGTH ys ==> r (EL n xs) (EL n ys) Proof Induct \\ Cases_on `ys` \\ fs [] \\ rw [] \\ eq_tac \\ rw [] THEN1 (Cases_on `n` \\ fs []) THEN1 (first_x_assum (qspec_then `0` mp_tac) \\ fs []) \\ first_x_assum (qspec_then `SUC n` mp_tac) \\ fs [] QED Inductive v_rel: (!n. v_rel (Loc n) (RefPtr n)) /\ (!i. v_rel (Litv (IntLit i)) (Number i)) /\ (!c. v_rel (Litv (Char c)) (Number (& (ORD c)))) /\ (!s. v_rel (Litv (StrLit s)) (ByteVector (MAP (n2w o ORD) s))) /\ (!b. v_rel (Litv (Word8 b)) (Number (& (w2n b)))) /\ (!w. v_rel (Litv (Word64 w)) (Word64 w)) /\ (!vs ws. LIST_REL v_rel vs ws ==> v_rel (Conv NONE vs) (Block 0 ws)) /\ (!vs ws t r. LIST_REL v_rel vs ws ==> v_rel (Conv (SOME (t,r)) vs) (Block t ws)) /\ (!vs ws. LIST_REL v_rel vs ws ==> v_rel (Vectorv vs) (Block 0 ws)) /\ (!env m db. (!n x. ALOOKUP env.v n = SOME x ==> findi (SOME n) m < LENGTH db /\ v_rel x (EL (findi (SOME n) m) db)) ==> env_rel env (m:string option list) (db:closSem$v list)) /\ (!env m db n e. env_rel env m db /\ no_Mat e ==> v_rel (Closure env.v n e) (Closure NONE [] db 1 (HD (compile (SOME n::m) [e])))) /\ (!funs n env m db. n < LENGTH funs /\ env_rel env m db /\ ALL_DISTINCT (MAP FST funs) /\ EVERY no_Mat (MAP (SND o SND) funs) ==> v_rel (Recclosure env.v funs (FST (EL n funs))) (Recclosure NONE [] db (MAP (λ(f,v,x). (1, HD (compile (SOME v::(MAP (λn. SOME (FST n)) funs ++ m)) [x]))) funs) n)) End Theorem v_rel_def = [``v_rel (Loc n) x1``, ``v_rel (Litv (IntLit l1)) x1``, ``v_rel (Litv (StrLit s)) x1``, ``v_rel (Litv (Char c)) x1``, ``v_rel (Litv (Word8 b)) x1``, ``v_rel (Litv (Word64 w)) x1``, ``v_rel (Vectorv y) x1``, ``v_rel (Conv x y) x1``, ``v_rel (Closure x y z) x1``, ``v_rel (Recclosure x y t) x1``] |> map (SIMP_CONV (srw_ss()) [Once v_rel_cases]) |> LIST_CONJ Theorem env_rel_def = ``env_rel env m db`` |> ONCE_REWRITE_CONV [v_rel_cases]; Definition opt_rel_def[simp]: opt_rel f NONE NONE = T /\ opt_rel f (SOME x) (SOME y) = f x y /\ opt_rel f _ _ = F End Definition store_rel_def: store_rel refs t_refs = !i. if LENGTH refs <= i then FLOOKUP t_refs i = NONE else case EL i refs of | Refv v => (?x. FLOOKUP t_refs i = SOME (ValueArray [x]) /\ v_rel v x) | Varray vs => (?xs. FLOOKUP t_refs i = SOME (ValueArray xs) /\ LIST_REL v_rel vs xs) | W8array bs => FLOOKUP t_refs i = SOME (ByteArray F bs) End Definition state_rel_def: state_rel (s:'ffi flatSem$state) (t:('c,'ffi) closSem$state) <=> s.check_ctor /\ 1 <= t.max_app /\ s.ffi = t.ffi /\ s.clock = t.clock /\ store_rel s.refs t.refs /\ LIST_REL (opt_rel v_rel) s.globals t.globals End Theorem v_rel_to_list: !x y xs. v_rel x y /\ flatSem$v_to_list x = SOME xs ==> ?ys. closSem$v_to_list y = SOME ys /\ LIST_REL v_rel xs ys Proof ho_match_mp_tac flatSemTheory.v_to_list_ind \\ fs [v_rel_def] \\ rpt strip_tac \\ fs [flatSemTheory.v_to_list_def,v_to_list_def] \\ rveq \\ fs [] \\ fs [option_case_eq] \\ rveq \\ fs [PULL_EXISTS] QED Theorem IMP_v_rel_to_list: !xs ys. LIST_REL v_rel xs ys ==> v_rel (list_to_v xs) (list_to_v ys) Proof Induct \\ Cases_on `ys` \\ fs [flatSemTheory.list_to_v_def,list_to_v_def,v_rel_def] QED Theorem lookup_byte_array: state_rel s1 t1 /\ store_lookup i s1.refs = SOME (W8array bytes) ==> FLOOKUP t1.refs i = SOME (ByteArray F bytes) Proof fs [state_rel_def,store_rel_def] \\ rw [] \\ fs [store_lookup_def] \\ first_x_assum (qspec_then `i` mp_tac) \\ fs [] QED Theorem lookup_array: state_rel s1 t1 /\ store_lookup i s1.refs = SOME (Varray vs) ==> ?ws. FLOOKUP t1.refs i = SOME (ValueArray ws) /\ LIST_REL v_rel vs ws Proof fs [state_rel_def,store_rel_def] \\ rw [] \\ fs [store_lookup_def] \\ first_x_assum (qspec_then `i` mp_tac) \\ fs [] QED Triviality env_rel_CONS: env_rel <| v := xs |> m db /\ v_rel v1 v2 ==> env_rel <| v := (n,v1) :: xs |> (SOME n :: m) (v2 :: db) Proof fs [env_rel_def,findi_def,GSYM ADD1] \\ rw [] \\ fs [] \\ rw [] \\ fs [] QED Triviality env_rel_APPEND: !name_prefix prefix db_prefix env m db. env_rel env m db /\ LIST_REL v_rel (MAP SND prefix) db_prefix /\ name_prefix = MAP (SOME o FST) prefix ==> env_rel <| v := prefix ++ env.v |> (name_prefix ++ m) (db_prefix ++ db) Proof Induct \\ fs [] THEN1 (rw[env_rel_def]) \\ Cases_on `prefix` \\ fs [PULL_EXISTS] \\ rw [] \\ PairCases_on `h` \\ fs [] \\ match_mp_tac env_rel_CONS \\ fs [] QED Theorem state_rel_initial_state: 0 < max_app ==> state_rel (initial_state ffi k T) (initial_state ffi max_app FEMPTY co cc k) Proof fs [state_rel_def,flatSemTheory.initial_state_def,initial_state_def,store_rel_def] QED Triviality state_rel_IMP_check_ctor: state_rel s t ==> s.check_ctor Proof fs [state_rel_def] QED val goal = ``\env (s:'ffi flatSem$state) es. !m db res1 s1 (t:('c,'ffi) closSem$state). evaluate env s es = (s1,res1) /\ state_rel s t /\ env_rel env m db /\ EVERY no_Mat es /\ res1 <> Rerr (Rabort Rtype_error) ==> ?res2 t1. evaluate (compile m es, db, t) = (res2,t1) /\ state_rel s1 t1 /\ result_rel (LIST_REL v_rel) v_rel res1 res2`` local val ind_thm = flatSemTheory.evaluate_ind |> ISPEC goal |> CONV_RULE (DEPTH_CONV BETA_CONV) |> REWRITE_RULE []; val ind_goals = ind_thm |> concl |> dest_imp |> fst |> helperLib.list_dest dest_conj in fun get_goal s = first (can (find_term (can (match_term (Term [QUOTE s]))))) ind_goals fun compile_correct_tm () = ind_thm |> concl |> rand fun the_ind_thm () = ind_thm end Theorem compile_nil: ^(get_goal "[]") Proof fs [evaluate_def,flatSemTheory.evaluate_def,compile_def] QED Theorem compile_cons: ^(get_goal "_::_::_") Proof rpt strip_tac \\ fs [evaluate_def,compile_def,flatSemTheory.evaluate_def] \\ fs [pair_case_eq] \\ fs [] \\ first_x_assum drule \\ disch_then drule \\ impl_tac THEN1 (CCONTR_TAC \\ fs []) \\ strip_tac \\ fs [evaluate_APPEND] \\ fs [result_case_eq] \\ rveq \\ fs [] \\ fs [pair_case_eq] \\ fs [] \\ rveq \\ fs [] \\ first_x_assum drule \\ disch_then drule \\ impl_tac THEN1 (CCONTR_TAC \\ fs []) \\ strip_tac \\ fs [] \\ qpat_x_assum `_ = (s1,res1)` mp_tac \\ TOP_CASE_TAC \\ fs [] \\ strip_tac \\ rveq \\ fs [] \\ imp_res_tac evaluate_sing \\ fs [] \\ rveq \\ fs [] QED Theorem compile_Lit: ^(get_goal "flatLang$Lit") Proof fs [flatSemTheory.evaluate_def,compile_def] \\ Cases_on `l` \\ fs [PULL_EXISTS] \\ once_rewrite_tac [CONJUNCT2 v_rel_cases] \\ fs [] \\ fs [compile_lit_def,evaluate_def,do_app_def] QED Theorem compile_Raise: ^(get_goal "flatLang$Raise") Proof fs [evaluate_def,flatSemTheory.evaluate_def,compile_def] \\ rw [] \\ reverse (fs [pair_case_eq,result_case_eq]) \\ rveq \\ fs [] \\ first_x_assum drule \\ disch_then drule \\ strip_tac \\ rveq \\ fs [] \\ imp_res_tac flatPropsTheory.evaluate_sing \\ fs [] QED Theorem dest_pat_from_case: (case pes of [(Pvar _, _)] => T | _ => F) ==> ?nm rhs. dest_pat pes = SOME (nm, rhs) Proof EVERY_CASE_TAC \\ simp [dest_pat_def] QED Theorem compile_Handle: ^(get_goal "flatLang$Handle") Proof rpt strip_tac \\ fs [evaluate_def,compile_def,flatSemTheory.evaluate_def] \\ fs [pair_case_eq] \\ fs [] \\ imp_res_tac dest_pat_from_case \\ fs [] \\ fs [dest_pat_thm] \\ rveq \\ fs [] \\ fs [flatSemTheory.evaluate_def,evaluate_def, EVAL ``ALL_DISTINCT (pat_bindings (Pvar x) [])``, EVAL ``pmatch s' (Pvar x) v []``,pmatch_rows_def] \\ first_x_assum drule \\ disch_then drule \\ impl_tac THEN1 (CCONTR_TAC \\ fs []) \\ strip_tac \\ fs [] \\ fs [result_case_eq] \\ rveq \\ fs [] \\ rveq \\ fs [] \\ fs [error_result_case_eq] \\ rveq \\ fs [] \\ rveq \\ fs [] \\ first_x_assum drule \\ rename [`v_rel v1 v2`] \\ `env_rel <|v := (nm,v1)::env.v|> (SOME nm::m) (v2::db)` by (match_mp_tac env_rel_CONS \\ fs [env_rel_def]) \\ disch_then drule \\ strip_tac \\ fs [] QED Theorem compile_Let: ^(get_goal "flatLang$Let") Proof rpt strip_tac \\ fs [evaluate_def,compile_def,flatSemTheory.evaluate_def] \\ fs [pair_case_eq] \\ fs [] \\ first_x_assum drule \\ disch_then drule \\ impl_tac THEN1 (CCONTR_TAC \\ fs []) \\ strip_tac \\ fs [] \\ fs [result_case_eq] \\ rveq \\ fs [] \\ rveq \\ fs [] \\ first_x_assum drule \\ imp_res_tac evaluate_sing \\ fs [] \\ rveq \\ fs [] \\ rename [`v_rel v1 v2`] \\ `env_rel (env with v updated_by opt_bind n v1) (n::m) (v2::db)` by (fs [env_rel_def] \\ Cases_on `n` \\ fs [libTheory.opt_bind_def,findi_def,GSYM ADD1] \\ rw [] \\ fs []) \\ disch_then drule \\ strip_tac \\ fs [] QED Triviality LIST_REL_MAP_GENLIST: !funs f1 f2 R. (!n. n < LENGTH funs ==> R (f1 (EL n funs)) (f2 n)) ==> LIST_REL R (MAP f1 funs) (GENLIST f2 (LENGTH funs)) Proof recInduct SNOC_INDUCT \\ fs [] \\ fs [GENLIST,MAP_SNOC,LIST_REL_SNOC] \\ rpt strip_tac THEN1 (first_x_assum match_mp_tac \\ metis_tac [EL_SNOC,DECIDE ``n<m ==> n < SUC m``]) \\ first_x_assum (qspec_then `LENGTH l` mp_tac) \\ fs [SNOC_APPEND,EL_LENGTH_APPEND] QED Theorem compile_Letrec: ^(get_goal "flatLang$Letrec") Proof rpt strip_tac \\ fs [evaluate_def,compile_def,flatSemTheory.evaluate_def] \\ fs [EVERY_MAP] \\ CONV_TAC (DEPTH_CONV PairRules.PBETA_CONV) \\ fs [] \\ rpt strip_tac \\ `1 <= t.max_app` by fs [state_rel_def] \\ fs [] \\ fs [bool_case_eq] \\ qpat_x_assum `(_,_) = _` (assume_tac o GSYM) \\ fs [] \\ qmatch_goalsub_abbrev_tac `GENLIST recc` \\ first_x_assum drule \\ disch_then match_mp_tac \\ fs [build_rec_env_eq_MAP] \\ match_mp_tac env_rel_APPEND \\ fs [] \\ reverse conj_tac THEN1 (qspec_tac (`Recclosure env.v funs`,`rr`) \\ qid_spec_tac `funs` \\ Induct \\ fs [FORALL_PROD]) \\ fs [MAP_MAP_o,o_DEF] \\ CONV_TAC (DEPTH_CONV PairRules.PBETA_CONV) \\ fs [] \\ match_mp_tac LIST_REL_MAP_GENLIST \\ fs [Abbr`recc`] \\ once_rewrite_tac [v_rel_cases] \\ fs [] \\ rw [] \\ qexists_tac `env` \\ qexists_tac `m` \\ fs [o_DEF] \\ simp [EVERY_MAP] QED Theorem compile_Fun: ^(get_goal "flatLang$Fun") Proof fs [evaluate_def,flatSemTheory.evaluate_def,PULL_EXISTS,compile_def] \\ rpt strip_tac \\ `1 <= t.max_app` by fs [state_rel_def] \\ fs [] \\ once_rewrite_tac [v_rel_cases] \\ fs [] \\ metis_tac [] QED Theorem compile_Con: ^(get_goal "flatLang$Con") /\ ^(get_goal "s.check_ctor ∧ _") Proof rpt strip_tac \\ fs [evaluate_def,compile_def,flatSemTheory.evaluate_def] \\ imp_res_tac state_rel_IMP_check_ctor \\ fs [] \\ fs [pair_case_eq,CaseEq"bool"] \\ fs [] \\ first_x_assum drule \\ fs [EVERY_REVERSE, Q.ISPEC `no_Mat` ETA_THM] \\ (disch_then drule \\ impl_tac THEN1 (CCONTR_TAC \\ fs [])) \\ strip_tac \\ fs [] \\ fs [result_case_eq] \\ rveq \\ fs [] \\ rveq \\ fs [] \\ fs [do_app_def] \\ once_rewrite_tac [v_rel_cases] \\ fs [] \\ PairCases_on `cn` \\ fs [] QED Theorem compile_Var_local: ^(get_goal "flatLang$Var_local") Proof fs [evaluate_def,flatSemTheory.evaluate_def,compile_def] \\ rpt strip_tac \\ pop_assum mp_tac \\ TOP_CASE_TAC \\ fs [env_rel_def] QED Triviality find_recfun_EL: !l0 n. n < LENGTH l0 /\ ALL_DISTINCT (MAP FST l0) ==> find_recfun (FST (EL n l0)) l0 = SOME (SND (EL n l0)) Proof Induct \\ fs [] \\ simp [Once find_recfun_def,FORALL_PROD] \\ rpt strip_tac \\ Cases_on `n` \\ fs [] \\ rw [] \\ fs [MEM_MAP] \\ fs [FORALL_PROD] \\ fs [MEM_EL] \\ metis_tac [PAIR,PAIR_EQ,FST] QED Triviality IMP_PAIR: z = (x,y) ==> x = FST z /\ y = SND z Proof Cases_on `z` \\ fs [] QED Theorem compile_If: ^(get_goal "flatLang$If") Proof rpt strip_tac \\ fs [evaluate_def,compile_def,flatSemTheory.evaluate_def] \\ fs [pair_case_eq] \\ fs [] \\ first_x_assum drule \\ disch_then drule \\ impl_tac THEN1 (CCONTR_TAC \\ fs []) \\ strip_tac \\ fs [] \\ fs [result_case_eq] \\ rveq \\ fs [] \\ imp_res_tac evaluate_sing \\ fs [] \\ rveq \\ fs [] \\ fs [option_case_eq] \\ fs [] \\ fs [do_if_def,bool_case_eq] \\ rveq \\ fs [] \\ first_x_assum drule \\ disch_then drule \\ strip_tac \\ fs [] \\ fs [flatSemTheory.Boolv_def] \\ qpat_x_assum `v_rel _ _` mp_tac \\ once_rewrite_tac [v_rel_cases] \\ fs [Boolv_def] QED Theorem compile_Mat: ^(get_goal "flatLang$Mat") Proof fs [no_Mat_def,dest_pat_thm] \\ rw [] \\ fs [EVAL ``pmatch s (Pvar p') v []``] \\ fs [EVAL ``ALL_DISTINCT (pat_bindings (Pvar p') [])``] QED Theorem state_rel_LEAST: state_rel s1 t1 ==> (LEAST ptr. ptr ∉ FDOM t1.refs) = LENGTH s1.refs Proof fs [state_rel_def,store_rel_def] \\ rw [] \\ ho_match_mp_tac (whileTheory.LEAST_ELIM |> ISPEC ``\x. x = LENGTH s1.refs`` |> CONV_RULE (DEPTH_CONV BETA_CONV)) \\ fs [] \\ rpt strip_tac \\ fs [FLOOKUP_DEF] THEN1 (first_x_assum (qspec_then `LENGTH s1.refs` mp_tac) \\ fs [] \\ rw [] \\ asm_exists_tac \\ fs []) \\ `!i. i IN FDOM t1.refs <=> ~(LENGTH s1.refs <= i)` by (strip_tac \\ last_x_assum (qspec_then `i` mp_tac) \\ rw [] \\ every_case_tac \\ fs[]) \\ fs [] \\ CCONTR_TAC \\ fs [] \\ `LENGTH s1.refs < ptr` by fs [] \\ res_tac \\ fs [] QED Theorem compile_op_evaluates_args: evaluate (xs,db,t) = (Rerr err,t1) /\ op <> Opapp ==> evaluate ([compile_op tra op xs],db,t) = (Rerr err,t1) Proof Cases_on `op` \\ fs [compile_op_def,evaluate_def,evaluate_APPEND,arg1_def,arg2_def] \\ every_case_tac \\ fs [evaluate_def] \\ fs [pair_case_eq,result_case_eq] \\ rw [] \\ fs [PULL_EXISTS,do_app_def] QED Theorem v_rel_Boolv[simp]: v_rel (Boolv b) v = (v = Boolv b) Proof Cases_on `b` \\ fs [Once v_rel_cases,flatSemTheory.Boolv_def] \\ rw [] \\ eq_tac \\ rw [] \\ EVAL_TAC QED val op_goal = ``do_app T s1 op vs = SOME (s2,res2) /\ state_rel s1 (t1:('c,'ffi) closSem$state) /\ evaluate (xs,db,t) = (Rval ws,t1) /\ LIST_REL v_rel vs (REVERSE ws) /\ LENGTH xs = LENGTH vs /\ op <> Opapp ==> ∃res2' t1. evaluate ([compile_op tt op xs],db,t) = (res2',t1) ∧ state_rel s2 t1 ∧ result_rel (LIST_REL v_rel) v_rel (list_result res2) res2'`` Theorem op_refs: (op = Opref) \/ (?n. op = El n) \/ (op = Opassign) ==> ^op_goal Proof Cases_on `op = Opref` THEN1 (fs [flatSemTheory.do_app_def,list_case_eq,CaseEq "flatSem$v",PULL_EXISTS, CaseEq "ast$lit",store_assign_def,option_case_eq] \\ rw [] \\ fs [] \\ rveq \\ fs [LENGTH_EQ_NUM_compute] \\ rveq \\ fs [] \\ fs [store_alloc_def] \\ rveq \\ fs [PULL_EXISTS] \\ simp [Once v_rel_cases] \\ fs [compile_op_def,evaluate_def,do_app_def,arg1_def] \\ imp_res_tac state_rel_LEAST \\ fs [] \\ fs [state_rel_def,store_rel_def] \\ strip_tac \\ first_assum (qspec_then `i` mp_tac) \\ rewrite_tac [GSYM NOT_LESS,FLOOKUP_UPDATE,EL_LUPDATE] \\ Cases_on `LENGTH s1.refs = i` \\ rveq \\ fs [EL_LENGTH_APPEND] \\ IF_CASES_TAC \\ fs [EL_APPEND1]) \\ Cases_on `?n. op = El n` THEN1 (fs [flatSemTheory.do_app_def,list_case_eq,CaseEq "flatSem$v",PULL_EXISTS, CaseEq "ast$lit",store_assign_def,option_case_eq] \\ rw [] \\ fs [] \\ rveq \\ fs [LENGTH_EQ_NUM_compute] \\ rveq \\ fs [] THEN1 (qpat_x_assum `v_rel (Conv _ _) _` mp_tac \\ simp [Once v_rel_cases] \\ rw [] \\ fs [compile_op_def,arg1_def] \\ fs [compile_op_def,evaluate_def,do_app_def,arg1_def] \\ imp_res_tac LIST_REL_LENGTH \\ fs [] \\ fs [LIST_REL_EL]) \\ qpat_x_assum `v_rel (Loc _) _` mp_tac \\ simp [Once v_rel_cases] \\ Cases_on `v2` \\ fs [] \\ fs [SWAP_REVERSE_SYM] \\ rw [] \\ fs [PULL_EXISTS] \\ fs [compile_op_def,evaluate_def,do_app_def,arg1_def] \\ fs [pair_case_eq,result_case_eq] \\ rveq \\ fs [] \\ fs [state_rel_def,store_rel_def,store_lookup_def] \\ rename [`i < LENGTH s1.refs`] \\ first_assum (qspec_then `i` mp_tac) \\ rewrite_tac [GSYM NOT_LESS] \\ Cases_on `EL i s1.refs` \\ fs [store_v_same_type_def] \\ rpt strip_tac \\ fs [] \\ strip_tac \\ fs [GSYM NOT_LESS,FLOOKUP_UPDATE,EL_LUPDATE]) \\ Cases_on `op = Opassign` THEN1 (fs [flatSemTheory.do_app_def,list_case_eq,CaseEq "flatSem$v",PULL_EXISTS, CaseEq "ast$lit",store_assign_def,option_case_eq] \\ rw [] \\ fs [] \\ rveq \\ fs [LENGTH_EQ_NUM_compute] \\ rveq \\ fs [] \\ qpat_x_assum `v_rel (Loc _) _` mp_tac \\ simp [Once v_rel_cases] \\ fs [SWAP_REVERSE_SYM] \\ rw [] \\ fs [PULL_EXISTS] \\ fs [compile_op_def,evaluate_def,do_app_def] \\ fs [pair_case_eq,result_case_eq] \\ rveq \\ fs [] \\ imp_res_tac evaluate_SING \\ rveq \\ fs [] \\ rveq \\ fs [] \\ fs [arg2_def,evaluate_def,do_app_def] \\ fs [state_rel_def,store_rel_def] \\ rename [`i < LENGTH s1.refs`] \\ first_assum (qspec_then `i` mp_tac) \\ rewrite_tac [GSYM NOT_LESS] \\ Cases_on `EL i s1.refs` \\ fs [store_v_same_type_def] \\ rpt strip_tac \\ fs [] \\ reverse conj_tac THEN1 (simp [Unit_def,Once v_rel_cases] \\ EVAL_TAC) \\ strip_tac \\ fs [GSYM NOT_LESS,FLOOKUP_UPDATE,EL_LUPDATE] \\ rename [`if i = j then _ else _`] \\ Cases_on `i = j` \\ fs [] \\ fs [LUPDATE_def]) \\ fs [] QED Theorem op_chars: (?chop. op = Chopb chop) \/ (op = Ord) \/ (op = Chr) ==> ^op_goal Proof Cases_on `?chop. op = Chopb chop` THEN1 (fs [] \\ Cases_on `chop` \\ fs [flatSemTheory.do_app_def,list_case_eq,CaseEq "flatSem$v",PULL_EXISTS, CaseEq "ast$lit"] \\ rw [] \\ fs [] \\ rveq \\ fs [LENGTH_EQ_NUM_compute] \\ rveq \\ fs [] \\ qpat_x_assum `v_rel _ _` mp_tac \\ simp [Once v_rel_cases] \\ qpat_x_assum `v_rel _ _` mp_tac \\ simp [Once v_rel_cases] \\ fs [SWAP_REVERSE_SYM] \\ rw [] \\ fs [compile_op_def,evaluate_def,do_app_def,opb_lookup_def]) \\ Cases_on `op = Ord \/ op = Chr` THEN1 (fs [flatSemTheory.do_app_def,list_case_eq,CaseEq "flatSem$v",PULL_EXISTS, CaseEq "ast$lit"] \\ rw [] \\ fs [] \\ rveq \\ fs [LENGTH_EQ_NUM_compute] \\ qpat_x_assum `v_rel _ _` mp_tac \\ simp [Once v_rel_cases] \\ rw [] \\ fs [compile_op_def,evaluate_def,evaluate_APPEND,do_app_def,evaluate_def,arg1_def] \\ simp [Once v_rel_cases] \\ rw [ORD_CHR,chr_exn_v_def] \\ TRY (rename1 `~(ii < 0i)` \\ Cases_on `ii` \\ fs []) \\ TRY (rename1 `(0i <= ii)` \\ Cases_on `ii` \\ fs []) \\ `F` by intLib.COOPER_TAC) \\ rw [] \\ fs [] QED Theorem op_ints: (?b. op = Opb b) \/ (?b. op = Opn b) ==> ^op_goal Proof rpt strip_tac \\ Cases_on `b` \\ rveq \\ fs [flatSemTheory.do_app_def,list_case_eq,CaseEq "flatSem$v",PULL_EXISTS, CaseEq "ast$lit",store_assign_def,option_case_eq,CaseEq "store_v"] \\ rw [] \\ fs [] \\ rveq \\ fs [LENGTH_EQ_NUM_compute] \\ rveq \\ fs [] \\ rpt (qpat_x_assum `v_rel _ _` mp_tac) \\ once_rewrite_tac [v_rel_cases] \\ fs [] \\ rpt strip_tac \\ rveq \\ fs [do_word_op_def] \\ rveq \\ fs [compile_op_def,arg1_def] \\ fs [] \\ rveq \\ fs [PULL_EXISTS,SWAP_REVERSE_SYM,v_rel_def] \\ rveq \\ fs [] \\ simp [evaluate_def,do_app_def,opb_lookup_def,opn_lookup_def,do_eq_def] \\ IF_CASES_TAC \\ fs [] \\ rveq \\ fs [div_exn_v_def,v_rel_def,opn_lookup_def] QED Theorem op_words: (?w w1. op = Opw w w1) \/ (?w. op = WordFromInt w) \/ (?w. op = WordToInt w) ==> ^op_goal Proof rw [] \\ Cases_on `w` \\ rveq \\ fs [] \\ TRY (Cases_on `w1`) \\ fs [flatSemTheory.do_app_def,list_case_eq,CaseEq "flatSem$v",PULL_EXISTS, CaseEq "ast$lit",store_assign_def,option_case_eq,CaseEq "store_v"] \\ rw [] \\ fs [] \\ rveq \\ fs [LENGTH_EQ_NUM_compute] \\ rveq \\ fs [] \\ rpt (qpat_x_assum `v_rel _ _` mp_tac) \\ once_rewrite_tac [v_rel_cases] \\ fs [] \\ rpt strip_tac \\ rveq \\ fs [do_word_op_def] \\ rveq \\ fs [compile_op_def,arg1_def] \\ fs [] \\ rveq \\ fs [PULL_EXISTS,SWAP_REVERSE_SYM,v_rel_def] \\ rveq \\ fs [] \\ simp [evaluate_def,do_app_def] \\ fs [some_def,EXISTS_PROD] \\ CONV_TAC (DEPTH_CONV PairRules.PBETA_CONV) \\ `!x. b = FST x ∧ b' = SND x <=> x = (b,b')` by (fs [FORALL_PROD] \\ metis_tac []) \\ simp [integer_wordTheory.w2n_i2w] QED Theorem op_shifts: (?w s n. op = Shift w s n) ==> ^op_goal Proof rw [] \\ Cases_on `w` \\ Cases_on `s` \\ rveq \\ fs [] \\ fs [flatSemTheory.do_app_def,list_case_eq,CaseEq "flatSem$v",PULL_EXISTS, CaseEq "ast$lit",store_assign_def,option_case_eq,CaseEq "store_v"] \\ rw [] \\ fs [] \\ rveq \\ fs [LENGTH_EQ_NUM_compute] \\ rveq \\ fs [] \\ fs [] \\ rveq \\ fs [PULL_EXISTS,SWAP_REVERSE_SYM,v_rel_def] \\ rveq \\ fs [] \\ rename [`v_rel (Litv ww) y`] \\ Cases_on `ww` \\ fs [v_rel_def,do_shift_def] \\ rveq \\ fs [] \\ fs [compile_op_def,evaluate_def,do_app_def,v_rel_def] QED Theorem op_floats: (?f. op = FP_cmp f) \/ (?f. op = FP_uop f) \/ (?f. op = FP_bop f) \/ (?f. op = FP_top f) ==> ^op_goal Proof rw [] \\ Cases_on `f` \\ rveq \\ fs [] \\ fs [flatSemTheory.do_app_def,list_case_eq,CaseEq "flatSem$v",PULL_EXISTS, CaseEq "ast$lit",store_assign_def,option_case_eq,CaseEq "store_v"] \\ rw [] \\ fs [] \\ rveq \\ fs [LENGTH_EQ_NUM_compute] \\ rveq \\ fs [] \\ fs [] \\ rveq \\ fs [PULL_EXISTS,SWAP_REVERSE_SYM,v_rel_def] \\ rveq \\ fs [] \\ simp [compile_op_def,evaluate_def,do_app_def] QED Theorem op_byte_arrays: op = Aw8length \/ op = Aw8alloc \/ op = Aw8sub_unsafe \/ op = Aw8sub \/ op = Aw8update_unsafe \/ op = Aw8update ==> ^op_goal Proof rpt strip_tac \\ rveq \\ fs [] \\ fs [flatSemTheory.do_app_def,list_case_eq,CaseEq "flatSem$v",PULL_EXISTS, CaseEq "ast$lit",store_assign_def,option_case_eq,CaseEq "store_v"] \\ rw [] \\ fs [] \\ rveq \\ fs [LENGTH_EQ_NUM_compute] \\ rveq \\ fs [] \\ fs [] \\ rveq \\ fs [PULL_EXISTS,SWAP_REVERSE_SYM,v_rel_def] \\ rveq \\ fs [] \\ imp_res_tac lookup_byte_array \\ fs [compile_op_def,subscript_exn_v_def,v_rel_def] THEN1 fs [evaluate_def,do_app_def] THEN1 (fs [evaluate_def,do_app_def,integerTheory.int_le] \\ rw [] \\ fs [] \\ rveq \\ fs [v_rel_def] \\ fs [store_alloc_def] \\ rveq \\ fs [] \\ imp_res_tac state_rel_LEAST \\ fs [] \\ fs [state_rel_def,store_rel_def,FLOOKUP_UPDATE,v_rel_def] \\ strip_tac \\ last_x_assum (qspec_then `i` mp_tac) \\ rename [`¬(k < 0)`] \\ `ABS k = k` by intLib.COOPER_TAC \\ simp [] \\ Cases_on `i = LENGTH s1.refs` \\ fs [EL_APPEND2] \\ IF_CASES_TAC \\ fs [EL_APPEND1]) THEN1 (fs [evaluate_def,do_app_def,integerTheory.int_le] \\ rename [`¬(k < 0)`] \\ `Num (ABS k) < LENGTH ws' <=> k < &LENGTH ws'` by intLib.COOPER_TAC \\ fs [GREATER_EQ,GSYM NOT_LESS] \\ `ABS k = k` by intLib.COOPER_TAC \\ simp []) THEN1 (fs [evaluate_def,do_app_def,integerTheory.int_le] \\ Cases_on `i < 0` \\ fs [] \\ rveq \\ fs [v_rel_def] \\ rename [`¬(k < 0)`] \\ `Num (ABS k) < LENGTH ws' <=> k < &LENGTH ws'` by intLib.COOPER_TAC \\ fs [GREATER_EQ,GSYM NOT_LESS] \\ IF_CASES_TAC \\ fs [] \\ rveq \\ fs [v_rel_def] \\ `ABS k = k` by intLib.COOPER_TAC \\ simp []) THEN1 (fs [evaluate_def,do_app_def,integerTheory.int_le] \\ rename [`¬(k < 0)`] \\ `Num (ABS k) < LENGTH ws' <=> k < &LENGTH ws'` by intLib.COOPER_TAC \\ fs [GREATER_EQ,GSYM NOT_LESS] \\ fs [option_case_eq] \\ rveq \\ fs [v_rel_def,Unit_def,EVAL ``tuple_tag``] \\ rename [`store_v_same_type (EL j s1.refs)`] \\ Cases_on `EL j s1.refs` \\ fs [store_v_same_type_def] \\ fs [state_rel_def,store_rel_def] \\ strip_tac \\ last_x_assum (qspec_then `i` mp_tac) \\ fs [FLOOKUP_UPDATE] \\ IF_CASES_TAC \\ fs [EL_LUPDATE] \\ Cases_on `i = j` \\ fs [] \\ rveq \\ fs [] \\ rpt strip_tac \\ rveq \\ fs [] \\ `ABS k = k` by intLib.COOPER_TAC \\ simp []) THEN1 (fs [evaluate_def,do_app_def,integerTheory.int_le] \\ rename [`¬(k < 0)`] \\ Cases_on `k < 0` \\ fs [] \\ rveq \\ fs [v_rel_def] \\ `Num (ABS k) < LENGTH ws' <=> k < &LENGTH ws'` by intLib.COOPER_TAC \\ fs [GREATER_EQ,GSYM NOT_LESS] \\ IF_CASES_TAC \\ fs [] \\ rveq \\ fs [v_rel_def] \\ fs [option_case_eq] \\ rveq \\ fs [v_rel_def,Unit_def,EVAL ``tuple_tag``] \\ rename [`store_v_same_type (EL j s1.refs)`] \\ Cases_on `EL j s1.refs` \\ fs [store_v_same_type_def] \\ fs [state_rel_def,store_rel_def] \\ strip_tac \\ last_x_assum (qspec_then `i` mp_tac) \\ fs [FLOOKUP_UPDATE] \\ IF_CASES_TAC \\ fs [EL_LUPDATE] \\ Cases_on `i = j` \\ fs [] \\ rveq \\ fs [] \\ rpt strip_tac \\ rveq \\ fs [] \\ `ABS k = k` by intLib.COOPER_TAC \\ simp []) QED Theorem op_byte_copy: op = CopyStrAw8 \/ op = CopyAw8Str \/ op = CopyAw8Aw8 \/ op = CopyStrStr ==> ^op_goal Proof rpt strip_tac \\ rveq \\ fs [] \\ fs [flatSemTheory.do_app_def,list_case_eq,CaseEq "flatSem$v",PULL_EXISTS, CaseEq "ast$lit",store_assign_def,option_case_eq,CaseEq "store_v"] \\ rw [] \\ fs [] \\ rveq \\ fs [LENGTH_EQ_NUM_compute] \\ rveq \\ fs [] \\ fs [] \\ rveq \\ fs [PULL_EXISTS,SWAP_REVERSE_SYM,v_rel_def] \\ rveq \\ fs [] \\ imp_res_tac lookup_byte_array \\ fs [compile_op_def,subscript_exn_v_def,v_rel_def,CopyByteAw8_def,CopyByteStr_def] \\ simp [evaluate_def,do_app_def] THEN1 (fs [copy_array_def] \\ qpat_x_assum `IS_SOME _ ==> _` mp_tac \\ rpt (IF_CASES_TAC \\ fs [ws_to_chars_def]) \\ intLib.COOPER_TAC) THEN1 (fs [copy_array_def] \\ fs [ws_to_chars_def] \\ reverse IF_CASES_TAC THEN1 (fs [] \\ intLib.COOPER_TAC) \\ reverse IF_CASES_TAC THEN1 (fs [] \\ intLib.COOPER_TAC) \\ fs [Unit_def,EVAL ``tuple_tag``] \\ rveq \\ fs [] \\ fs [state_rel_def,store_rel_def] \\ strip_tac \\ last_x_assum (qspec_then `i` mp_tac) \\ fs [FLOOKUP_UPDATE,EL_LUPDATE] \\ IF_CASES_TAC \\ fs [] \\ Cases_on `i=dst` \\ fs [] \\ fs [chars_to_ws_def,MAP_TAKE,MAP_DROP,MAP_MAP_o,o_DEF,ORD_CHR, integer_wordTheory.i2w_pos]) THEN1 (fs [copy_array_def] \\ rpt (IF_CASES_TAC \\ fs [ws_to_chars_def]) \\ intLib.COOPER_TAC) THEN1 (fs [copy_array_def] \\ fs [ws_to_chars_def] \\ reverse IF_CASES_TAC THEN1 (fs [] \\ intLib.COOPER_TAC) \\ fs [MAP_MAP_o,o_DEF]) THEN1 (fs [copy_array_def] \\ fs [ws_to_chars_def] \\ qpat_x_assum `IS_SOME _ ==> _` mp_tac \\ IF_CASES_TAC \\ fs [] \\ rpt strip_tac \\ fs [] \\ rpt (IF_CASES_TAC \\ fs [] \\ rpt strip_tac \\ fs []) \\ intLib.COOPER_TAC) THEN1 (fs [copy_array_def] \\ fs [ws_to_chars_def] \\ reverse IF_CASES_TAC THEN1 (fs [] \\ intLib.COOPER_TAC) \\ reverse IF_CASES_TAC THEN1 (fs [] \\ intLib.COOPER_TAC) \\ fs [Unit_def,EVAL ``tuple_tag``] \\ rveq \\ fs [] \\ fs [state_rel_def,store_rel_def] \\ strip_tac \\ last_x_assum (qspec_then `i` mp_tac) \\ fs [FLOOKUP_UPDATE,EL_LUPDATE] \\ IF_CASES_TAC \\ fs [] \\ Cases_on `i=dst'` \\ fs []) THEN1 (fs [copy_array_def] \\ fs [ws_to_chars_def] \\ rpt (IF_CASES_TAC \\ fs [] \\ rpt strip_tac \\ fs []) \\ intLib.COOPER_TAC) THEN1 (fs [copy_array_def] \\ fs [ws_to_chars_def] \\ reverse IF_CASES_TAC THEN1 (fs [] \\ intLib.COOPER_TAC) \\ fs [] \\ rveq \\ fs [MAP_TAKE,MAP_DROP]) QED Theorem op_eq_gc: op = ConfigGC \/ op = Equality ==> ^op_goal Proof rpt strip_tac \\ rveq \\ fs [] \\ fs [flatSemTheory.do_app_def,list_case_eq,CaseEq "flatSem$v",PULL_EXISTS, CaseEq "ast$lit",store_assign_def,option_case_eq] \\ rw [] \\ fs [] \\ rveq \\ fs [LENGTH_EQ_NUM_compute] \\ rveq \\ fs [] \\ fs [] \\ rveq \\ fs [PULL_EXISTS,SWAP_REVERSE_SYM] \\ rveq \\ fs [] THEN1 (ntac 2 (pop_assum mp_tac) \\ once_rewrite_tac [v_rel_cases] \\ fs [] \\ rw [] \\ fs [compile_op_def,evaluate_def,do_app_def,Unit_def] \\ EVAL_TAC) \\ fs [CaseEq"eq_result"] \\ rveq \\ fs [] \\ fs [compile_op_def,evaluate_def,do_app_def] \\ qsuff_tac ` (!v1 v2 x1 x2 b. v_rel v1 x1 /\ v_rel v2 x2 /\ do_eq v1 v2 = Eq_val b ==> do_eq x1 x2 = Eq_val b) /\ (!v1 v2 x1 x2 b. LIST_REL v_rel v1 x1 /\ LIST_REL v_rel v2 x2 /\ do_eq_list v1 v2 = Eq_val b ==> do_eq_list x1 x2 = Eq_val b)` THEN1 (rw [] \\ res_tac \\ fs []) \\ rpt (pop_assum kall_tac) \\ ho_match_mp_tac flatSemTheory.do_eq_ind \\ rw [] \\ fs [v_rel_def,flatSemTheory.do_eq_def,bool_case_eq] \\ rveq \\ fs [] \\ imp_res_tac LIST_REL_LENGTH THEN1 (rename [`lit_same_type l1 l2`] \\ Cases_on `l1` \\ Cases_on `l2` \\ fs [lit_same_type_def,v_rel_def] \\ fs [do_eq_def] \\ rveq \\ fs [ORD_11] \\ rename [`MAP _ l1 = MAP _ l2`] \\ qid_spec_tac `l2` \\ qid_spec_tac `l1` \\ Induct \\ Cases_on `l2` \\ fs [ORD_BOUND,ORD_11]) \\ TRY (fs [do_eq_def] \\ rveq \\ fs [v_rel_def] \\ NO_TAC) \\ rveq \\ fs [ctor_same_type_def] \\ fs [CaseEq"eq_result",bool_case_eq] \\ rveq \\ fs [] \\ fs [do_eq_def] \\ qpat_x_assum `Eq_val b = _` (assume_tac o GSYM) \\ res_tac \\ fs [] QED Theorem v_rel_v_to_char_list: !x ls y. v_to_char_list x = SOME ls /\ v_rel x y ==> v_to_list y = SOME (MAP (Number ∘ $&) (MAP ORD ls)) Proof ho_match_mp_tac v_to_char_list_ind \\ rw [] \\ fs [v_rel_def,v_to_list_def,v_to_char_list_def] \\ rveq \\ fs [option_case_eq] \\ rveq \\ fs [] QED Theorem op_str: op = Explode \/ op = Implode \/ op = Strlen \/ op = Strsub \/ op = Strcat ==> ^op_goal Proof rpt strip_tac \\ rveq \\ fs [] \\ fs [flatSemTheory.do_app_def,list_case_eq,CaseEq "flatSem$v",PULL_EXISTS, CaseEq "ast$lit",store_assign_def,option_case_eq] \\ rw [] \\ fs [] \\ rveq \\ fs [LENGTH_EQ_NUM_compute] \\ rveq \\ fs [] \\ fs [] \\ rveq \\ fs [PULL_EXISTS] \\ fs [compile_op_def,evaluate_def,do_app_def,get_global_def,v_rel_def] \\ rveq \\ fs [SWAP_REVERSE_SYM] \\ rveq \\ fs [SWAP_REVERSE_SYM] THEN1 (match_mp_tac IMP_v_rel_to_list \\ rename [`MAP _ xs`] \\ qid_spec_tac `xs` \\ Induct \\ fs [v_rel_def,ORD_BOUND]) THEN1 (imp_res_tac v_rel_v_to_char_list \\ fs [] \\ `!xs. MAP (Number ∘ $&) (MAP ORD ls) = MAP (Number ∘ $&) xs <=> xs = (MAP ORD ls)` by (qid_spec_tac `ls` \\ Induct \\ Cases_on `xs` \\ fs [] \\ rw [] \\ eq_tac \\ rw[]) \\ fs [] \\ `(!xs. xs = MAP ORD ls /\ EVERY (λn. n < 256n) xs <=> xs = MAP ORD ls /\ EVERY (λn. n < 256n) (MAP ORD ls))` by metis_tac [] \\ fs [] \\ `!ls. EVERY (λn. n < 256) (MAP ORD ls)` by (Induct \\ fs [ORD_BOUND]) \\ fs [] \\ fs [MAP_MAP_o,stringTheory.IMPLODE_EXPLODE_I]) THEN1 (fs [integerTheory.int_le] \\ rename [`~(i4 < 0)`] \\ Cases_on `i4 < 0` \\ fs [] \\ rveq \\ fs [subscript_exn_v_def,v_rel_def] \\ rename [`i4 < &LENGTH str`] \\ fs [GREATER_EQ,GSYM NOT_LESS] \\ `Num (ABS i4) < STRLEN str <=> i4 < &STRLEN str` by intLib.COOPER_TAC \\ fs [] \\ IF_CASES_TAC \\ fs [] \\ rveq \\ fs [v_rel_def] \\ Cases_on `i4` \\ fs [] \\ fs [EL_MAP,ORD_BOUND] \\ Cases_on `str` \\ fs [EL_MAP,ORD_BOUND]) \\ qsuff_tac `!x vs str y. v_to_list x = SOME vs /\ vs_to_string vs = SOME str /\ v_rel x y ==> ?wss. v_to_list y = SOME (MAP ByteVector wss) /\ MAP (CHR o w2n) (FLAT wss) = str` THEN1 (rpt (disch_then drule \\ fs []) \\ strip_tac \\ fs [] \\ `!xs ys. MAP ByteVector xs = MAP ByteVector ys <=> xs = ys` by (Induct \\ Cases_on `ys` \\ fs []) \\ fs [] \\ rveq \\ fs [MAP_MAP_o,o_DEF]) \\ rpt (pop_assum kall_tac) \\ recInduct flatSemTheory.v_to_list_ind \\ rw [] \\ fs [v_rel_def] \\ rveq \\ fs [flatSemTheory.v_to_list_def] \\ rveq \\ fs [vs_to_string_def] \\ rveq \\ fs [] THEN1 (qexists_tac `[]` \\ EVAL_TAC) \\ fs [option_case_eq] \\ rveq \\ Cases_on `v1` \\ fs [flatSemTheory.v_to_list_def,vs_to_string_def] \\ Cases_on `l` \\ fs [flatSemTheory.v_to_list_def,vs_to_string_def,option_case_eq] \\ rveq \\ fs [v_rel_def,v_to_list_def,option_case_eq,PULL_EXISTS] \\ res_tac \\ fs [] \\ rveq \\ fs [] \\ qexists_tac `(MAP (n2w ∘ ORD) s) :: wss` \\ fs [MAP_MAP_o,o_DEF,ORD_BOUND,CHR_ORD] QED Theorem op_globals: (?n. op = GlobalVarLookup n) \/ (?n. op = GlobalVarInit n) \/ (?n. op = GlobalVarAlloc n) ==> ^op_goal Proof rpt strip_tac \\ rveq \\ fs [] \\ fs [flatSemTheory.do_app_def,list_case_eq,CaseEq "flatSem$v",PULL_EXISTS, CaseEq "ast$lit",store_assign_def,option_case_eq] \\ rw [] \\ fs [] \\ rveq \\ fs [LENGTH_EQ_NUM_compute] \\ rveq \\ fs [] \\ fs [] \\ rveq \\ fs [PULL_EXISTS] \\ fs [compile_op_def,evaluate_def,do_app_def,get_global_def] THEN1 (Cases_on `EL n s1.globals` \\ fs [state_rel_def] \\ imp_res_tac LIST_REL_LENGTH \\ fs [] \\ fs [LIST_REL_EL] \\ res_tac \\ fs [] \\ qpat_x_assum `_ = SOME x` assume_tac \\ Cases_on `EL n t.globals` \\ fs []) THEN1 (fs [state_rel_def] \\ imp_res_tac LIST_REL_LENGTH \\ fs [] \\ fs [LIST_REL_EL] \\ res_tac \\ fs [] \\ qpat_x_assum `_ = NONE` assume_tac \\ Cases_on `EL n t1.globals` \\ fs [] \\ fs [EL_LUPDATE] \\ simp [Once v_rel_cases,Unit_def] \\ rw [] \\ EVAL_TAC) \\ simp [Once v_rel_cases,Unit_def] \\ fs [compile_op_def,evaluate_def,do_app_def,arg1_def] \\ qsuff_tac `!n db (t:('c,'ffi) closSem$state). evaluate ([AllocGlobals tt n],db,t) = (Rval [Block 0 []],t with globals := t.globals ++ REPLICATE n NONE)` THEN1 (fs [state_rel_def] \\ rw [] \\ match_mp_tac EVERY2_APPEND_suff \\ fs [] \\ qid_spec_tac `n` \\ Induct \\ fs []) \\ Induct \\ simp [Once AllocGlobals_def,evaluate_def,do_app_def] THEN1 (fs [state_component_equality]) \\ rw [] THEN1 (simp [Once AllocGlobals_def,evaluate_def,do_app_def,Unit_def] \\ EVAL_TAC) \\ simp [evaluate_def,do_app_def,Unit_def] \\ fs [state_component_equality] QED Theorem op_vectors: op = Vlength \/ op = Vsub \/ op = VfromList ==> ^op_goal Proof rpt strip_tac \\ rveq \\ fs [] \\ fs [flatSemTheory.do_app_def,list_case_eq,CaseEq "flatSem$v",PULL_EXISTS, CaseEq "ast$lit",store_assign_def,option_case_eq] \\ rw [] \\ fs [] \\ rveq \\ fs [LENGTH_EQ_NUM_compute] \\ rveq \\ fs [] \\ fs [v_rel_def] \\ rveq \\ fs [PULL_EXISTS] \\ fs [compile_op_def,evaluate_def,do_app_def] \\ imp_res_tac LIST_REL_LENGTH \\ fs [SWAP_REVERSE_SYM] THEN1 (rveq \\ fs [] \\ rename [`0 <= i5`] \\ Cases_on `i5` \\ fs [bool_case_eq] \\ rveq \\ fs [] \\ fs [subscript_exn_v_def,v_rel_def,GREATER_EQ] \\ fs [LIST_REL_EL] \\ first_x_assum (qspec_then `0` mp_tac) \\ fs [] \\ rename [`wss <> []`] \\ Cases_on `wss` \\ fs []) \\ rename [`v_rel x y`] \\ imp_res_tac v_rel_to_list \\ fs [] QED Theorem op_arrays: op = Aalloc \/ op = Asub_unsafe \/ op = Asub \/ op = Alength \/ op = Aupdate_unsafe \/ op = Aupdate ==> ^op_goal Proof rpt strip_tac \\ rveq \\ fs [] \\ fs [flatSemTheory.do_app_def,list_case_eq,CaseEq "flatSem$v",PULL_EXISTS, CaseEq "ast$lit",store_assign_def,option_case_eq,store_alloc_def] \\ rw [] \\ fs [] \\ rveq \\ fs [LENGTH_EQ_NUM_compute] \\ rveq \\ fs [] \\ fs [v_rel_def] \\ rveq \\ fs [PULL_EXISTS] \\ fs [compile_op_def,evaluate_def,do_app_def,arg1_def] \\ imp_res_tac LIST_REL_LENGTH \\ fs [SWAP_REVERSE_SYM,list_case_eq] \\ rveq \\ fs [bool_case_eq] \\ rveq \\ fs [] \\ fs [subscript_exn_v_def,v_rel_def,integerTheory.INT_NOT_LT,CaseEq"store_v"] \\ rveq \\ fs [PULL_EXISTS] \\ imp_res_tac state_rel_LEAST \\ fs [] THEN1 (rename [`0<=i`] \\ `Num (ABS i) = Num i` by intLib.COOPER_TAC \\ fs [] \\ fs [state_rel_def,store_rel_def,EL_LUPDATE] \\ strip_tac \\ first_x_assum (qspec_then `i'` mp_tac) \\ IF_CASES_TAC \\ fs [FLOOKUP_UPDATE,EL_LUPDATE,EL_APPEND1,EL_APPEND2] \\ Cases_on `LENGTH s1.refs = i'` \\ fs [] \\ rveq \\ fs [] \\ rw [] \\ qspec_tac (`Num i`,`j`) \\ Induct \\ fs []) THEN1 (imp_res_tac lookup_array \\ fs [GREATER_EQ,GSYM NOT_LESS,v_rel_def] \\ fs [bool_case_eq] \\ rveq \\ fs [integerTheory.int_le] \\ fs [v_rel_def] \\ imp_res_tac LIST_REL_LENGTH \\ fs [PULL_EXISTS] \\ rename [`i6 < _:int`] \\ reverse IF_CASES_TAC THEN1 `F` by intLib.COOPER_TAC \\ fs [] \\ fs [LIST_REL_EL] \\ Cases_on `i6` \\ fs [] \\ first_x_assum (qspec_then `0` mp_tac) \\ Cases_on `ws` \\ fs []) THEN1 (imp_res_tac lookup_array \\ fs [GREATER_EQ,GSYM NOT_LESS,v_rel_def] \\ fs [bool_case_eq] \\ rveq \\ fs [integerTheory.int_le] \\ fs [v_rel_def] \\ imp_res_tac LIST_REL_LENGTH THEN1 intLib.COOPER_TAC \\ fs [PULL_EXISTS] \\ rename [`i6 < _:int`] \\ Cases_on `i6` \\ fs [] \\ fs [LIST_REL_EL] \\ first_x_assum (qspec_then `0` mp_tac) \\ Cases_on `ws` \\ fs []) THEN1 (imp_res_tac lookup_array \\ fs [GREATER_EQ,GSYM NOT_LESS,v_rel_def] \\ imp_res_tac LIST_REL_LENGTH \\ decide_tac) THEN1 (imp_res_tac lookup_array \\ fs [GREATER_EQ,GSYM NOT_LESS,v_rel_def] \\ fs [bool_case_eq,CaseEq"option"] \\ rveq \\ fs [integerTheory.int_le,v_rel_def] \\ rename [`~(i7 < 0i)`] \\ `Num (ABS i7) = Num i7 /\ (i7 < &LENGTH ws <=> Num i7 < LENGTH ws)` by intLib.COOPER_TAC \\ fs [] \\ imp_res_tac LIST_REL_LENGTH \\ fs [] \\ fs [option_case_eq] \\ rveq \\ fs [v_rel_def,Unit_def,EVAL ``tuple_tag``] \\ fs [state_rel_def,store_rel_def,EL_LUPDATE] \\ strip_tac \\ first_x_assum (qspec_then `i` mp_tac) \\ IF_CASES_TAC \\ fs [FLOOKUP_UPDATE,EL_LUPDATE,EL_APPEND1,EL_APPEND2] \\ IF_CASES_TAC \\ fs [] \\ CASE_TAC \\ fs [] \\ strip_tac \\ rveq \\ fs [LUPDATE_def] \\ match_mp_tac EVERY2_LUPDATE_same \\ fs []) \\ imp_res_tac lookup_array \\ fs [GREATER_EQ,GSYM NOT_LESS,v_rel_def] \\ fs [bool_case_eq] \\ rveq \\ fs [integerTheory.int_le,v_rel_def] \\ rename [`~(i7 < 0i)`] \\ `Num (ABS i7) = Num i7 /\ (i7 < &LENGTH ws <=> Num i7 < LENGTH ws)` by intLib.COOPER_TAC \\ fs [] \\ imp_res_tac LIST_REL_LENGTH \\ fs [] \\ qpat_x_assum `SOME (s2,res2) = _` (assume_tac o GSYM) \\ fs [option_case_eq] \\ rveq \\ fs [v_rel_def,Unit_def,EVAL ``tuple_tag``] \\ fs [state_rel_def,store_rel_def,EL_LUPDATE] \\ strip_tac \\ first_x_assum (qspec_then `i` mp_tac) \\ IF_CASES_TAC \\ fs [FLOOKUP_UPDATE,EL_LUPDATE,EL_APPEND1,EL_APPEND2] \\ IF_CASES_TAC \\ fs [] \\ CASE_TAC \\ fs [] \\ strip_tac \\ rveq \\ fs [LUPDATE_def] \\ match_mp_tac EVERY2_LUPDATE_same \\ fs [] QED Theorem op_blocks: (?n0 n1. op = TagLenEq n0 n1) \/ (?l. op = LenEq l) \/ op = ListAppend ==> ^op_goal Proof rpt strip_tac \\ rveq \\ fs [] \\ fs [flatSemTheory.do_app_def,list_case_eq,CaseEq "flatSem$v",PULL_EXISTS, CaseEq "ast$lit",store_assign_def,option_case_eq] \\ rw [] \\ fs [] \\ rveq \\ fs [LENGTH_EQ_NUM_compute] \\ rveq \\ fs [] \\ fs [v_rel_def] \\ rveq \\ fs [PULL_EXISTS] \\ fs [compile_op_def,evaluate_def,do_app_def,arg1_def] \\ imp_res_tac LIST_REL_LENGTH \\ fs [SWAP_REVERSE_SYM,list_case_eq] \\ rveq \\ fs [] \\ imp_res_tac v_rel_to_list \\ fs [] \\ rveq \\ fs [] \\ match_mp_tac IMP_v_rel_to_list \\ match_mp_tac EVERY2_APPEND_suff \\ fs [] QED Theorem op_ffi: (?n. op = FFI n) ==> ^op_goal Proof rpt strip_tac \\ rveq \\ fs [] \\ fs [flatSemTheory.do_app_def,list_case_eq,CaseEq "flatSem$v",PULL_EXISTS, CaseEq "ast$lit",store_assign_def,option_case_eq] \\ rw [] \\ fs [] \\ rveq \\ fs [LENGTH_EQ_NUM_compute] \\ rveq \\ fs [] \\ fs [v_rel_def] \\ rveq \\ fs [PULL_EXISTS] \\ fs [compile_op_def,evaluate_def,do_app_def,arg1_def] \\ fs [CaseEq "store_v",CaseEq"ffi_result",option_case_eq,bool_case_eq] \\ rveq \\ fs [SWAP_REVERSE_SYM] \\ rveq \\ fs [] \\ imp_res_tac lookup_byte_array \\ fs [] \\ `t1.ffi = s1.ffi` by fs[state_rel_def] \\ fs [o_DEF] \\ fs [v_rel_def,Unit_def,EVAL ``tuple_tag``] \\ fs [state_rel_def,store_rel_def,EL_LUPDATE] \\ strip_tac \\ first_x_assum (qspec_then `i` mp_tac) \\ IF_CASES_TAC \\ fs [FLOOKUP_UPDATE] \\ IF_CASES_TAC \\ fs [] \\ CASE_TAC \\ fs [] QED Theorem compile_op_correct: ^op_goal Proof EVERY (map assume_tac [op_refs, op_chars, op_ints, op_words, op_str, op_shifts, op_floats, op_eq_gc, op_byte_arrays, op_vectors, op_arrays, op_globals, op_blocks, op_ffi, op_byte_copy]) \\ `?this_is_case. this_is_case op` by (qexists_tac `K T` \\ fs []) \\ rpt strip_tac \\ fs [] \\ Cases_on `op` \\ fs [] QED Theorem compile_App: ^(get_goal "flatLang$App") Proof rpt strip_tac \\ fs [evaluate_def,compile_def,flatSemTheory.evaluate_def] \\ rfs [pair_case_eq] \\ fs [EVERY_REVERSE, Q.ISPEC `no_Mat` ETA_THM] \\ first_x_assum drule \\ disch_then drule \\ impl_tac THEN1 (CCONTR_TAC \\ fs []) \\ strip_tac \\ Cases_on `op = Opapp` \\ fs [] THEN1 (fs [compile_op_def] \\ rveq \\ reverse (fs [result_case_eq] \\ rveq \\ fs [] \\ rveq \\ fs []) THEN1 (Cases_on `compile m (REVERSE es)` \\ fs [arg2_def] \\ fs [evaluate_def] \\ rename [`_ = _::ys`] \\ Cases_on `ys` \\ fs [arg2_def] \\ fs [evaluate_def] \\ rename [`_ = _::_::ys`] \\ Cases_on `ys` \\ fs [arg2_def] \\ fs [evaluate_def] \\ fs [pair_case_eq,result_case_eq]) \\ fs [option_case_eq,pair_case_eq] \\ rveq \\ fs [] \\ fs [flatSemTheory.do_opapp_def] \\ `?f x. vs = [x;f]` by fs [list_case_eq,SWAP_REVERSE_SYM] \\ rveq \\ fs [] \\ rveq \\ fs [] \\ `?ef ex. es = [ex;ef]` by (imp_res_tac evaluate_IMP_LENGTH \\ fs [LENGTH_compile] \\ Cases_on `es` \\ fs [] \\ Cases_on `t'` \\ fs []) \\ rveq \\ fs [] \\ rveq \\ fs [] \\ `compile m [ef; ex] = HD (compile m [ef]) :: HD (compile m [ex]) :: []` by fs [compile_def,LENGTH_compile] \\ asm_rewrite_tac [arg2_def] \\ fs [] \\ fs [evaluate_def,LENGTH_compile] \\ qpat_x_assum `evaluate _ = _` mp_tac \\ once_rewrite_tac [evaluate_CONS] \\ fs [] \\ fs [pair_case_eq,result_case_eq,PULL_EXISTS] \\ rpt strip_tac \\ rveq \\ fs [] \\ `?vx. v = [vx]` by (imp_res_tac evaluate_IMP_LENGTH \\ fs [LENGTH_compile] \\ Cases_on `v` \\ fs []) \\ rveq \\ fs [] \\ fs [evaluate_def] \\ Cases_on `f` \\ fs [] \\ rveq \\ fs [] \\ qpat_x_assum `v_rel _ _` mp_tac \\ once_rewrite_tac [v_rel_cases] \\ fs [] \\ strip_tac \\ fs [] \\ rename [`state_rel s1 t1`] \\ `1 <= t1.max_app /\ t1.clock = s1.clock` by fs [state_rel_def] \\ fs [dest_closure_def,check_loc_def] \\ rveq \\ fs [] THEN1 (Cases_on `s1.clock = 0` THEN1 (fs [] \\ fs [state_rel_def] \\ rveq \\ fs[]) \\ fs [] \\ rename [`compile (SOME vn::m1) [e],vx::db1,dec_clock 1 t1`] \\ `state_rel (dec_clock s1) (dec_clock 1 t1)` by fs [flatSemTheory.dec_clock_def,dec_clock_def,state_rel_def] \\ first_x_assum drule \\ `env_rel <|v := (vn,x)::env'.v|> (SOME vn::m1) (vx::db1)` by (match_mp_tac env_rel_CONS \\ fs [env_rel_def]) \\ disch_then drule \\ strip_tac \\ fs [] \\ Cases_on `res1` \\ fs [] \\ rveq \\ fs [] \\ imp_res_tac evaluate_sing \\ rveq \\ fs []) \\ fs [EL_MAP] \\ CONV_TAC (DEPTH_CONV PairRules.PBETA_CONV) \\ fs [] \\ Cases_on `s1.clock = 0` THEN1 (fs [] \\ fs [state_rel_def] \\ rveq \\ fs[]) \\ fs [option_case_eq,pair_case_eq] \\ rveq \\ fs [] \\ `state_rel (dec_clock s1) (dec_clock 1 t1)` by fs [flatSemTheory.dec_clock_def,dec_clock_def,state_rel_def] \\ first_x_assum drule \\ qpat_x_assum `ALL_DISTINCT (MAP FST l0)` assume_tac \\ fs [find_recfun_EL] \\ qpat_x_assum `SND (EL n l0) = (_,_)` assume_tac \\ drule IMP_PAIR \\ strip_tac \\ rveq \\ fs [] \\ qmatch_goalsub_abbrev_tac `evaluate (compile m2 _, db2, _)` \\ disch_then (qspecl_then [`m2`,`db2`] mp_tac) \\ reverse impl_tac THEN1 (strip_tac \\ fs [] \\ rpt (goal_assum (first_assum o mp_then Any mp_tac)) \\ Cases_on `res1` \\ fs [] \\ rveq \\ fs [] \\ imp_res_tac evaluate_sing \\ fs []) \\ unabbrev_all_tac \\ reverse conj_tac THEN1 (fs [EVERY_EL] \\ fs [EL_MAP]) \\ fs [] \\ match_mp_tac env_rel_CONS \\ fs [build_rec_env_eq_MAP] \\ match_mp_tac env_rel_APPEND \\ fs [] \\ fs [MAP_MAP_o,o_DEF] \\ CONV_TAC (DEPTH_CONV PairRules.PBETA_CONV) \\ fs [] \\ match_mp_tac LIST_REL_MAP_GENLIST \\ fs [] \\ rw [] \\ once_rewrite_tac [v_rel_cases] \\ fs [] \\ rename [`env_rel env3 m3 db3`] \\ qexists_tac `env3` \\ qexists_tac `m3` \\ fs [] \\ fs [o_DEF]) \\ reverse (fs [result_case_eq]) \\ rveq \\ fs [] \\ rveq \\ fs [] THEN1 (drule compile_op_evaluates_args \\ fs []) \\ fs [option_case_eq,pair_case_eq] \\ rveq \\ fs [] \\ rename [`state_rel s1 t1`,`LIST_REL v_rel vs ws`,`_ = SOME (s2,res2)`] \\ qmatch_goalsub_rename_tac `compile_op tt op cexps` \\ drule EVERY2_REVERSE \\ qmatch_goalsub_rename_tac `LIST_REL _ vvs` \\ imp_res_tac state_rel_IMP_check_ctor \\ fs [] \\ rw [] \\ match_mp_tac (GEN_ALL compile_op_correct) \\ rpt (asm_exists_tac \\ fs []) \\ imp_res_tac evaluate_IMP_LENGTH \\ imp_res_tac LIST_REL_LENGTH \\ fs [] QED Theorem compile_correct: ^(compile_correct_tm()) Proof match_mp_tac (the_ind_thm()) \\ EVERY (map strip_assume_tac [compile_nil, compile_cons, compile_Lit, compile_Handle, compile_Raise, compile_Let, compile_Letrec, compile_Fun, compile_Con, compile_App, compile_If, compile_Mat, compile_Var_local]) \\ asm_rewrite_tac [] QED Theorem compile_decs_correct: ∀ds s res1 s1 (t:('c,'ffi) closSem$state). evaluate_decs s ds = (s1,res1) ∧ state_rel s t ∧ no_Mat_decs ds /\ res1 ≠ SOME (Rabort Rtype_error) ⇒ ∃res2 t1. evaluate (compile_decs ds,[],t) = (res2,t1) ∧ state_rel s1 t1 /\ ?v. let res1' = (case res1 of NONE => Rval v | SOME e => Rerr e) in result_rel (LIST_REL (\x y. T)) v_rel res1' res2 Proof Induct THEN1 fs [evaluate_decs_def,compile_decs_def,closSemTheory.evaluate_def] \\ reverse Cases \\ rw [] \\ imp_res_tac state_rel_IMP_check_ctor \\ fs [compile_decs_def] \\ TRY (first_x_assum match_mp_tac) \\ fs [evaluate_decs_def,compile_decs_def,closSemTheory.evaluate_def,evaluate_dec_def] \\ fs [pair_case_eq,CaseEq"result",CaseEq"bool"] \\ rveq \\ fs [] \\ TRY asm_exists_tac \\ fs [] \\ rveq \\ fs [] \\ TRY (fs [state_rel_def] \\ NO_TAC) \\ drule compile_correct \\ fs [evaluate_APPEND] \\ `env_rel <|v := []|> [] []` by fs [env_rel_def] \\ disch_then drule \\ disch_then drule \\ strip_tac \\ fs [] \\ rveq \\ fs [] \\ first_x_assum drule \\ fs [] \\ disch_then drule \\ rw [] \\ fs [] \\ Cases_on `res1` \\ fs [] \\ asm_exists_tac \\ fs [] QED Theorem compile_semantics: 0 < max_app /\ no_Mat_decs ds ==> flatSem$semantics T (ffi:'ffi ffi_state) ds ≠ Fail ==> closSem$semantics ffi max_app FEMPTY co cc (compile_decs ds) = flatSem$semantics T ffi ds Proof strip_tac \\ simp[flatSemTheory.semantics_def] \\ IF_CASES_TAC \\ fs[] \\ DEEP_INTRO_TAC some_intro \\ simp[] \\ conj_tac >- ( rw[] \\ simp[closSemTheory.semantics_def] \\ IF_CASES_TAC \\ fs[] THEN1 (qhdtm_x_assum`flatSem$evaluate_decs`kall_tac \\ last_x_assum(qspec_then`k'`mp_tac) \\ simp[] \\ (fn g => subterm (fn tm => Cases_on`^(assert(has_pair_type)tm)`) (#2 g) g) \\ spose_not_then strip_assume_tac \\ drule (compile_decs_correct |> INST_TYPE [``:'c``|->``:'a``]) \\ qmatch_asmsub_abbrev_tac `([],init)` \\ `state_rel (initial_state ffi k' T) init` by fs [Abbr`init`,state_rel_initial_state] \\ disch_then drule \\ impl_tac THEN1 fs [] \\ strip_tac \\ every_case_tac \\ fs [] \\ rw [] \\ fs []) \\ DEEP_INTRO_TAC some_intro \\ simp[] \\ conj_tac >- ( rw[] \\ qmatch_assum_abbrev_tac`flatSem$evaluate_decs ss es = _` \\ qmatch_assum_abbrev_tac`closSem$evaluate bp = _` \\ fs [option_case_eq,result_case_eq] \\ drule evaluate_decs_add_to_clock_io_events_mono_alt \\ Q.ISPEC_THEN`bp`(mp_tac o Q.GEN`extra`) (CONJUNCT1 closPropsTheory.evaluate_add_to_clock_io_events_mono) \\ simp[Abbr`ss`,Abbr`bp`] \\ disch_then(qspec_then`k`strip_assume_tac) \\ disch_then(qspec_then`k'`strip_assume_tac) \\ drule(GEN_ALL(SIMP_RULE std_ss [](CONJUNCT1 closPropsTheory.evaluate_add_to_clock))) \\ disch_then(qspec_then `k` mp_tac) \\ impl_tac >- rpt(PURE_FULL_CASE_TAC \\ fs[]) \\ drule(GEN_ALL(SIMP_RULE std_ss [] (ONCE_REWRITE_RULE [CONJ_COMM] flatPropsTheory.evaluate_decs_add_to_clock))) \\ disch_then(qspec_then `k'` mp_tac) \\ impl_tac >- rpt(PURE_FULL_CASE_TAC \\ fs[]) \\ ntac 2 strip_tac \\ fs[] \\ drule (compile_decs_correct |> INST_TYPE [``:'c``|->``:'a``]) \\ rfs [] \\ disch_then (qspec_then `initial_state ffi max_app FEMPTY co cc k' with clock := k + k'` mp_tac) \\ impl_tac >- (reverse conj_tac THEN1 (CCONTR_TAC \\ fs []) \\ fs [flatPropsTheory.initial_state_clock, closPropsTheory.initial_state_clock, state_rel_initial_state]) \\ strip_tac \\ unabbrev_all_tac \\ fs[] \\ fs[initial_state_def] \\ rfs[] \\ rveq \\ fs [] \\ every_case_tac \\ fs[state_component_equality] \\ fs [state_rel_def]) \\ drule (compile_decs_correct |> INST_TYPE [``:'c``|->``:'a``]) \\ `state_rel (initial_state ffi k T) (initial_state ffi max_app FEMPTY co cc k)` by (match_mp_tac state_rel_initial_state \\ fs []) \\ rfs [] \\ disch_then drule \\ impl_tac THEN1 (CCONTR_TAC \\ fs []) \\ strip_tac \\ fs [] \\ qexists_tac `k` \\ fs [] \\ every_case_tac \\ fs[state_component_equality] \\ fs [state_rel_def]) \\ strip_tac \\ simp[closSemTheory.semantics_def] \\ IF_CASES_TAC \\ fs [] >- ( last_x_assum(qspec_then`k`strip_assume_tac) \\ qmatch_assum_abbrev_tac`SND p ≠ _` \\ Cases_on`p` \\ fs[markerTheory.Abbrev_def] \\ pop_assum(assume_tac o SYM) \\ drule (compile_decs_correct |> INST_TYPE [``:'c``|->``:'a``]) \\ `state_rel (initial_state ffi k T) (initial_state ffi max_app FEMPTY co cc k)` by (match_mp_tac state_rel_initial_state \\ fs []) \\ disch_then drule \\ impl_tac THEN1 (fs [] \\ CCONTR_TAC \\ fs []) \\ strip_tac \\ fs [] \\ rveq \\ fs [] \\ every_case_tac \\ fs []) \\ DEEP_INTRO_TAC some_intro \\ simp[] \\ conj_tac >- ( spose_not_then strip_assume_tac \\ last_x_assum(qspec_then`k`mp_tac) \\ (fn g => subterm (fn tm => Cases_on`^(assert (can dest_prod o type_of) tm)` g) (#2 g)) \\ strip_tac \\ drule (compile_decs_correct |> INST_TYPE [``:'c``|->``:'a``]) \\ `state_rel (initial_state ffi k T) (initial_state ffi max_app FEMPTY co cc k)` by (match_mp_tac state_rel_initial_state \\ fs []) \\ disch_then drule \\ impl_tac THEN1 (fs [] \\ CCONTR_TAC \\ fs []) \\ strip_tac \\ fs [] \\ rveq \\ fs [] \\ qpat_x_assum `!k s. _` (qspecl_then [`k`] mp_tac) \\ strip_tac \\ rfs [] \\ every_case_tac \\ fs []) \\ strip_tac \\ rpt (AP_TERM_TAC ORELSE AP_THM_TAC) \\ simp[FUN_EQ_THM] \\ gen_tac \\ rpt (AP_TERM_TAC ORELSE AP_THM_TAC) \\ qpat_abbrev_tac`s0 = closSem$initial_state _ _ _ _ _` \\ Cases_on `evaluate_decs (initial_state ffi k T) ds` \\ drule (compile_decs_correct |> INST_TYPE [``:'c``|->``:'a``]) \\ `state_rel (initial_state ffi k T) (initial_state ffi max_app FEMPTY co cc k)` by (match_mp_tac state_rel_initial_state \\ fs []) \\ disch_then drule \\ impl_tac THEN1 (fs [] \\ last_x_assum (qspec_then `k` mp_tac) \\ fs []) \\ fs [] \\ strip_tac \\ fs [state_rel_def] QED Theorem contains_App_SOME_APPEND: closProps$contains_App_SOME ma (xs ++ ys) <=> closProps$contains_App_SOME ma xs \/ closProps$contains_App_SOME ma ys Proof simp [Once closPropsTheory.contains_App_SOME_EXISTS] \\ simp [GSYM closPropsTheory.contains_App_SOME_EXISTS] QED val props_defs = [closPropsTheory.contains_App_SOME_def, closPropsTheory.every_Fn_vs_NONE_def, closPropsTheory.no_mti_def, Q.ISPEC `no_mti` ETA_THM, closPropsTheory.esgc_free_def] Theorem EVERY_IMP_HD: EVERY P xs /\ ~ NULL xs ==> P (HD xs) Proof Cases_on `xs` \\ simp [] QED Theorem compile_single_DEEP_INTRO: !P. (!exp'. flat_to_clos$compile m [exp] = [exp'] ==> P [exp']) ==> P (flat_to_clos$compile m [exp]) Proof qspecl_then [`m`, `[exp]`] assume_tac LENGTH_compile \\ fs [quantHeuristicsTheory.LIST_LENGTH_2] QED Theorem elist_globals_empty: !es. closProps$elist_globals es = {||} <=> !e. MEM e es ==> set_globals e = {||} Proof Induct \\ fs [] \\ rw [] \\ eq_tac \\ rw [] \\ fs [] QED Theorem compile_set_globals: ∀m e. EVERY no_Mat e ==> closProps$elist_globals (compile m e) = flatProps$elist_globals e Proof ho_match_mp_tac flat_to_closTheory.compile_ind \\ simp [compile_def, elist_globals_REVERSE] \\ rw [] \\ fs [EVERY_REVERSE, Q.ISPEC `no_Mat` ETA_THM] \\ TRY (qmatch_goalsub_abbrev_tac `compile_lit _ lit` \\ Cases_on `lit` \\ simp [compile_lit_def]) \\ TRY (qmatch_goalsub_abbrev_tac `compile_op _ op` \\ Cases_on `op` \\ simp ([compile_op_def] @ props_defs) \\ rpt (CASE_TAC \\ simp props_defs)) \\ TRY (qmatch_goalsub_abbrev_tac `AllocGlobals _ n` \\ Induct_on `n` \\ simp [Once AllocGlobals_def] \\ rw props_defs) \\ simp [compile_def, closPropsTheory.op_gbag_def, flatPropsTheory.op_gbag_def, closPropsTheory.elist_globals_append] \\ rpt ( DEEP_INTRO_TAC compile_single_DEEP_INTRO \\ rw [] \\ fs [] ) \\ simp ([CopyByteAw8_def, CopyByteStr_def] @ props_defs) \\ simp [arg1_def, arg2_def] \\ EVERY_CASE_TAC \\ simp [flatPropsTheory.op_gbag_def, closPropsTheory.op_gbag_def] \\ fs [Q.ISPEC `{||}` EQ_SYM_EQ, COMM_BAG_UNION] \\ rpt (DEEP_INTRO_TAC compile_single_DEEP_INTRO \\ rw [] \\ fs []) \\ fs [dest_pat_def] \\ simp [flatPropsTheory.elist_globals_FOLDR, closPropsTheory.elist_globals_FOLDR] \\ irule FOLDR_CONG \\ simp [MAP_MAP_o] \\ irule MAP_CONG \\ simp [FORALL_PROD] \\ rw [] \\ fs [EVERY_MAP] \\ fs [EVERY_MEM] \\ res_tac \\ fs [] \\ qpat_x_assum `_ = flatProps$set_globals _` (assume_tac o GSYM) \\ simp [] \\ rpt (DEEP_INTRO_TAC compile_single_DEEP_INTRO \\ rw [] \\ fs []) QED Theorem compile_eq_set_globals: flat_to_clos$compile m exps = exps' /\ EVERY no_Mat exps ==> closProps$elist_globals exps' = flatProps$elist_globals exps Proof metis_tac [compile_set_globals] QED Theorem compile_decs_set_globals: ∀decs. no_Mat_decs decs ==> closProps$elist_globals (compile_decs decs) = flatProps$elist_globals (MAP dest_Dlet (FILTER is_Dlet decs)) Proof Induct \\ simp [compile_decs_def] \\ Cases \\ simp [compile_decs_def, closPropsTheory.elist_globals_append] \\ simp [compile_set_globals] QED Theorem compile_esgc_free: !m e. EVERY flatProps$esgc_free e /\ EVERY no_Mat e ==> EVERY closProps$esgc_free (flat_to_clos$compile m e) Proof ho_match_mp_tac compile_ind \\ simp [compile_def, closPropsTheory.esgc_free_def] \\ simp [EVERY_REVERSE] \\ rw [] \\ fs [EVERY_REVERSE, Q.ISPEC `no_Mat` ETA_THM] \\ TRY (qmatch_goalsub_abbrev_tac `compile_lit _ lit` \\ Cases_on `lit` \\ simp [compile_lit_def]) \\ TRY (qmatch_goalsub_abbrev_tac `compile_op _ op` \\ Cases_on `op` \\ simp ([compile_op_def] @ props_defs) \\ rpt (CASE_TAC \\ simp props_defs)) \\ TRY (qmatch_goalsub_abbrev_tac `AllocGlobals _ n` \\ Induct_on `n` \\ simp [Once AllocGlobals_def] \\ rw props_defs) \\ simp [compile_def, closPropsTheory.op_gbag_def, flatPropsTheory.op_gbag_def, closPropsTheory.elist_globals_append] \\ rpt ( DEEP_INTRO_TAC compile_single_DEEP_INTRO \\ rw [] \\ fs [] ) \\ simp ([CopyByteAw8_def, CopyByteStr_def] @ props_defs) \\ simp [arg1_def, arg2_def] \\ EVERY_CASE_TAC \\ simp [flatPropsTheory.op_gbag_def, closPropsTheory.op_gbag_def] \\ fs [Q.ISPEC `{||}` EQ_SYM_EQ, EVERY_REVERSE] \\ imp_res_tac compile_eq_set_globals \\ fs [] \\ rpt (DEEP_INTRO_TAC compile_single_DEEP_INTRO \\ rw [] \\ fs []) \\ fs [dest_pat_def] \\ simp [elglobals_EQ_EMPTY, MEM_MAP, PULL_EXISTS] \\ fs [flatPropsTheory.elist_globals_eq_empty, FORALL_PROD, MEM_MAP, PULL_EXISTS] \\ rw [] \\ res_tac \\ DEEP_INTRO_TAC compile_single_DEEP_INTRO \\ rw [] \\ fs [] \\ imp_res_tac compile_eq_set_globals \\ fs [EVERY_MEM, MEM_MAP, PULL_EXISTS, FORALL_PROD] \\ res_tac \\ fs [] QED Theorem compile_decs_esgc_free: !decs. EVERY (flatProps$esgc_free o dest_Dlet) (FILTER is_Dlet decs) /\ no_Mat_decs decs ==> EVERY closProps$esgc_free (compile_decs decs) Proof Induct \\ simp [compile_decs_def] \\ Cases \\ simp [compile_decs_def] \\ simp [compile_esgc_free] QED Theorem compile_syntactic_props: 0 < max_app ⇒ ∀m e. ¬closProps$contains_App_SOME max_app (compile m e) /\ EVERY closProps$no_mti (compile m e) /\ closProps$every_Fn_vs_NONE (compile m e) Proof disch_tac \\ ho_match_mp_tac compile_ind \\ simp ([compile_def] @ props_defs) \\ simp [contains_App_SOME_APPEND, EVERY_REVERSE] \\ rw [] \\ TRY (qmatch_goalsub_abbrev_tac `compile_lit _ lit` \\ Cases_on `lit` \\ simp [compile_lit_def]) \\ TRY (qmatch_goalsub_abbrev_tac `compile_op _ op` \\ Cases_on `op` \\ simp ([compile_op_def] @ props_defs) \\ rpt (CASE_TAC \\ simp props_defs)) \\ TRY (qmatch_goalsub_abbrev_tac `AllocGlobals _ n` \\ Induct_on `n` \\ simp [Once AllocGlobals_def] \\ rw props_defs) \\ simp ([CopyByteAw8_def, CopyByteStr_def] @ props_defs) \\ simp [arg1_def, arg2_def] \\ EVERY_CASE_TAC \\ fs props_defs \\ imp_res_tac EVERY_IMP_HD \\ fs [NULL_LENGTH, EVERY_REVERSE] \\ simp [Once closPropsTheory.contains_App_SOME_EXISTS, Once closPropsTheory.every_Fn_vs_NONE_EVERY, EVERY_MAP, ELIM_UNCURRY] \\ rw [EVERY_MEM, FORALL_PROD] \\ first_x_assum drule \\ rw [] \\ imp_res_tac EVERY_IMP_HD \\ fs [NULL_LENGTH] QED Theorem compile_decs_syntactic_props: !decs. EVERY closProps$no_mti (compile_decs decs) /\ closProps$every_Fn_vs_NONE (compile_decs decs) /\ (0 < max_app ==> ¬closProps$contains_App_SOME max_app (compile_decs decs)) Proof Induct \\ simp ([compile_decs_def] @ props_defs) \\ Cases \\ simp ([compile_decs_def, contains_App_SOME_APPEND] @ props_defs) \\ rw [] \\ simp [compile_syntactic_props] QED val _ = export_theory()
{ "pile_set_name": "Github" }
/*============================================================================= Copyright (c) 2001-2007 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(FUSION_INCLUDE_DISTANCE) #define FUSION_INCLUDE_DISTANCE #include <boost/fusion/support/config.hpp> #include <boost/fusion/iterator/distance.hpp> #endif
{ "pile_set_name": "Github" }
#pragma once #include <string> #include "Entities/Platformer/PlatformerHelper.h" class HexusOpponentData; class LocalizedString; class GuanoPetrified : public PlatformerHelper { public: static GuanoPetrified* deserialize(cocos2d::ValueMap& properties); cocos2d::Vec2 getDialogueOffset() override; LocalizedString* getEntityName() override; static const std::string MapKey; protected: GuanoPetrified(cocos2d::ValueMap& properties); virtual ~GuanoPetrified(); private: typedef PlatformerHelper super; };
{ "pile_set_name": "Github" }
<!--Select Multiple Tags --> <div class="form-group pmd-textfield pmd-textfield-floating-label"> <label>Select Multiple Tags</label> <select class="select-tags form-control pmd-select2-tags" multiple> <option>Dallas Cowboys</option> <option>New York Giants</option> <option>Philadelphia Eagles</option> <option>Washington Redskins</option> <option>Chicago Bears</option> <option>Detroit Lions</option> <option>Green Bay Packers</option> <option>Minnesota Vikings</option> <option>Arizona Cardinals</option> <option>St. Louis Rams</option> <option>San Francisco 49ers</option> <option>Seattle Seahawks</option> <option>Baltimore Ravens</option> <option>Cincinnati Bengals</option> <option>Cleveland Browns</option> <option>Pittsburgh Steelers</option> <option>Houston Texans</option> <option>Indianapolis Colts</option> <option>Jacksonville Jaguars</option> <option>Tennessee Titans</option> <option>Denver Broncos</option> <option>Kansas City Chiefs</option> <option>Oakland Raiders</option> <option>San Diego Chargers</option> </select> </div>
{ "pile_set_name": "Github" }
# ID: PCSH00075 # Title: The Legend of Heroes SEN NO KISEKI II (Chinese Ver.) # Region: ASA/CHN # Version: 1.03 # Type: MAI5 # Code Author: dask # Source: https://github.com/r0ah/vitacheat/blob/master/db/PCSH00075.psv # Original Source: http://www.speedfly.cn/20494.html _V0 Battle in the CP and EP Unabated, STR9999 $A200 81037E62 B3BDF063 $A200 8149B5E0 1090F8D7 $A200 8149B5E4 D1062900 $A200 8149B5E8 81018941 $A200 8149B5EC 818189C1 $A200 8149B5F0 710FF242 $A200 8149B5F4 21008201 $A200 8149B5F8 60316801 $A200 8149B5FC B433F79C _V0 Battle Brave Points Always 5 $A200 811EF6B0 BFAEF2AB $A200 8149B610 F8842205 $A200 8149B614 F55421E3 $A100 8149B618 0000B84D _V0 Mira Max $A100 81167188 0000DD00 _V0 U Substance 99 $A200 81161AE4 BCD0F339 $A200 8149B488 D1042F32 $A200 8149B48C 0863F05F $A200 8149B490 F8A018A0 $A200 8149B494 18A08002 $A200 8149B498 F4C68840 $A100 8149B49C 0000BB25 _V0 Seven Colors Crystals $A200 810CF9B2 7210F646 $A200 810CF9B6 0218F2C0 $A200 8149B470 6C9FF248 $A200 8149B474 0C01F2C0 $A200 8149B478 7210F646 $A200 8149B47C 0218F2C0 $A200 8149B480 BA9BF434 _V0 Spar $A200 8116704A BA28F334 $A200 8149B49E 6C9FF248 $A200 8149B4A2 0C01F2C0 $A200 8149B4A6 C002F840 $A200 8149B4AA 47705880 _V0 Core Loop level 5 $A200 81147D18 BBDEF353 $A200 8149B4D8 F80A2005 $A200 8149B4DC F4AC0B20 $A100 8149B4E0 0000BC1D _V0 Core loop Experience MAX $A200 81147D24 BBDDF353 $A200 8149B4E2 7090F645 $A200 8149B4E6 0001F2C0 $A200 8149B4EA 0B20F848 $A200 8149B4EE BC1BF4AC _V0 Points inherited $A100 811F588E 0000BF00 _V0 Link Experience Max $A200 811EB2CA B8F1F2B0 $A200 8149B4B0 4047F242 $A200 8149B4B4 0900F8C9 $A200 8149B4B8 BF09F54F $A200 811EAF52 BAB5F2B0 $A200 8149B4C0 3900F8D0 $A200 8149B4C4 4446F242 $A200 8149B4C8 DAFF42A3 $A200 8149B4CC F8C01C23 $A200 8149B4D0 F54F3900 $A100 8149B4D4 0000BD40 _V0 Ski championship game smooth clearance $A200 81186DE8 00B0F898 $A200 81186DEC 00B4F888 $A100 81186DF0 00004640 _V0 Faster game speed (don't use with normal speed) $0200 815AD0E4 40000000 _V0 game speed is normal (don't use with faster game speed) $0200 815AD0E4 3F800000 _V0 1 Character Level and Experience MAX $4101 8172F300 000000C8 $0018 00000040 00000000 $0200 8172F304 003DF35F $0200 8172F344 003F3085 $0200 8172F384 003F3085 $0200 8172F3C4 003CB639 $0200 8172F404 003CB639 $0200 8172F444 003DF35F $0200 8172F484 003CB639 $0200 8172F4C4 003F3085 $0200 8172F504 003DF35F $0200 8172F544 003F3085 $0200 8172F584 003DF35F $0200 8172F5C4 003CB639 $0200 8172F604 003DF35F $0200 8172F644 003F3085 $0200 8172F684 003F3085 $0200 8172F6C4 003CB639 $0200 8172F704 003CB639 $0200 8172F744 003DF35F $0200 8172F784 003F3085 $0200 8172F7C4 003DF35F $0200 8172F804 003DF35F $0200 8172F844 003CB639 $0200 8172F884 003DF35F $0200 8172F8C4 003CB639 _V0 AP315 points $0100 815AE04C 0000013B _V0 Fetters action points unabated $5100 815AE038 815AE03C _V0 Fishing times unabated $A100 81177740 00003B00 _V0 Fishing point changes after MAX $A100 81167208 0000E000 $A100 81167218 0000E000 _V0 Props unabated - (buggy code so take caution) $A200 81161C4A 0002F8A9
{ "pile_set_name": "Github" }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Yaml\Tests; use Symfony\Component\Yaml\Yaml; use Symfony\Component\Yaml\Inline; class InlineTest extends \PHPUnit_Framework_TestCase { public function testParse() { foreach ($this->getTestsForParse() as $yaml => $value) { $this->assertEquals($value, Inline::parse($yaml), sprintf('::parse() converts an inline YAML to a PHP structure (%s)', $yaml)); } } public function testDump() { $testsForDump = $this->getTestsForDump(); foreach ($testsForDump as $yaml => $value) { $this->assertEquals($yaml, Inline::dump($value), sprintf('::dump() converts a PHP structure to an inline YAML (%s)', $yaml)); } foreach ($this->getTestsForParse() as $yaml => $value) { $this->assertEquals($value, Inline::parse(Inline::dump($value)), 'check consistency'); } foreach ($testsForDump as $yaml => $value) { $this->assertEquals($value, Inline::parse(Inline::dump($value)), 'check consistency'); } } public function testDumpNumericValueWithLocale() { $locale = setlocale(LC_NUMERIC, 0); if (false === $locale) { $this->markTestSkipped('Your platform does not support locales.'); } $required_locales = array('fr_FR.UTF-8', 'fr_FR.UTF8', 'fr_FR.utf-8', 'fr_FR.utf8', 'French_France.1252'); if (false === setlocale(LC_ALL, $required_locales)) { $this->markTestSkipped('Could not set any of required locales: ' . implode(", ", $required_locales)); } $this->assertEquals('1.2', Inline::dump(1.2)); $this->assertContains('fr', strtolower(setlocale(LC_NUMERIC, 0))); setlocale(LC_ALL, $locale); } public function testHashStringsResemblingExponentialNumericsShouldNotBeChangedToINF() { $value = '686e444'; $this->assertSame($value, Inline::parse(Inline::dump($value))); } /** * @expectedException \Symfony\Component\Yaml\Exception\ParseException */ public function testParseScalarWithIncorrectlyQuotedStringShouldThrowException() { $value = "'don't do somthin' like that'"; Inline::parse($value); } /** * @expectedException \Symfony\Component\Yaml\Exception\ParseException */ public function testParseScalarWithIncorrectlyDoubleQuotedStringShouldThrowException() { $value = '"don"t do somthin" like that"'; Inline::parse($value); } /** * @expectedException \Symfony\Component\Yaml\Exception\ParseException */ public function testParseInvalidMappingKeyShouldThrowException() { $value = '{ "foo " bar": "bar" }'; Inline::parse($value); } public function testParseScalarWithCorrectlyQuotedStringShouldReturnString() { $value = "'don''t do somthin'' like that'"; $expect = "don't do somthin' like that"; $this->assertSame($expect, Inline::parseScalar($value)); } protected function getTestsForParse() { return array( '' => '', 'null' => null, 'false' => false, 'true' => true, '12' => 12, '"quoted string"' => 'quoted string', "'quoted string'" => 'quoted string', '12.30e+02' => 12.30e+02, '0x4D2' => 0x4D2, '02333' => 02333, '.Inf' => -log(0), '-.Inf' => log(0), "'686e444'" => '686e444', '686e444' => 646e444, '123456789123456789' => '123456789123456789', '"foo\r\nbar"' => "foo\r\nbar", "'foo#bar'" => 'foo#bar', "'foo # bar'" => 'foo # bar', "'#cfcfcf'" => '#cfcfcf', '::form_base.html.twig' => '::form_base.html.twig', '2007-10-30' => mktime(0, 0, 0, 10, 30, 2007), '2007-10-30T02:59:43Z' => gmmktime(2, 59, 43, 10, 30, 2007), '2007-10-30 02:59:43 Z' => gmmktime(2, 59, 43, 10, 30, 2007), '"a \\"string\\" with \'quoted strings inside\'"' => 'a "string" with \'quoted strings inside\'', "'a \"string\" with ''quoted strings inside'''" => 'a "string" with \'quoted strings inside\'', // sequences // urls are no key value mapping. see #3609. Valid yaml "key: value" mappings require a space after the colon '[foo, http://urls.are/no/mappings, false, null, 12]' => array('foo', 'http://urls.are/no/mappings', false, null, 12), '[ foo , bar , false , null , 12 ]' => array('foo', 'bar', false, null, 12), '[\'foo,bar\', \'foo bar\']' => array('foo,bar', 'foo bar'), // mappings '{foo:bar,bar:foo,false:false,null:null,integer:12}' => array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12), '{ foo : bar, bar : foo, false : false, null : null, integer : 12 }' => array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12), '{foo: \'bar\', bar: \'foo: bar\'}' => array('foo' => 'bar', 'bar' => 'foo: bar'), '{\'foo\': \'bar\', "bar": \'foo: bar\'}' => array('foo' => 'bar', 'bar' => 'foo: bar'), '{\'foo\'\'\': \'bar\', "bar\"": \'foo: bar\'}' => array('foo\'' => 'bar', "bar\"" => 'foo: bar'), '{\'foo: \': \'bar\', "bar: ": \'foo: bar\'}' => array('foo: ' => 'bar', "bar: " => 'foo: bar'), // nested sequences and mappings '[foo, [bar, foo]]' => array('foo', array('bar', 'foo')), '[foo, {bar: foo}]' => array('foo', array('bar' => 'foo')), '{ foo: {bar: foo} }' => array('foo' => array('bar' => 'foo')), '{ foo: [bar, foo] }' => array('foo' => array('bar', 'foo')), '[ foo, [ bar, foo ] ]' => array('foo', array('bar', 'foo')), '[{ foo: {bar: foo} }]' => array(array('foo' => array('bar' => 'foo'))), '[foo, [bar, [foo, [bar, foo]], foo]]' => array('foo', array('bar', array('foo', array('bar', 'foo')), 'foo')), '[foo, {bar: foo, foo: [foo, {bar: foo}]}, [foo, {bar: foo}]]' => array('foo', array('bar' => 'foo', 'foo' => array('foo', array('bar' => 'foo'))), array('foo', array('bar' => 'foo'))), '[foo, bar: { foo: bar }]' => array('foo', '1' => array('bar' => array('foo' => 'bar'))), '[foo, \'@foo.baz\', { \'%foo%\': \'foo is %foo%\', bar: \'%foo%\' }, true, \'@service_container\']' => array('foo', '@foo.baz', array('%foo%' => 'foo is %foo%', 'bar' => '%foo%',), true, '@service_container',), ); } protected function getTestsForDump() { return array( 'null' => null, 'false' => false, 'true' => true, '12' => 12, "'quoted string'" => 'quoted string', '12.30e+02' => 12.30e+02, '1234' => 0x4D2, '1243' => 02333, '.Inf' => -log(0), '-.Inf' => log(0), "'686e444'" => '686e444', '.Inf' => 646e444, '"foo\r\nbar"' => "foo\r\nbar", "'foo#bar'" => 'foo#bar', "'foo # bar'" => 'foo # bar', "'#cfcfcf'" => '#cfcfcf', "'a \"string\" with ''quoted strings inside'''" => 'a "string" with \'quoted strings inside\'', // sequences '[foo, bar, false, null, 12]' => array('foo', 'bar', false, null, 12), '[\'foo,bar\', \'foo bar\']' => array('foo,bar', 'foo bar'), // mappings '{ foo: bar, bar: foo, \'false\': false, \'null\': null, integer: 12 }' => array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12), '{ foo: bar, bar: \'foo: bar\' }' => array('foo' => 'bar', 'bar' => 'foo: bar'), // nested sequences and mappings '[foo, [bar, foo]]' => array('foo', array('bar', 'foo')), '[foo, [bar, [foo, [bar, foo]], foo]]' => array('foo', array('bar', array('foo', array('bar', 'foo')), 'foo')), '{ foo: { bar: foo } }' => array('foo' => array('bar' => 'foo')), '[foo, { bar: foo }]' => array('foo', array('bar' => 'foo')), '[foo, { bar: foo, foo: [foo, { bar: foo }] }, [foo, { bar: foo }]]' => array('foo', array('bar' => 'foo', 'foo' => array('foo', array('bar' => 'foo'))), array('foo', array('bar' => 'foo'))), '[foo, \'@foo.baz\', { \'%foo%\': \'foo is %foo%\', bar: \'%foo%\' }, true, \'@service_container\']' => array('foo', '@foo.baz', array('%foo%' => 'foo is %foo%', 'bar' => '%foo%',), true, '@service_container',), ); } }
{ "pile_set_name": "Github" }
# The MIT License # # All contents Copyright (c) 2004-2008 Reginald Braithwaite # <http://braythwayt.com> except as otherwise noted. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above Copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # http://www.opensource.org/licenses/mit-license.php module PartialApplicationRecursiveCombinators def multirec(steps, optional_value = nil) worker_proc = lambda do |value| if steps[:divisible?].call(value) steps[:recombine].call( steps[:divide].call(value).map { |sub_value| worker_proc.call(sub_value) } ) else steps[:conquer].call(value) end end if optional_value.nil? worker_proc else worker_proc.call(optional_value) end end def linrec(steps, optional_value = nil) worker_proc = lambda do |value| if steps[:divisible?].call(value) trivial_part, sub_problem = steps[:divide].call(value) steps[:recombine].call( trivial_part, worker_proc.call(sub_problem) ) else steps[:conquer].call(value) end end if optional_value.nil? worker_proc else worker_proc.call(optional_value) end end module_function :multirec, :linrec end
{ "pile_set_name": "Github" }
@REM ---------------------------------------------------------------------------- @REM Licensed to the Apache Software Foundation (ASF) under one @REM or more contributor license agreements. See the NOTICE file @REM distributed with this work for additional information @REM regarding copyright ownership. The ASF licenses this file @REM to you under the Apache License, Version 2.0 (the @REM "License"); you may not use this file except in compliance @REM with the License. You may obtain a copy of the License at @REM @REM http://www.apache.org/licenses/LICENSE-2.0 @REM @REM Unless required by applicable law or agreed to in writing, @REM software distributed under the License is distributed on an @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @REM KIND, either express or implied. See the License for the @REM specific language governing permissions and limitations @REM under the License. @REM ---------------------------------------------------------------------------- @REM ---------------------------------------------------------------------------- @REM Maven2 Start Up Batch script @REM @REM Required ENV vars: @REM JAVA_HOME - location of a JDK home dir @REM @REM Optional ENV vars @REM M2_HOME - location of maven2's installed home dir @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven @REM e.g. to debug Maven itself, use @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files @REM ---------------------------------------------------------------------------- @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' @echo off @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% @REM set %HOME% to equivalent of $HOME if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") @REM Execute a user defined script before this one if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre @REM check for pre script, once with legacy .bat ending and once with .cmd ending if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" :skipRcPre @setlocal set ERROR_CODE=0 @REM To isolate internal variables from possible post scripts, we use another setlocal @setlocal @REM ==== START VALIDATION ==== if not "%JAVA_HOME%" == "" goto OkJHome echo. echo Error: JAVA_HOME not found in your environment. >&2 echo Please set the JAVA_HOME variable in your environment to match the >&2 echo location of your Java installation. >&2 echo. goto error :OkJHome if exist "%JAVA_HOME%\bin\java.exe" goto init echo. echo Error: JAVA_HOME is set to an invalid directory. >&2 echo JAVA_HOME = "%JAVA_HOME%" >&2 echo Please set the JAVA_HOME variable in your environment to match the >&2 echo location of your Java installation. >&2 echo. goto error @REM ==== END VALIDATION ==== :init set MAVEN_CMD_LINE_ARGS=%* @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". @REM Fallback to current working directory if not found. set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir set EXEC_DIR=%CD% set WDIR=%EXEC_DIR% :findBaseDir IF EXIST "%WDIR%"\.mvn goto baseDirFound cd .. IF "%WDIR%"=="%CD%" goto baseDirNotFound set WDIR=%CD% goto findBaseDir :baseDirFound set MAVEN_PROJECTBASEDIR=%WDIR% cd "%EXEC_DIR%" goto endDetectBaseDir :baseDirNotFound set MAVEN_PROJECTBASEDIR=%EXEC_DIR% cd "%EXEC_DIR%" :endDetectBaseDir IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig @setlocal EnableExtensions EnableDelayedExpansion for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% :endReadAdditionalConfig SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% if ERRORLEVEL 1 goto error goto end :error set ERROR_CODE=1 :end @endlocal & set ERROR_CODE=%ERROR_CODE% if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost @REM check for post script, once with legacy .bat ending and once with .cmd ending if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" :skipRcPost @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' if "%MAVEN_BATCH_PAUSE%" == "on" pause if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% exit /B %ERROR_CODE%
{ "pile_set_name": "Github" }
.loader { position: relative; top: 100px; left: 50%; width: 7.33333em; height: 7.33333em; margin-left: -3.66667em; margin-top: -3.66667em; } .block { position: absolute; top: 0; left: 0; display: inline-block; opacity: 0; width: 2em; height: 2em; background: #fdfdfd; animation: show 0.88s step-end infinite alternate, pulse 0.88s linear infinite alternate; } .block:nth-child(1) { transform: translate(0, 0); animation-delay: 0.065s; } .block:nth-child(2) { transform: translate(2.66667em, 0); animation-delay: 0.13s; } .block:nth-child(3) { transform: translate(5.33333em, 0); animation-delay: 0.195s; } .block:nth-child(4) { transform: translate(0, 2.66667em); animation-delay: 0.325s; } .block:nth-child(5) { transform: translate(2.66667em, 2.66667em); animation-delay: 0.13s; } .block:nth-child(6) { transform: translate(5.33333em, 2.66667em); animation-delay: 0.455s; } .block:nth-child(7) { transform: translate(0, 5.33333em); animation-delay: 0.39s; } .block:nth-child(8) { transform: translate(2.66667em, 5.33333em); animation-delay: 0.26s; } .block:nth-child(9) { transform: translate(5.33333em, 5.33333em); } @keyframes pulse { from, 40% { background: #fdfdfd; } to { background: #dadada; } } @keyframes show { from, 40% { opacity: 0; } 41%, to { opacity: 1; } }
{ "pile_set_name": "Github" }
/*************************************** Intrinsics and subroutines exclusive to the Freescale and Metrowerks compilers Copyright (c) 1995-2019 by Rebecca Ann Heineman <[email protected]> It is released under an MIT Open Source license. Please see LICENSE for license details. Yes, you can use it in a commercial title without paying anything, just give me a credit. Please? It's not like I'm asking you for money! ***************************************/ #ifndef __BRMETROWERKS_H__ #define __BRMETROWERKS_H__ #ifndef __BRTYPES_H__ #include "brtypes.h" #endif // Hidden intrinsics 68K and x86 // C_Compilers_Reference_3.2,pdf page 51 // __rol(uint16_t uInput,uint8_t uShift); // __rol(uint32_t uInput,uint8_t uShift); // __ror(uint16_t uInput,uint8_t uShift); // __ror(uint32_t uInput,uint8_t uShift); /* BEGIN */ #if defined(BURGER_METROWERKS) && !defined(DOXYGEN) extern "C" { #if defined(BURGER_X86) extern float __builtin_fabsf(float) __attribute__((nothrow)) __attribute__((const)); extern double __builtin_fabs(double) __attribute__((nothrow)) __attribute__((const)); extern double __builtin_sqrt(double) __attribute__((nothrow)) __attribute__((const)); extern unsigned int __builtin___count_leading_zero32(unsigned int) __attribute__((nothrow)) __attribute__((const)); extern unsigned int __builtin___count_trailing_zero32(unsigned int) __attribute__((nothrow)) __attribute__((const)); extern unsigned int __builtin___count_leading_zero64(unsigned long long) __attribute__((nothrow)) __attribute__((const)); extern unsigned int __builtin___count_trailing_zero64(unsigned long long) __attribute__((nothrow)) __attribute__((const)); // extern unsigned int __builtin___count_bits32(unsigned long long) // __attribute__((nothrow)) __attribute__((const)); extern unsigned int // __builtin___count_bits64(unsigned long long) __attribute__((nothrow)) // __attribute__((const)); BURGER_INLINE long _InterlockedExchange( register long volatile* pOutput, register long lValue) { __asm lock xchg lValue, [pOutput]; return lValue; } BURGER_INLINE long _InterlockedIncrement(register long volatile* pOutput) { register long lTemp = 1; __asm lock xadd[pOutput], lTemp; return lTemp + 1; } BURGER_INLINE long _InterlockedDecrement(register long volatile* pOutput) { register long lTemp = -1; __asm lock xadd[pOutput], lTemp; return lTemp - 1; } BURGER_INLINE long _InterlockedExchangeAdd( register long volatile* pOutput, register long lValue) { __asm lock xadd[pOutput], lValue; return lValue; } BURGER_INLINE long _InterlockedCompareExchange(register long volatile* pOutput, register long lAfter, register long lBefore) { __asm { mov eax,lBefore lock xadd [pOutput],lAfter mov lBefore,eax } return lBefore; } BURGER_INLINE void __cpuid(int a[4], int b) { // clang-format off BURGER_ASM { // Get the pointer to the destination buffer mov esi,a mov eax,b // Command byte cpuid // Invoke CPUID // Store the result in the same order as Visual C mov[esi],eax mov[esi + 4],ebx mov[esi + 8],ecx mov[esi + 12],edx } // clang-format on } BURGER_INLINE void __cpuidex(int a[4], int b, int c) { // clang-format off BURGER_ASM { // Get the pointer to the destination buffer mov esi,a mov eax,b // Command byte mov ecx,c // Get the sub command cpuid // Invoke CPUID // Store the result in the same order as Visual C mov[esi],eax mov[esi + 4],ebx mov[esi + 8],ecx mov[esi + 12],edx } // clang-format on } BURGER_INLINE uint32_t _BitScanForward( register unsigned long* Index, register unsigned long Mask) { // clang-format off BURGER_ASM { mov eax, Mask mov ebx, Index bsf eax, eax mov dword ptr[ebx],eax setne al } // clang-format on } BURGER_INLINE uint32_t _BitScanReverse( register unsigned long* Index, register unsigned long Mask) { // clang-format off BURGER_ASM { mov eax, Mask mov ebx, Index bsr eax, eax mov dword ptr[ebx],eax setne al } // clang-format on } #elif defined(BURGER_68K) // muls.l d1,d1:d0 #pragma parameter __D1 BurgerIntMathMul32GetUpper32(__D0, __D1) Int32 BurgerIntMathMul32GetUpper32(Int32 iInputMulA, Int32 iInputMulB) = { 0x4c01, 0xc01}; // muls.l d1,d1:d0 // divs.l d2,d1:d0 #pragma parameter __D0 BurgerIntMathMul32x32To64Div32(__D0, __D1, __D2) Int32 BurgerIntMathMul32x32To64Div32(Int32 iInputMulA, Int32 iInputMulB, Int32 iInputDiv) = {0x4c01, 0xc01, 0x4c42, 0xc01}; extern double __fabs(double x); extern void* __alloca(unsigned x); #elif defined(BURGER_PPC) // Most PowerPC CPUs don't have fsqrt or fsqrts in hardware. // Use Burgerlib's Sqrt() which is optimized PPC code extern double sqrt(double); BURGER_INLINE float sqrtf(float fInput) { return static_cast<float>(sqrt(fInput)); } #if __has_intrinsic(__builtin___rotate_left32) extern unsigned int __builtin___rotate_left32(unsigned int, int) __attribute__((nothrow)) __attribute__((const)); #endif #if __has_intrinsic(__builtin___rotate_right32) extern unsigned int __builtin___rotate_right32(unsigned int, int) __attribute__((nothrow)) __attribute__((const)); #endif #endif } #endif /* END */ #endif
{ "pile_set_name": "Github" }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2014 Benoit Steiner <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #if defined(EIGEN_USE_THREADS) && !defined(EIGEN_CXX11_TENSOR_TENSOR_DEVICE_THREAD_POOL_H) #define EIGEN_CXX11_TENSOR_TENSOR_DEVICE_THREAD_POOL_H namespace Eigen { // Barrier is an object that allows one or more threads to wait until // Notify has been called a specified number of times. class Barrier { public: Barrier(unsigned int count) : state_(count << 1), notified_(false) { eigen_assert(((count << 1) >> 1) == count); } ~Barrier() { eigen_assert((state_>>1) == 0); } void Notify() { unsigned int v = state_.fetch_sub(2, std::memory_order_acq_rel) - 2; if (v != 1) { eigen_assert(((v + 2) & ~1) != 0); return; // either count has not dropped to 0, or waiter is not waiting } std::unique_lock<std::mutex> l(mu_); eigen_assert(!notified_); notified_ = true; cv_.notify_all(); } void Wait() { unsigned int v = state_.fetch_or(1, std::memory_order_acq_rel); if ((v >> 1) == 0) return; std::unique_lock<std::mutex> l(mu_); while (!notified_) { cv_.wait(l); } } private: std::mutex mu_; std::condition_variable cv_; std::atomic<unsigned int> state_; // low bit is waiter flag bool notified_; }; // Notification is an object that allows a user to to wait for another // thread to signal a notification that an event has occurred. // // Multiple threads can wait on the same Notification object, // but only one caller must call Notify() on the object. struct Notification : Barrier { Notification() : Barrier(1) {}; }; // Runs an arbitrary function and then calls Notify() on the passed in // Notification. template <typename Function, typename... Args> struct FunctionWrapperWithNotification { static void run(Notification* n, Function f, Args... args) { f(args...); if (n) { n->Notify(); } } }; template <typename Function, typename... Args> struct FunctionWrapperWithBarrier { static void run(Barrier* b, Function f, Args... args) { f(args...); if (b) { b->Notify(); } } }; template <typename SyncType> static EIGEN_STRONG_INLINE void wait_until_ready(SyncType* n) { if (n) { n->Wait(); } } // Build a thread pool device on top the an existing pool of threads. struct ThreadPoolDevice { // The ownership of the thread pool remains with the caller. ThreadPoolDevice(ThreadPoolInterface* pool, int num_cores) : pool_(pool), num_threads_(num_cores) { } EIGEN_STRONG_INLINE void* allocate(size_t num_bytes) const { return internal::aligned_malloc(num_bytes); } EIGEN_STRONG_INLINE void deallocate(void* buffer) const { internal::aligned_free(buffer); } EIGEN_STRONG_INLINE void memcpy(void* dst, const void* src, size_t n) const { ::memcpy(dst, src, n); } EIGEN_STRONG_INLINE void memcpyHostToDevice(void* dst, const void* src, size_t n) const { memcpy(dst, src, n); } EIGEN_STRONG_INLINE void memcpyDeviceToHost(void* dst, const void* src, size_t n) const { memcpy(dst, src, n); } EIGEN_STRONG_INLINE void memset(void* buffer, int c, size_t n) const { ::memset(buffer, c, n); } EIGEN_STRONG_INLINE int numThreads() const { return num_threads_; } EIGEN_STRONG_INLINE size_t firstLevelCacheSize() const { return l1CacheSize(); } EIGEN_STRONG_INLINE size_t lastLevelCacheSize() const { // The l3 cache size is shared between all the cores. return l3CacheSize() / num_threads_; } EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int majorDeviceVersion() const { // Should return an enum that encodes the ISA supported by the CPU return 1; } template <class Function, class... Args> EIGEN_STRONG_INLINE Notification* enqueue(Function&& f, Args&&... args) const { Notification* n = new Notification(); pool_->Schedule(std::bind(&FunctionWrapperWithNotification<Function, Args...>::run, n, f, args...)); return n; } template <class Function, class... Args> EIGEN_STRONG_INLINE void enqueue_with_barrier(Barrier* b, Function&& f, Args&&... args) const { pool_->Schedule(std::bind( &FunctionWrapperWithBarrier<Function, Args...>::run, b, f, args...)); } template <class Function, class... Args> EIGEN_STRONG_INLINE void enqueueNoNotification(Function&& f, Args&&... args) const { pool_->Schedule(std::bind(f, args...)); } // Returns a logical thread index between 0 and pool_->NumThreads() - 1 if // called from one of the threads in pool_. Returns -1 otherwise. EIGEN_STRONG_INLINE int currentThreadId() const { return pool_->CurrentThreadId(); } // parallelFor executes f with [0, n) arguments in parallel and waits for // completion. F accepts a half-open interval [first, last). // Block size is choosen based on the iteration cost and resulting parallel // efficiency. If block_align is not nullptr, it is called to round up the // block size. void parallelFor(Index n, const TensorOpCost& cost, std::function<Index(Index)> block_align, std::function<void(Index, Index)> f) const { typedef TensorCostModel<ThreadPoolDevice> CostModel; if (n <= 1 || numThreads() == 1 || CostModel::numThreads(n, cost, static_cast<int>(numThreads())) == 1) { f(0, n); return; } // Calculate block size based on (1) the iteration cost and (2) parallel // efficiency. We want blocks to be not too small to mitigate // parallelization overheads; not too large to mitigate tail // effect and potential load imbalance and we also want number // of blocks to be evenly dividable across threads. double block_size_f = 1.0 / CostModel::taskSize(1, cost); Index block_size = numext::mini(n, numext::maxi<Index>(1, block_size_f)); const Index max_block_size = numext::mini(n, numext::maxi<Index>(1, 2 * block_size_f)); if (block_align) { Index new_block_size = block_align(block_size); eigen_assert(new_block_size >= block_size); block_size = numext::mini(n, new_block_size); } Index block_count = divup(n, block_size); // Calculate parallel efficiency as fraction of total CPU time used for // computations: double max_efficiency = static_cast<double>(block_count) / (divup<int>(block_count, numThreads()) * numThreads()); // Now try to increase block size up to max_block_size as long as it // doesn't decrease parallel efficiency. for (Index prev_block_count = block_count; prev_block_count > 1;) { // This is the next block size that divides size into a smaller number // of blocks than the current block_size. Index coarser_block_size = divup(n, prev_block_count - 1); if (block_align) { Index new_block_size = block_align(coarser_block_size); eigen_assert(new_block_size >= coarser_block_size); coarser_block_size = numext::mini(n, new_block_size); } if (coarser_block_size > max_block_size) { break; // Reached max block size. Stop. } // Recalculate parallel efficiency. const Index coarser_block_count = divup(n, coarser_block_size); eigen_assert(coarser_block_count < prev_block_count); prev_block_count = coarser_block_count; const double coarser_efficiency = static_cast<double>(coarser_block_count) / (divup<int>(coarser_block_count, numThreads()) * numThreads()); if (coarser_efficiency + 0.01 >= max_efficiency) { // Taking it. block_size = coarser_block_size; block_count = coarser_block_count; if (max_efficiency < coarser_efficiency) { max_efficiency = coarser_efficiency; } } } // Recursively divide size into halves until we reach block_size. // Division code rounds mid to block_size, so we are guaranteed to get // block_count leaves that do actual computations. Barrier barrier(static_cast<unsigned int>(block_count)); std::function<void(Index, Index)> handleRange; handleRange = [=, &handleRange, &barrier, &f](Index first, Index last) { if (last - first <= block_size) { // Single block or less, execute directly. f(first, last); barrier.Notify(); return; } // Split into halves and submit to the pool. Index mid = first + divup((last - first) / 2, block_size) * block_size; pool_->Schedule([=, &handleRange]() { handleRange(mid, last); }); handleRange(first, mid); }; handleRange(0, n); barrier.Wait(); } // Convenience wrapper for parallelFor that does not align blocks. void parallelFor(Index n, const TensorOpCost& cost, std::function<void(Index, Index)> f) const { parallelFor(n, cost, nullptr, std::move(f)); } private: ThreadPoolInterface* pool_; int num_threads_; }; } // end namespace Eigen #endif // EIGEN_CXX11_TENSOR_TENSOR_DEVICE_THREAD_POOL_H
{ "pile_set_name": "Github" }
/* * Copyright (C) 2009 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 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. */ #include "config.h" #include "AccessibleImage.h" #include <WebCore/AccessibilityRenderObject.h> #include <WebCore/HTMLNames.h> using namespace WebCore; using namespace WebCore::HTMLNames; AccessibleImage::AccessibleImage(AccessibilityObject* obj) : AccessibleBase(obj) { ASSERT_ARG(obj, obj->isImage()); ASSERT_ARG(obj, obj->isAccessibilityRenderObject()); } String AccessibleImage::name() const { if (!m_object->isAccessibilityRenderObject()) return AccessibleBase::name(); AccessibilityRenderObject* obj = static_cast<AccessibilityRenderObject*>(m_object); String ariaLabel = obj->ariaLabeledByAttribute(); if (!ariaLabel.isEmpty()) return ariaLabel; const AtomicString& altText = obj->getAttribute(HTMLNames::altAttr); if (!altText.isEmpty()) return altText; return AccessibleBase::name(); }
{ "pile_set_name": "Github" }
/* * Generic big.LITTLE CPUFreq Interface driver * * It provides necessary ops to arm_big_little cpufreq driver and gets * Frequency information from Device Tree. Freq table in DT must be in KHz. * * Copyright (C) 2013 Linaro. * Viresh Kumar <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed "as is" WITHOUT ANY WARRANTY of any * kind, whether express or implied; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/cpufreq.h> #include <linux/device.h> #include <linux/export.h> #include <linux/module.h> #include <linux/of_device.h> #include <linux/pm_opp.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/types.h> #include "arm_big_little.h" /* get cpu node with valid operating-points */ static struct device_node *get_cpu_node_with_valid_op(int cpu) { struct device_node *np = of_cpu_device_node_get(cpu); if (!of_get_property(np, "operating-points", NULL)) { of_node_put(np); np = NULL; } return np; } static int dt_get_transition_latency(struct device *cpu_dev) { struct device_node *np; u32 transition_latency = CPUFREQ_ETERNAL; np = of_node_get(cpu_dev->of_node); if (!np) { pr_info("Failed to find cpu node. Use CPUFREQ_ETERNAL transition latency\n"); return CPUFREQ_ETERNAL; } of_property_read_u32(np, "clock-latency", &transition_latency); of_node_put(np); pr_debug("%s: clock-latency: %d\n", __func__, transition_latency); return transition_latency; } static const struct cpufreq_arm_bL_ops dt_bL_ops = { .name = "dt-bl", .get_transition_latency = dt_get_transition_latency, .init_opp_table = dev_pm_opp_of_cpumask_add_table, .free_opp_table = dev_pm_opp_of_cpumask_remove_table, }; static int generic_bL_probe(struct platform_device *pdev) { struct device_node *np; np = get_cpu_node_with_valid_op(0); if (!np) return -ENODEV; of_node_put(np); return bL_cpufreq_register(&dt_bL_ops); } static int generic_bL_remove(struct platform_device *pdev) { bL_cpufreq_unregister(&dt_bL_ops); return 0; } static struct platform_driver generic_bL_platdrv = { .driver = { .name = "arm-bL-cpufreq-dt", }, .probe = generic_bL_probe, .remove = generic_bL_remove, }; module_platform_driver(generic_bL_platdrv); MODULE_AUTHOR("Viresh Kumar <[email protected]>"); MODULE_DESCRIPTION("Generic ARM big LITTLE cpufreq driver via DT"); MODULE_LICENSE("GPL v2");
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>${EXECUTABLE_NAME}</string> <key>CFBundleIdentifier</key> <string>com.github.${PRODUCT_NAME:rfc1034identifier}</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundlePackageType</key> <string>BNDL</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>1</string> </dict> </plist>
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 50848317f66fb4a4b8e4293c56763736 timeCreated: 1427406000 licenseType: Free DefaultImporter: userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
--- layout: model title: Progressive shift model-language: webppl --- A model of progressive vs. imperfective aspect by Becky Jarvis and Gunnar Lund: ~~~~ //Generate the state space given a number of events var stateGen = function(numberBins) { var stateSoFar = [] var binSize = 1 / numberBins var binArray = _.range(0, numberBins) var eventPop = map(function(x){return Math.round(((binSize/2)+(binSize*x))*100)/100}, binArray) var newEvents = stateSoFar.concat(eventPop) return newEvents } //Power set helper function, from lexical uncertainty model. var powerset = function(set){ if(set.length==0){ return [set] } var r = powerset(set.slice(1)) // exlude first element var element = [set[0]] // first element var new_r = r.concat(map(function(x){ element.concat(x) }, r)) return new_r } //Generate the states and then apply the powerset (removing empty set) var allstates = stateGen(5) var powersetStates = filter(function(x){return x.length>0},powerset(allstates)) //Return uniform draw of the powerset of states. var statePrior = function() { return uniformDraw(powersetStates) } //utterances and utterancePrior function; requires null utt due to threshold semantics var utterances = ["prog", "impf",""] var cost = { "prog": 5, "impf": 1, "": 100 } var utterancePrior = function() { var uttProbs = map(function(u) {return Math.exp(-cost[u]) }, utterances); return categorical(uttProbs, utterances); }; //List of possibe thetas var possibleThetas = [0.4,0.5,0.6,0.7,0.8,0.9,1] //Generate ordered pair <thetaR, thetaImpf> s.t. thetaImpf is greater than or equal to thetaR var thetaGen = function(number, stateSoFar) { var stateSoFar = stateSoFar == undefined ? [] : stateSoFar if (number != -1) { var newThetaN = map(function(x){if (x >= possibleThetas[number]){return [possibleThetas[number], x]}}, possibleThetas) var newThetas = stateSoFar.concat(newThetaN) return thetaGen(number-1, newThetas) } else { return remove(null, stateSoFar) } } //the possibleThetas.length argument is essentially an index for the recursive function. var thetas = thetaGen(possibleThetas.length) var thetasPrior = function(){ return uniformDraw(thetas) } //Generates the bins from the different thetas var thetaBins = function(numberBins, theta) { var newBins = [0] var binSize = theta / numberBins var binArray = _.range(0, numberBins) var binPop = map(function(x){return (binSize)+(binSize*x)}, binArray) var newEvents = newBins.concat(binPop) return newEvents } //meaning fxn: checks to make sure at least one event is contained in every bin. var meaningFn = function(state, bins, index, stateSoFar){ var stateSoFar = stateSoFar == undefined ? [] : stateSoFar if (index != bins.length-1){ var inBin = any(function(x){return x>bins[index] && x<=bins[index+1]}, state) var eventsInBins = stateSoFar.concat(inBin) return meaningFn(state, bins, index+1, eventsInBins) } else { return all(function(x){return x==true}, stateSoFar) } } //Actually apply the meaning function for the utterances var meaning = function(utterance, binsR, binsT, state) { if (utterance == "prog") { return meaningFn(state, binsR, 0) } else if (utterance == "impf") { return meaningFn(state, binsT, 0) } else { return true } } //Alphas and bins var alpha = 1 var nBins = 2 //our actors: var literalListener = cache(function(utterance, thetaR, thetaT) { return Infer({model: function() { var state = statePrior(); var binsR = thetaBins(nBins, thetaR); var binsT = thetaBins(nBins, thetaT); condition(meaning(utterance, binsR, binsT, state)) return state; }}); }); var speaker = cache(function(state, thetaR, thetaT) { return Infer({method: "enumerate"}, function() { var utterance = utterancePrior(); factor(alpha * literalListener(utterance, thetaR, thetaT).score(state)); return utterance; }); }); var pragmaticListener = function(utterance) { return Infer({method: "enumerate"}, function() { var state = statePrior(); var thetas = thetasPrior(); var thetaR = thetas[0] var thetaT = thetas[1] factor(speaker(state, thetaR, thetaT).score(utterance)); return {state: state, thetaR: thetaR, thetaT: thetaT}; }); }; viz.marginals(pragmaticListener("prog")) ~~~~
{ "pile_set_name": "Github" }
{ "data": { "__type": { "name": "CreateRejectionSurveyAnswerPayload", "description": "Autogenerated return type of CreateRejectionSurveyAnswer", "fields": [ { "name": "clientMutationId", "type": { "name": "String", "kind": "SCALAR", "ofType": null } }, { "name": "errors", "type": { "name": null, "kind": "NON_NULL", "ofType": { "name": "ErrorConnection", "kind": "OBJECT" } } }, { "name": "me", "type": { "name": "User", "kind": "OBJECT", "ofType": null } }, { "name": "was_successful", "type": { "name": null, "kind": "NON_NULL", "ofType": { "name": "Boolean", "kind": "SCALAR" } } } ] } } }
{ "pile_set_name": "Github" }
Tests a project file with a resource. You should see --resource:obj/Debug/Sample_VS2012_FSharp_ConsoleApp_net45.resource.txt on the command line when you run xbuild on the .fsproj file
{ "pile_set_name": "Github" }
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springsource.restbucks.payment; import java.util.Optional; import org.springsource.restbucks.order.Order; import org.springsource.restbucks.payment.Payment.Receipt; /** * Interface to collect payment services. * * @author Oliver Gierke */ public interface PaymentService { /** * Pay the given {@link Order} with the {@link CreditCard} identified by the given {@link CreditCardNumber}. * * @param order * @param creditCardNumber * @return */ CreditCardPayment pay(Order order, CreditCardNumber creditCardNumber); /** * Returns the {@link Payment} for the given {@link Order}. * * @param order * @return the {@link Payment} for the given {@link Order} or {@link Optional#empty()} if the Order hasn't been payed * yet. */ Optional<Payment> getPaymentFor(Order order); /** * Takes the receipt * * @param order * @return */ Optional<Receipt> takeReceiptFor(Order order); }
{ "pile_set_name": "Github" }
begin 664 test_read_format_zip_encryption_header.zip M4$L#!#,`02``````````````5@$````````!````,1``X3'*9,%K7_13)[I3 MUO.*N2`!```#`!!F``$!`)``M'BJYI=VD<MB76[?O3IDTVM#',YK$L&:DX!C ML%00Q:QRCM/8%XJ.8''-JI$Z*\!\`]%-[F'4"G01L1E]L[ST_7"*)/_/9VO1 MLKUI\AFKFUK@M89K)2HI3-"XGZN4SSBEZ&\F@R?>ZMXC4&]B1)Q%WJ/M`8VS M%S*.0\5[MJ34[W"H8*AO==S@TG'S'J'3A;8C`````(``4-?ZX*L^`*0786KZ ME7<\#%<[_`^#/MO"P\3FX5`^9`Q%(S:FDO98B*C`BC%'XQ0*X"FMO8[@3'S@ MX(JO5(Q:8-&AM8(OPBY40\O!"%Z5'>I\/<_(AA-%)*TBI6YT6!WEM7L,-"W( M/GE:7T.B39$3C.W)X2`A=KV-UB4C7<C^OV&:"B?Y]DU=W2*(SFV=8Q]D\Q*W M%B9E>I?6B-!F<"?VLE!+`P0S`$$@`````````````%8!`````````0```#(0 M`%(U7N:0Z+,VS3SNJBRE_=`@`0```P`09@`!`0"0`+1XJN:7=I'+8EUNW[TZ M9--K0QS.:Q+!FI.`8[!4$,6L<H[3V!>*CF!QS:J1.BO`?`/13>YAU`IT$;$9 M?;.\]/UPBB3_SV=KT;*]:?(9JYM:X+6&:R4J*4S0N)^KE,\XI>AO)H,GWNK> M(U!O8D2<1=ZC[0&-LQ<RCD/%>[:DU.]PJ&"H;W7<X-)Q\QZATX6V(P````"` M`&O$^CTH9KN(X?(:`+,T7:PMJ"E"?LTSG9^$P881P?4X"%AG>CYF;:)G.8S3 M%AT<])L+^"37+I@-S&ALBA\_10'AM,+6C"RP!FEV@VW1"2PDL->Q5HL*M[X( M];^?-43F%4=UMP/U>8<DO/W\7,S2S5MSP96Y5"C'I3MST([/-X3(VZQ.XNGM M>3:C4K&OM*'&=DS[_V!*YK9X(6G9R,]GJ\\0`!A&@I%F4R!H=;RQSVWL,/D@ M`0```P`09@`!`0"0`+1XJN:7=I'+8EUNW[TZ9--K0QS.:Q+!FI.`8[!4$,6L M<H[3V!>*CF!QS:J1.BO`?`/13>YAU`IT$;$9?;.\]/UPBB3_SV=KT;*]:?(9 MJYM:X+6&:R4J*4S0N)^KE,\XI>AO)H,GWNK>(U!O8D2<1=ZC[0&-LQ<RCD/% M>[:DU.]PJ&"H;W7<X-)Q\QZATX6V(P````"``(/(E'//(-;AFW-I#4'M.C!+ MWZ-\VREA15;E6=_G,KY#<1*,3$U0:B#`]\N[&'P`IT9>A2^EL1N!T3'%DP<< MXY=DJB$8LS8KERBNN[I*X]M"?A<Q))<H]YV`F<GNWHI#Z].M5&6VM)!B&&/1 M&15"]OG@91-531!<@R6L;"PIU/R)H]QUVXIM$G9<!+J]4N0\+SL(Q,5?)."! MY-^!/U`V$I@O%ZUMU2755&HDUS$*:?33>\FYX"B`IP_XMQ-.*H3#`XY.,-K% M0`Z%4:U*W#IM_DBOP-$^?R<8,!%#Z6F1`?;Z:=LG6@'C+#0I[]^+E$0'L5!+ M!@9,`````````$``/@```````````````````````@````````"F`0`````` M`.H"````````"`"F`0```````-(`````````$&8``0$``0`$``"$P.)02P8' F`````)`$`````````0```%!+!08```````#__Z8!``#J`@`````` ` end
{ "pile_set_name": "Github" }
/* * libwebsockets - small server side websockets and web server implementation * * Copyright (C) 2019 - 2020 Andy Green <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. * * * When the user code is in a different process, a non-tls unix domain socket * proxy is used to asynchronusly transfer buffers in each direction via the * network stack, without explicit IPC * * user_process{ [user code] | shim | socket-}------ lws_process{ lws } * * Lws exposes a listening unix domain socket in this case, the user processes * connect to it and pass just info.streamtype in an initial tx packet. All * packets are prepended by a 1-byte type field when used in this mode. See * lws-secure-streams.h for documentation and definitions. * * Proxying in either direction can face the situation it cannot send the onward * packet immediately and is subject to separating the write request from the * write action. To make the best use of memory, a single preallocated buffer * stashes pending packets in all four directions (c->p, p->c, p->ss, ss->p). * This allows it to adapt to different traffic patterns without wasted areas * dedicated to traffic that isn't coming in a particular application. * * A shim is provided to monitor the process' unix domain socket and regenerate * the secure sockets api there with callbacks happening in the process thread * context. * * This file implements the listening unix domain socket proxy... this code is * only going to run on a Linux-class device with its implications about memory * availability. */ #include <private-lib-core.h> /* * Because both sides of the connection share the conn, we allocate it * during accepted adoption, and both sides point to it. * * The last one of the accepted side and the onward side to close frees it. */ struct conn { struct lws_ss_serialization_parser parser; lws_dsh_t *dsh; /* unified buffer for both sides */ struct lws *wsi; /* the client side */ lws_ss_handle_t *ss; /* the onward, ss side */ lws_ss_conn_states_t state; }; struct raw_pss { struct conn *conn; }; /* * Proxy - onward secure-stream handler */ typedef struct ss_proxy_onward { lws_ss_handle_t *ss; struct conn *conn; } ss_proxy_t; /* secure streams payload interface */ static int ss_proxy_onward_rx(void *userobj, const uint8_t *buf, size_t len, int flags) { ss_proxy_t *m = (ss_proxy_t *)userobj; const char *rsp = NULL; int n; // lwsl_notice("%s: len %d\n", __func__, (int)len); /* * The onward secure stream connection has received something. */ if (m->ss->rideshare != m->ss->policy && m->ss->rideshare) { rsp = m->ss->rideshare->streamtype; flags |= LWSSS_FLAG_RIDESHARE; } n = lws_ss_serialize_rx_payload(m->conn->dsh, buf, len, flags, rsp); if (n) return n; if (m->conn->wsi) /* if possible, request client conn write */ lws_callback_on_writable(m->conn->wsi); return 0; } /* * we are transmitting buffered payload originally from the client on to the ss */ static int ss_proxy_onward_tx(void *userobj, lws_ss_tx_ordinal_t ord, uint8_t *buf, size_t *len, int *flags) { ss_proxy_t *m = (ss_proxy_t *)userobj; void *p; size_t si; if (!m->conn->ss || m->conn->state != LPCSPROX_OPERATIONAL) { lwsl_notice("%s: ss not ready\n", __func__); *len = 0; return 1; } /* * The onward secure stream says that we could send something to it * (by putting it in buf, and setting *len and *flags) */ if (lws_ss_deserialize_tx_payload(m->conn->dsh, m->ss->wsi, ord, buf, len, flags)) return 1; if (!lws_dsh_get_head(m->conn->dsh, KIND_C_TO_P, (void **)&p, &si)) lws_ss_request_tx(m->conn->ss); if (!*len && !*flags) return 1; /* we don't actually want to send anything */ lwsl_info("%s: onward tx %d fl 0x%x\n", __func__, (int)*len, *flags); #if 0 { int ff = open("/tmp/z", O_RDWR | O_CREAT | O_APPEND, 0666); if (ff == -1) lwsl_err("%s: errno %d\n", __func__, errno); write(ff, buf, *len); close(ff); } #endif return 0; } static int ss_proxy_onward_state(void *userobj, void *sh, lws_ss_constate_t state, lws_ss_tx_ordinal_t ack) { ss_proxy_t *m = (ss_proxy_t *)userobj; switch (state) { case LWSSSCS_CREATING: break; case LWSSSCS_DESTROYING: if (!m->conn) break; if (!m->conn->wsi) { /* * Our onward secure stream is closing and our client * connection has already gone away... destroy the conn. */ lwsl_info("%s: Destroying conn\n", __func__); lws_dsh_destroy(&m->conn->dsh); free(m->conn); m->conn = NULL; return 0; } else lwsl_info("%s: ss DESTROYING, wsi up\n", __func__); break; default: break; } if (!m->conn) { lwsl_warn("%s: dropping state due to conn not up\n", __func__); return 0; } lws_ss_serialize_state(m->conn->dsh, state, ack); if (m->conn->wsi) /* if possible, request client conn write */ lws_callback_on_writable(m->conn->wsi); return 0; } void ss_proxy_onward_txcr(void *userobj, int bump) { ss_proxy_t *m = (ss_proxy_t *)userobj; if (!m->conn) return; lws_ss_serialize_txcr(m->conn->dsh, bump); if (m->conn->wsi) /* if possible, request client conn write */ lws_callback_on_writable(m->conn->wsi); } /* * Client - Proxy connection on unix domain socket */ static int callback_ss_proxy(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { struct lws_context_per_thread *pt = &wsi->a.context->pt[(int)wsi->tsi]; struct raw_pss *pss = (struct raw_pss *)user; const lws_ss_policy_t *rsp; struct conn *conn = NULL; lws_ss_info_t ssi; const uint8_t *cp; #if defined(LWS_WITH_DETAILED_LATENCY) lws_usec_t us; #endif char s[128]; uint8_t *p; size_t si; char pay; int n; if (pss) conn = pss->conn; switch (reason) { case LWS_CALLBACK_PROTOCOL_INIT: break; case LWS_CALLBACK_PROTOCOL_DESTROY: break; /* callbacks related to raw socket descriptor "accepted side" */ case LWS_CALLBACK_RAW_ADOPT: lwsl_info("LWS_CALLBACK_RAW_ADOPT\n"); if (!pss) return -1; pss->conn = malloc(sizeof(struct conn)); if (!pss->conn) return -1; memset(pss->conn, 0, sizeof(*pss->conn)); pss->conn->dsh = lws_dsh_create(&pt->ss_dsh_owner, LWS_SS_MTU * 160, 2); if (!pss->conn->dsh) { free(pss->conn); return -1; } pss->conn->wsi = wsi; pss->conn->state = LPCSPROX_WAIT_INITIAL_TX; /* * Client is expected to follow the unix domain socket * acceptance up rapidly with an initial tx containing the * streamtype name. We can't create the stream until then. */ lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND, 3); break; case LWS_CALLBACK_RAW_CLOSE: lwsl_info("LWS_CALLBACK_RAW_CLOSE:\n"); if (!conn) break; /* * the client unix domain socket connection (wsi / conn->wsi) * has closed... eg, client has exited or otherwise has * definitively finished with the proxying and onward connection * * But right now, the SS and possibly the SS onward wsi are * still live... */ if (conn->ss) { struct lws *cw = conn->ss->wsi; /* * The onward connection is around */ lwsl_info("%s: destroying ss.h=%p, ss.wsi=%p\n", __func__, conn->ss, conn->ss->wsi); /* sever relationship with ss about to be deleted */ lws_set_opaque_user_data(wsi, NULL); if (wsi != cw) /* * The wsi doing the onward connection can no * longer relate to the conn... otherwise when * he gets callbacks he wants to bind to * the ss we are about to delete */ lws_wsi_close(cw, LWS_TO_KILL_ASYNC); conn->wsi = NULL; lws_ss_destroy(&conn->ss); /* conn may have gone */ break; } if (conn->state == LPCSPROX_DESTROYED || !conn->ss) { /* * There's no onward secure stream and our client * connection is closing. Destroy the conn. */ lws_dsh_destroy(&conn->dsh); free(conn); pss->conn = NULL; } else lwsl_debug("%s: CLOSE; ss=%p\n", __func__, conn->ss); break; case LWS_CALLBACK_RAW_RX: /* * ie, the proxy is receiving something from a client */ lwsl_info("%s: RX: rx %d\n", __func__, (int)len); if (!conn || !conn->wsi) { lwsl_err("%s: rx with bad conn state\n", __func__); return -1; } // lwsl_hexdump_info(in, len); if (conn->state == LPCSPROX_WAIT_INITIAL_TX) { memset(&ssi, 0, sizeof(ssi)); ssi.user_alloc = sizeof(ss_proxy_t); ssi.handle_offset = offsetof(ss_proxy_t, ss); ssi.opaque_user_data_offset = offsetof(ss_proxy_t, conn); ssi.rx = ss_proxy_onward_rx; ssi.tx = ss_proxy_onward_tx; } ssi.state = ss_proxy_onward_state; ssi.flags = 0; n = lws_ss_deserialize_parse(&conn->parser, lws_get_context(wsi), conn->dsh, in, len, &conn->state, conn, &conn->ss, &ssi, 0); switch (n) { case LWSSSSRET_OK: break; case LWSSSSRET_DISCONNECT_ME: return -1; case LWSSSSRET_DESTROY_ME: if (conn->ss) lws_ss_destroy(&conn->ss); return -1; } if (conn->state == LPCSPROX_REPORTING_FAIL || conn->state == LPCSPROX_REPORTING_OK) lws_callback_on_writable(conn->wsi); break; case LWS_CALLBACK_RAW_WRITEABLE: // lwsl_notice("LWS_CALLBACK_RAW_PROXY_SRV_WRITEABLE\n"); /* * We can transmit something back to the client from the dsh * of stuff we received on its behalf from the ss */ if (!conn || !conn->wsi) break; n = 0; pay = 0; s[3] = 0; cp = (const uint8_t *)s; switch (conn->state) { case LPCSPROX_REPORTING_FAIL: s[3] = 1; /* fallthru */ case LPCSPROX_REPORTING_OK: s[0] = LWSSS_SER_RXPRE_CREATE_RESULT; s[1] = 0; s[2] = 1; n = 4; /* * If there's rideshare sequencing, it's added after the * first 4 bytes or the create result, comma-separated */ if (conn->ss) { rsp = conn->ss->policy; while (rsp) { if (n != 4 && n < (int)sizeof(s) - 2) s[n++] = ','; n += lws_snprintf(&s[n], sizeof(s) - n, "%s", rsp->streamtype); rsp = lws_ss_policy_lookup(wsi->a.context, rsp->rideshare_streamtype); } } s[2] = n - 3; conn->state = LPCSPROX_OPERATIONAL; lws_set_timeout(wsi, 0, 0); break; case LPCSPROX_OPERATIONAL: if (lws_dsh_get_head(conn->dsh, KIND_SS_TO_P, (void **)&p, &si)) break; cp = p; #if defined(LWS_WITH_DETAILED_LATENCY) if (cp[0] == LWSSS_SER_RXPRE_RX_PAYLOAD && wsi->a.context->detailed_latency_cb) { /* * we're fulfilling rx that came in on ss * by sending it back out to the client on * the Unix Domain Socket * * + 7 u32 write will compute latency here... * + 11 u32 ust we received from ss * * lws_write will report it and fill in * LAT_DUR_PROXY_CLIENT_REQ_TO_WRITE */ us = lws_now_usecs(); lws_ser_wu32be(&p[7], us - lws_ser_ru64be(&p[11])); lws_ser_wu64be(&p[11], us); wsi->detlat.acc_size = wsi->detlat.req_size = si - 19; /* time proxy held it */ wsi->detlat.latencies[ LAT_DUR_PROXY_RX_TO_ONWARD_TX] = lws_ser_ru32be(&p[7]); } #endif pay = 1; n = (int)si; break; default: break; } again: if (!n) break; n = lws_write(wsi, (uint8_t *)cp, n, LWS_WRITE_RAW); if (n < 0) { lwsl_info("%s: WRITEABLE: %d\n", __func__, n); goto hangup; } switch (conn->state) { case LPCSPROX_REPORTING_FAIL: goto hangup; case LPCSPROX_OPERATIONAL: if (pay) lws_dsh_free((void **)&p); if (!lws_dsh_get_head(conn->dsh, KIND_SS_TO_P, (void **)&p, &si)) { if (!lws_send_pipe_choked(wsi)) { cp = p; pay = 1; n = (int)si; goto again; } lws_callback_on_writable(wsi); } break; default: break; } break; default: break; } return lws_callback_http_dummy(wsi, reason, user, in, len); hangup: //lws_ss_destroy(&conn->ss); //conn->state = LPCSPROX_DESTROYED; /* hang up on him */ return -1; } static const struct lws_protocols protocols[] = { { "ssproxy-protocol", callback_ss_proxy, sizeof(struct raw_pss), 2048, 2048, NULL, 0 }, { NULL, NULL, 0, 0, 0, NULL, 0 } }; /* * called from create_context() */ int lws_ss_proxy_create(struct lws_context *context, const char *bind, int port) { struct lws_context_creation_info info; memset(&info, 0, sizeof(info)); info.vhost_name = "ssproxy"; info.options = LWS_SERVER_OPTION_ADOPT_APPLY_LISTEN_ACCEPT_CONFIG; info.port = port; if (!port) { if (!bind) bind = "@proxy.ss.lws"; info.options |= LWS_SERVER_OPTION_UNIX_SOCK; } info.iface = bind; info.unix_socket_perms = "root:root"; info.listen_accept_role = "raw-skt"; info.listen_accept_protocol = "ssproxy-protocol"; info.protocols = protocols; if (!lws_create_vhost(context, &info)) { lwsl_err("%s: Failed to create ss proxy vhost\n", __func__); return 1; } return 0; }
{ "pile_set_name": "Github" }
var fs = require('fs'); var path = require('path'); var common = require('./common'); var os = require('os'); //@ //@ ### ln(options, source, dest) //@ ### ln(source, dest) //@ Available options: //@ //@ + `s`: symlink //@ + `f`: force //@ //@ Examples: //@ //@ ```javascript //@ ln('file', 'newlink'); //@ ln('-sf', 'file', 'existing'); //@ ``` //@ //@ Links source to dest. Use -f to force the link, should dest already exist. function _ln(options, source, dest) { options = common.parseOptions(options, { 's': 'symlink', 'f': 'force' }); if (!source || !dest) { common.error('Missing <source> and/or <dest>'); } source = path.resolve(process.cwd(), String(source)); dest = path.resolve(process.cwd(), String(dest)); if (!fs.existsSync(source)) { common.error('Source file does not exist', true); } if (fs.existsSync(dest)) { if (!options.force) { common.error('Destination file exists', true); } fs.unlinkSync(dest); } if (options.symlink) { fs.symlinkSync(source, dest, os.platform() === "win32" ? "junction" : null); } else { fs.linkSync(source, dest, os.platform() === "win32" ? "junction" : null); } } module.exports = _ln;
{ "pile_set_name": "Github" }
// Copyright (c) 2005-2008 Fernando Luis Cacciola Carballal. All rights reserved. // // This file is part of CGAL (www.cgal.org). // You can redistribute it and/or modify it under the terms of the GNU // General Public License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL$ // $Id$ // SPDX-License-Identifier: GPL-3.0+ // // Author(s) : Fernando Cacciola <[email protected]> #ifndef CGAL_POLYGON_OFFSET_BUILDER_TRAITS_2_H #define CGAL_POLYGON_OFFSET_BUILDER_TRAITS_2_H 1 #include <CGAL/license/Straight_skeleton_2.h> #include <CGAL/Straight_skeleton_2/Straight_skeleton_aux.h> #include <CGAL/Straight_skeleton_2/Straight_skeleton_builder_traits_2_aux.h> #include <CGAL/Straight_skeleton_builder_traits_2.h> #include <CGAL/predicates/Polygon_offset_pred_ftC2.h> #include <CGAL/constructions/Polygon_offset_cons_ftC2.h> #include <CGAL/Exact_predicates_exact_constructions_kernel.h> namespace CGAL { namespace CGAL_SS_i { template<class K> struct Compare_offset_against_event_time_2 : Functor_base_2<K> { typedef Functor_base_2<K> Base ; typedef typename Base::FT FT ; typedef typename Base::Segment_2 Segment_2 ; typedef typename Base::Trisegment_2_ptr Trisegment_2_ptr ; typedef Uncertain<Comparison_result> result_type ; Uncertain<Comparison_result> operator() ( FT const& aT, Trisegment_2_ptr const& aE ) const { return compare_offset_against_isec_timeC2(aT,aE) ; } }; template<class K> struct Construct_offset_point_2 : Functor_base_2<K> { typedef Functor_base_2<K> Base ; typedef typename Base::FT FT ; typedef typename Base::Point_2 Point_2 ; typedef typename Base::Segment_2 Segment_2 ; typedef typename Base::Trisegment_2_ptr Trisegment_2_ptr ; typedef boost::optional<Point_2> result_type ; result_type operator() ( FT const& aT , Segment_2 const& aE0 , Segment_2 const& aE1 , Trisegment_2_ptr const& aNode ) const { typename Has_inexact_constructions<K>::type has_inexact_constructions CGAL_SUNPRO_INITIALIZE( = typename Has_inexact_constructions<K>::type()) ; return calc(aT, aE0, aE1, aNode, has_inexact_constructions); } result_type calc ( FT const& aT , Segment_2 const& aE0 , Segment_2 const& aE1 , Trisegment_2_ptr const& aNode , Tag_false // kernel already has exact constructions ) const { result_type p = construct_offset_pointC2(aT,aE0,aE1,aNode); CGAL_stskel_intrinsic_test_assertion(!p || (p && !is_point_calculation_clearly_wrong(aT,*p,aE0,aE1))); return p ; } result_type calc ( FT const& aT , Segment_2 const& aE0 , Segment_2 const& aE1 , Trisegment_2_ptr const& aNode , Tag_true // kernel does not provides exact constructions ) const { typedef Exact_predicates_exact_constructions_kernel EK ; typedef Cartesian_converter<K,EK> BaseC2E; typedef Cartesian_converter<EK,K> BaseE2C; SS_converter<BaseC2E> C2E ; SS_converter<BaseE2C> E2C ; result_type p = E2C(construct_offset_pointC2(C2E(aT),C2E(aE0),C2E(aE1),C2E(aNode))); CGAL_stskel_intrinsic_test_assertion(!p || (p && !is_point_calculation_clearly_wrong(aT,*p,aE0,aE1))); return p ; } bool is_point_calculation_clearly_wrong( FT const& t, Point_2 const& p, Segment_2 const& aE0, Segment_2 const& aE1 ) const { bool rR = false ; if ( is_possibly_inexact_time_clearly_not_zero(t) ) { Point_2 const& e0s = aE0.source(); Point_2 const& e0t = aE0.target(); Point_2 const& e1s = aE1.source(); Point_2 const& e1t = aE1.target(); FT const very_short(0.1); FT const very_short_squared = CGAL_NTS square(very_short); FT l0 = squared_distance(e0s,e0t) ; FT l1 = squared_distance(e1s,e1t) ; bool e0_is_not_very_short = l0 > very_short_squared ; bool e1_is_not_very_short = l1 > very_short_squared ; FT d0 = squared_distance_from_point_to_lineC2(p.x(),p.y(),e0s.x(),e0s.y(),e0t.x(),e0t.y()).to_nt(); FT d1 = squared_distance_from_point_to_lineC2(p.x(),p.y(),e1s.x(),e1s.y(),e1t.x(),e1t.y()).to_nt(); FT tt = CGAL_NTS square(t) ; bool e0_is_clearly_wrong = e0_is_not_very_short && is_possibly_inexact_distance_clearly_not_equal_to(d0,tt) ; bool e1_is_clearly_wrong = e1_is_not_very_short && is_possibly_inexact_distance_clearly_not_equal_to(d1,tt) ; rR = e0_is_clearly_wrong || e1_is_clearly_wrong ; CGAL_stskel_intrinsic_test_trace_if(rR , "\nOffset point calculation is clearly wrong:" << "\ntime=" << t << " p=" << p2str(p) << " e0=" << s2str(aE0) << " e1=" << s2str(aE1) << "\nl0=" << inexact_sqrt(l0) << " l1=" << inexact_sqrt(l1) << "\nd0=" << d0 << " d1=" << d1 << " tt=" << tt ) ; } return rR ; } }; } // namespace CGAL_SS_i template<class K> struct Polygon_offset_builder_traits_2_functors { typedef CGAL_SS_i::Compare_offset_against_event_time_2<K> Compare_offset_against_event_time_2 ; typedef CGAL_SS_i::Compare_ss_event_times_2 <K> Compare_ss_event_times_2 ; typedef CGAL_SS_i::Construct_offset_point_2 <K> Construct_offset_point_2 ; typedef CGAL_SS_i::Construct_ss_trisegment_2 <K> Construct_ss_trisegment_2 ; typedef CGAL_SS_i::Construct_ss_event_time_and_point_2<K> Construct_ss_event_time_and_point_2 ; } ; template<class K> struct Polygon_offset_builder_traits_2_base { typedef K Kernel ; typedef typename K::FT FT ; typedef typename K::Point_2 Point_2 ; typedef typename K::Segment_2 Segment_2 ; typedef CGAL_SS_i::Trisegment_2<K> Trisegment_2 ; typedef typename Trisegment_2::Self_ptr Trisegment_2_ptr ; template<class F> F get( F const* = 0 ) const { return F(); } } ; template<class Is_filtered_kernel, class K> class Polygon_offset_builder_traits_2_impl ; template<class K> class Polygon_offset_builder_traits_2_impl<Tag_false,K> : public Polygon_offset_builder_traits_2_base<K> { typedef Polygon_offset_builder_traits_2_functors<K> Unfiltering ; public: typedef Unfiltered_predicate_adaptor<typename Unfiltering::Compare_offset_against_event_time_2> Compare_offset_against_event_time_2 ; typedef Unfiltered_predicate_adaptor<typename Unfiltering::Compare_ss_event_times_2> Compare_ss_event_times_2 ; typedef typename Unfiltering::Construct_offset_point_2 Construct_offset_point_2 ; typedef typename Unfiltering::Construct_ss_trisegment_2 Construct_ss_trisegment_2 ; typedef typename Unfiltering::Construct_ss_event_time_and_point_2 Construct_ss_event_time_and_point_2 ; } ; template<class K> class Polygon_offset_builder_traits_2_impl<Tag_true,K> : public Polygon_offset_builder_traits_2_base<K> { typedef typename K::Exact_kernel EK ; typedef typename K::Approximate_kernel FK ; typedef Polygon_offset_builder_traits_2_functors<EK> Exact ; typedef Polygon_offset_builder_traits_2_functors<FK> Filtering ; typedef Polygon_offset_builder_traits_2_functors<K> Unfiltering ; typedef Cartesian_converter<K,EK> BaseC2E; typedef Cartesian_converter<K,FK> BaseC2F; typedef Cartesian_converter<EK,K> BaseE2C; typedef Cartesian_converter<FK,K> BaseF2C; typedef Cartesian_converter<K,K> BaseC2C; typedef CGAL_SS_i::SS_converter<BaseC2E> C2E ; typedef CGAL_SS_i::SS_converter<BaseC2F> C2F ; typedef CGAL_SS_i::SS_converter<BaseE2C> E2C ; typedef CGAL_SS_i::SS_converter<BaseF2C> F2C ; typedef CGAL_SS_i::SS_converter<BaseC2C> C2C ; public: typedef Filtered_predicate<typename Exact ::Compare_offset_against_event_time_2 ,typename Filtering::Compare_offset_against_event_time_2 , C2E , C2F > Compare_offset_against_event_time_2 ; typedef Filtered_predicate< typename Exact ::Compare_ss_event_times_2 , typename Filtering::Compare_ss_event_times_2 , C2E , C2F > Compare_ss_event_times_2 ; typedef CGAL_SS_i::Exceptionless_filtered_construction< typename Unfiltering::Construct_offset_point_2 , typename Exact ::Construct_offset_point_2 , typename Unfiltering::Construct_offset_point_2 , C2E , C2C , E2C , C2C > Construct_offset_point_2 ; typedef CGAL_SS_i::Exceptionless_filtered_construction< typename Unfiltering::Construct_ss_trisegment_2 , typename Exact ::Construct_ss_trisegment_2 , typename Unfiltering::Construct_ss_trisegment_2 , C2E , C2C , E2C , C2C > Construct_ss_trisegment_2 ; typedef CGAL_SS_i::Exceptionless_filtered_construction< typename Unfiltering::Construct_ss_event_time_and_point_2 , typename Exact ::Construct_ss_event_time_and_point_2 , typename Unfiltering::Construct_ss_event_time_and_point_2 , C2E , C2C , E2C , C2C > Construct_ss_event_time_and_point_2 ; } ; template<class K> class Polygon_offset_builder_traits_2 : public Polygon_offset_builder_traits_2_impl<typename CGAL_SS_i::Is_filtering_kernel<K>::type,K> { } ; CGAL_STRAIGHT_SKELETON_CREATE_FUNCTOR_ADAPTER(Compare_offset_against_event_time_2) CGAL_STRAIGHT_SKELETON_CREATE_FUNCTOR_ADAPTER(Construct_offset_point_2) } // end namespace CGAL #endif // CGAL_POLYGON_OFFSET_BUILDER_TRAITS_2_H // // EOF //
{ "pile_set_name": "Github" }
package swarm // import "github.com/docker/docker/api/types/swarm" // RuntimeType is the type of runtime used for the TaskSpec type RuntimeType string // RuntimeURL is the proto type url type RuntimeURL string const ( // RuntimeContainer is the container based runtime RuntimeContainer RuntimeType = "container" // RuntimePlugin is the plugin based runtime RuntimePlugin RuntimeType = "plugin" // RuntimeNetworkAttachment is the network attachment runtime RuntimeNetworkAttachment RuntimeType = "attachment" // RuntimeURLContainer is the proto url for the container type RuntimeURLContainer RuntimeURL = "types.docker.com/RuntimeContainer" // RuntimeURLPlugin is the proto url for the plugin type RuntimeURLPlugin RuntimeURL = "types.docker.com/RuntimePlugin" ) // NetworkAttachmentSpec represents the runtime spec type for network // attachment tasks type NetworkAttachmentSpec struct { ContainerID string }
{ "pile_set_name": "Github" }
// Protocol messages for describing features for machine learning model // training or inference. // // There are three base Feature types: // - bytes // - float // - int64 // // A Feature contains Lists which may hold zero or more values. These // lists are the base values BytesList, FloatList, Int64List. // // Features are organized into categories by name. The Features message // contains the mapping from name to Feature. // // Example Features for a movie recommendation application: // feature { // key: "age" // value { float_list { // value: 29.0 // }} // } // feature { // key: "movie" // value { bytes_list { // value: "The Shawshank Redemption" // value: "Fight Club" // }} // } // feature { // key: "movie_ratings" // value { float_list { // value: 9.0 // value: 9.7 // }} // } // feature { // key: "suggestion" // value { bytes_list { // value: "Inception" // }} // } // feature { // key: "suggestion_purchased" // value { int64_list { // value: 1 // }} // } // feature { // key: "purchase_price" // value { float_list { // value: 9.99 // }} // } // syntax = "proto3"; option cc_enable_arenas = true; option java_outer_classname = "FeatureProtos"; option java_multiple_files = true; option java_package = "org.tensorflow.example"; package tensorflow; // Containers to hold repeated fundamental values. message BytesList { repeated bytes value = 1; } message FloatList { repeated float value = 1 [packed = true]; } message Int64List { repeated int64 value = 1 [packed = true]; } // Containers for non-sequential data. message Feature { // Each feature can be exactly one kind. oneof kind { BytesList bytes_list = 1; FloatList float_list = 2; Int64List int64_list = 3; } }; message Features { // Map from feature name to feature. map<string, Feature> feature = 1; }; // Containers for sequential data. // // A FeatureList contains lists of Features. These may hold zero or more // Feature values. // // FeatureLists are organized into categories by name. The FeatureLists message // contains the mapping from name to FeatureList. // message FeatureList { repeated Feature feature = 1; }; message FeatureLists { // Map from feature name to feature list. map<string, FeatureList> feature_list = 1; };
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- # Spearmint # # Academic and Non-Commercial Research Use Software License and Terms # of Use # # Spearmint is a software package to perform Bayesian optimization # according to specific algorithms (the “Software”). The Software is # designed to automatically run experiments (thus the code name # 'spearmint') in a manner that iteratively adjusts a number of # parameters so as to minimize some objective in as few runs as # possible. # # The Software was developed by Ryan P. Adams, Michael Gelbart, and # Jasper Snoek at Harvard University, Kevin Swersky at the # University of Toronto (“Toronto”), and Hugo Larochelle at the # Université de Sherbrooke (“Sherbrooke”), which assigned its rights # in the Software to Socpra Sciences et Génie # S.E.C. (“Socpra”). Pursuant to an inter-institutional agreement # between the parties, it is distributed for free academic and # non-commercial research use by the President and Fellows of Harvard # College (“Harvard”). # # Using the Software indicates your agreement to be bound by the terms # of this Software Use Agreement (“Agreement”). Absent your agreement # to the terms below, you (the “End User”) have no rights to hold or # use the Software whatsoever. # # Harvard agrees to grant hereunder the limited non-exclusive license # to End User for the use of the Software in the performance of End # User’s internal, non-commercial research and academic use at End # User’s academic or not-for-profit research institution # (“Institution”) on the following terms and conditions: # # 1. NO REDISTRIBUTION. The Software remains the property Harvard, # Toronto and Socpra, and except as set forth in Section 4, End User # shall not publish, distribute, or otherwise transfer or make # available the Software to any other party. # # 2. NO COMMERCIAL USE. End User shall not use the Software for # commercial purposes and any such use of the Software is expressly # prohibited. This includes, but is not limited to, use of the # Software in fee-for-service arrangements, core facilities or # laboratories or to provide research services to (or in collaboration # with) third parties for a fee, and in industry-sponsored # collaborative research projects where any commercial rights are # granted to the sponsor. If End User wishes to use the Software for # commercial purposes or for any other restricted purpose, End User # must execute a separate license agreement with Harvard. # # Requests for use of the Software for commercial purposes, please # contact: # # Office of Technology Development # Harvard University # Smith Campus Center, Suite 727E # 1350 Massachusetts Avenue # Cambridge, MA 02138 USA # Telephone: (617) 495-3067 # Facsimile: (617) 495-9568 # E-mail: [email protected] # # 3. OWNERSHIP AND COPYRIGHT NOTICE. Harvard, Toronto and Socpra own # all intellectual property in the Software. End User shall gain no # ownership to the Software. End User shall not remove or delete and # shall retain in the Software, in any modifications to Software and # in any Derivative Works, the copyright, trademark, or other notices # pertaining to Software as provided with the Software. # # 4. DERIVATIVE WORKS. End User may create and use Derivative Works, # as such term is defined under U.S. copyright laws, provided that any # such Derivative Works shall be restricted to non-commercial, # internal research and academic use at End User’s Institution. End # User may distribute Derivative Works to other Institutions solely # for the performance of non-commercial, internal research and # academic use on terms substantially similar to this License and # Terms of Use. # # 5. FEEDBACK. In order to improve the Software, comments from End # Users may be useful. End User agrees to provide Harvard with # feedback on the End User’s use of the Software (e.g., any bugs in # the Software, the user experience, etc.). Harvard is permitted to # use such information provided by End User in making changes and # improvements to the Software without compensation or an accounting # to End User. # # 6. NON ASSERT. End User acknowledges that Harvard, Toronto and/or # Sherbrooke or Socpra may develop modifications to the Software that # may be based on the feedback provided by End User under Section 5 # above. Harvard, Toronto and Sherbrooke/Socpra shall not be # restricted in any way by End User regarding their use of such # information. End User acknowledges the right of Harvard, Toronto # and Sherbrooke/Socpra to prepare, publish, display, reproduce, # transmit and or use modifications to the Software that may be # substantially similar or functionally equivalent to End User’s # modifications and/or improvements if any. In the event that End # User obtains patent protection for any modification or improvement # to Software, End User agrees not to allege or enjoin infringement of # End User’s patent against Harvard, Toronto or Sherbrooke or Socpra, # or any of the researchers, medical or research staff, officers, # directors and employees of those institutions. # # 7. PUBLICATION & ATTRIBUTION. End User has the right to publish, # present, or share results from the use of the Software. In # accordance with customary academic practice, End User will # acknowledge Harvard, Toronto and Sherbrooke/Socpra as the providers # of the Software and may cite the relevant reference(s) from the # following list of publications: # # Practical Bayesian Optimization of Machine Learning Algorithms # Jasper Snoek, Hugo Larochelle and Ryan Prescott Adams # Neural Information Processing Systems, 2012 # # Multi-Task Bayesian Optimization # Kevin Swersky, Jasper Snoek and Ryan Prescott Adams # Advances in Neural Information Processing Systems, 2013 # # Input Warping for Bayesian Optimization of Non-stationary Functions # Jasper Snoek, Kevin Swersky, Richard Zemel and Ryan Prescott Adams # Preprint, arXiv:1402.0929, http://arxiv.org/abs/1402.0929, 2013 # # Bayesian Optimization and Semiparametric Models with Applications to # Assistive Technology Jasper Snoek, PhD Thesis, University of # Toronto, 2013 # # 8. NO WARRANTIES. THE SOFTWARE IS PROVIDED "AS IS." TO THE FULLEST # EXTENT PERMITTED BY LAW, HARVARD, TORONTO AND SHERBROOKE AND SOCPRA # HEREBY DISCLAIM ALL WARRANTIES OF ANY KIND (EXPRESS, IMPLIED OR # OTHERWISE) REGARDING THE SOFTWARE, INCLUDING BUT NOT LIMITED TO ANY # IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR # PURPOSE, OWNERSHIP, AND NON-INFRINGEMENT. HARVARD, TORONTO AND # SHERBROOKE AND SOCPRA MAKE NO WARRANTY ABOUT THE ACCURACY, # RELIABILITY, COMPLETENESS, TIMELINESS, SUFFICIENCY OR QUALITY OF THE # SOFTWARE. HARVARD, TORONTO AND SHERBROOKE AND SOCPRA DO NOT WARRANT # THAT THE SOFTWARE WILL OPERATE WITHOUT ERROR OR INTERRUPTION. # # 9. LIMITATIONS OF LIABILITY AND REMEDIES. USE OF THE SOFTWARE IS AT # END USER’S OWN RISK. IF END USER IS DISSATISFIED WITH THE SOFTWARE, # ITS EXCLUSIVE REMEDY IS TO STOP USING IT. IN NO EVENT SHALL # HARVARD, TORONTO OR SHERBROOKE OR SOCPRA BE LIABLE TO END USER OR # ITS INSTITUTION, IN CONTRACT, TORT OR OTHERWISE, FOR ANY DIRECT, # INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR OTHER # DAMAGES OF ANY KIND WHATSOEVER ARISING OUT OF OR IN CONNECTION WITH # THE SOFTWARE, EVEN IF HARVARD, TORONTO OR SHERBROOKE OR SOCPRA IS # NEGLIGENT OR OTHERWISE AT FAULT, AND REGARDLESS OF WHETHER HARVARD, # TORONTO OR SHERBROOKE OR SOCPRA IS ADVISED OF THE POSSIBILITY OF # SUCH DAMAGES. # # 10. INDEMNIFICATION. To the extent permitted by law, End User shall # indemnify, defend and hold harmless Harvard, Toronto and Sherbrooke # and Socpra, their corporate affiliates, current or future directors, # trustees, officers, faculty, medical and professional staff, # employees, students and agents and their respective successors, # heirs and assigns (the "Indemnitees"), against any liability, # damage, loss or expense (including reasonable attorney's fees and # expenses of litigation) incurred by or imposed upon the Indemnitees # or any one of them in connection with any claims, suits, actions, # demands or judgments arising from End User’s breach of this # Agreement or its Institution’s use of the Software except to the # extent caused by the gross negligence or willful misconduct of # Harvard, Toronto or Sherbrooke or Socpra. This indemnification # provision shall survive expiration or termination of this Agreement. # # 11. GOVERNING LAW. This Agreement shall be construed and governed by # the laws of the Commonwealth of Massachusetts regardless of # otherwise applicable choice of law standards. # # 12. NON-USE OF NAME. Nothing in this License and Terms of Use shall # be construed as granting End Users or their Institutions any rights # or licenses to use any trademarks, service marks or logos associated # with the Software. You may not use the terms “Harvard” or # “University of Toronto” or “Université de Sherbrooke” or “Socpra # Sciences et Génie S.E.C.” (or a substantially similar term) in any # way that is inconsistent with the permitted uses described # herein. You agree not to use any name or emblem of Harvard, Toronto # or Sherbrooke, or any of their subdivisions for any purpose, or to # falsely suggest any relationship between End User (or its # Institution) and Harvard, Toronto and/or Sherbrooke, or in any # manner that would infringe or violate any of their rights. # # 13. End User represents and warrants that it has the legal authority # to enter into this License and Terms of Use on behalf of itself and # its Institution. import numpy as np import numpy.random as npr def elliptical_slice(xx, chol_Sigma, log_like_fn, *log_like_fn_args): D = xx.size # Select a random ellipse. nu = np.dot(chol_Sigma, npr.randn(D)) # Select the slice threshold. hh = np.log(npr.rand()) + log_like_fn(xx, *log_like_fn_args) # Randomly center the bracket. phi = npr.rand()*2*np.pi phi_max = phi phi_min = phi_max - 2*np.pi # Loop until acceptance. while True: # Compute the proposal. xx_prop = xx*np.cos(phi) + nu*np.sin(phi) # If on the slice, return the proposal. if log_like_fn(xx_prop, *log_like_fn_args) > hh: return xx_prop if phi > 0: phi_max = phi elif phi < 0: phi_min = phi else: raise Exception("Shrank to zero!") phi = npr.rand()*(phi_max - phi_min) + phi_min def uni_slice_sample(init_x, logprob, lower, upper, *logprob_args): llh_s = np.log(npr.rand()) + logprob(init_x, *logprob_args) while True: new_x = npr.rand()*(upper-lower) + lower new_llh = logprob(new_x, *logprob_args) if new_llh > llh_s: return new_x elif new_x < init_x: lower = new_x elif new_x > init_x: upper = new_x else: raise Exception("Slice sampler shrank to zero!") def slice_sample(init_x, logprob, *logprob_args, **slice_sample_args): """generate a new sample from a probability density using slice sampling Parameters ---------- init_x : array logprob : callable, `lprob = logprob(x, *logprob_args)` A functions which returns the log probability at a given location *logprob_args : additional arguments are passed to logprob TODO: this function has too many levels and is hard to read. It would be clearer as a class or just moving the sub-functions to another location Returns ------- new_x : float the sampled position new_llh : float the log likelihood at the new position (I'm not sure about this?) Notes ----- http://en.wikipedia.org/wiki/Slice_sampling """ sigma = slice_sample_args.get('sigma', 1.0) step_out = slice_sample_args.get('step_out', True) max_steps_out = slice_sample_args.get('max_steps_out', 1000) compwise = slice_sample_args.get('compwise', True) doubling_step = slice_sample_args.get('doubling_step', True) verbose = slice_sample_args.get('verbose', False) def direction_slice(direction, init_x): def dir_logprob(z): return logprob(direction*z + init_x, *logprob_args) def acceptable(z, llh_s, L, U): while (U-L) > 1.1*sigma: middle = 0.5*(L+U) splits = (middle > 0 and z >= middle) or (middle <= 0 and z < middle) if z < middle: U = middle else: L = middle # Probably these could be cached from the stepping out. if splits and llh_s >= dir_logprob(U) and llh_s >= dir_logprob(L): return False return True upper = sigma*npr.rand() lower = upper - sigma llh_s = np.log(npr.rand()) + dir_logprob(0.0) l_steps_out = 0 u_steps_out = 0 if step_out: if doubling_step: while (dir_logprob(lower) > llh_s or dir_logprob(upper) > llh_s) and (l_steps_out + u_steps_out) < max_steps_out: if npr.rand() < 0.5: l_steps_out += 1 lower -= (upper-lower) else: u_steps_out += 1 upper += (upper-lower) else: while dir_logprob(lower) > llh_s and l_steps_out < max_steps_out: l_steps_out += 1 lower -= sigma while dir_logprob(upper) > llh_s and u_steps_out < max_steps_out: u_steps_out += 1 upper += sigma start_upper = upper start_lower = lower steps_in = 0 while True: steps_in += 1 new_z = (upper - lower)*npr.rand() + lower new_llh = dir_logprob(new_z) if np.isnan(new_llh): print new_z, direction*new_z + init_x, new_llh, llh_s, init_x, logprob(init_x, *logprob_args) raise Exception("Slice sampler got a NaN") if new_llh > llh_s and acceptable(new_z, llh_s, start_lower, start_upper): break elif new_z < 0: lower = new_z elif new_z > 0: upper = new_z else: raise Exception("Slice sampler shrank to zero!") if verbose: print "Steps Out:", l_steps_out, u_steps_out, " Steps In:", steps_in return new_z*direction + init_x, new_llh if type(init_x) == float or isinstance(init_x, np.number): init_x = np.array([init_x]) scalar = True else: scalar = False dims = init_x.shape[0] if compwise: ordering = range(dims) npr.shuffle(ordering) new_x = init_x.copy() for d in ordering: direction = np.zeros((dims)) direction[d] = 1.0 new_x, new_llh = direction_slice(direction, new_x) else: direction = npr.randn(dims) direction = direction / np.sqrt(np.sum(direction**2)) new_x, new_llh = direction_slice(direction, init_x) if scalar: return float(new_x[0]), new_llh else: return new_x, new_llh def slice_sample_simple(init_x, logprob, *logprob_args, **slice_sample_args): sigma = slice_sample_args.get('sigma', 1.0) step_out = slice_sample_args.get('step_out', True) max_steps_out = slice_sample_args.get('max_steps_out', 1000) compwise = slice_sample_args.get('compwise', True) verbose = slice_sample_args.get('verbose', False) # Keep track of the number of evaluations of the logprob function # funEvals = {'funevals': 0} # sorry, i don't know how to actually do this properly with all these nested function. pls forgive me -MG -- from collections imoprt Counter ? # this is a 1-d sampling subrountine that only samples along the direction "direction" def direction_slice(direction, init_x): def dir_logprob(z): # logprob of the proposed point (x + dir*z) where z must be the step size # funEvals['funevals'] += 1 try: return logprob(direction*z + init_x, *logprob_args) except: print 'ERROR: Logprob failed at input %s' % str(direction*z + init_x) raise # upper and lower are step sizes -- everything is measured relative to init_x upper = sigma*npr.rand() # random thing above 0 lower = upper - sigma # random thing below 0 llh_s = np.log(npr.rand()) + dir_logprob(0.0) # = log(prob_current * rand) # (above) uniformly sample vertically at init_x l_steps_out = 0 u_steps_out = 0 if step_out: # increase upper and decrease lower until they overshoot the curve while dir_logprob(lower) > llh_s and l_steps_out < max_steps_out: l_steps_out += 1 lower -= sigma # make lower smaller by sigma while dir_logprob(upper) > llh_s and u_steps_out < max_steps_out: u_steps_out += 1 upper += sigma # rejection sample along the horizontal line (because we don't know the bounds exactly) steps_in = 0 while True: steps_in += 1 new_z = (upper - lower)*npr.rand() + lower # uniformly sample between upper and lower new_llh = dir_logprob(new_z) # new current logprob if np.isnan(new_llh): print new_z, direction*new_z + init_x, new_llh, llh_s, init_x, logprob(init_x) raise Exception("Slice sampler got a NaN logprob") if new_llh > llh_s: # this is the termination condition break # it says, if you got to a better place than you started, you're done # the below is only if you've overshot, meaning your uniform sample from the horizontal # slice ended up outside the curve because the bounds lower and upper were not tight elif new_z < 0: # new_z is to the left of init_x lower = new_z # shrink lower to it elif new_z > 0: upper = new_z else: # upper and lower are both 0... raise Exception("Slice sampler shrank to zero!") if verbose: print "Steps Out:", l_steps_out, u_steps_out, " Steps In:", steps_in, "Final logprob:", new_llh # return new the point return new_z*direction + init_x, new_llh # begin main # # This causes an extra "logprob" function call -- might want to turn off for speed initial_llh = logprob(init_x, *logprob_args) if verbose: sys.stderr.write('Logprob before sampling: %f\n' % initial_llh) if np.isneginf(initial_llh): sys.stderr.write('Values passed into slice sampler: %s\n' % init_x) raise Exception("Initial value passed into slice sampler has logprob = -inf") if not init_x.shape: # if there is just one dimension, stick it in a numpy array init_x = np.array([init_x]) dims = init_x.shape[0] if compwise: # if component-wise (independent) sampling ordering = range(dims) npr.shuffle(ordering) cur_x = init_x.copy() for d in ordering: direction = np.zeros((dims)) direction[d] = 1.0 cur_x, cur_llh = direction_slice(direction, cur_x) else: # if not component-wise sampling direction = npr.randn(dims) direction = direction / np.sqrt(np.sum(direction**2)) # pick a unit vector in a random direction cur_x, cur_llh = direction_slice(direction, init_x) # attempt to sample in that direction return cur_x, cur_llh # return (cur_x, funEvals['funevals']) if returnFunEvals else cur_x if __name__ == '__main__': npr.seed(1) import pylab as pl import pymc D = 10 fn = lambda x: -0.5*np.sum(x**2) iters = 1000 samps = np.zeros((iters,D)) for ii in xrange(1,iters): samps[ii,:] = slice_sample(samps[ii-1,:], fn, sigma=0.1, step_out=False, doubling_step=True, verbose=False) ll = -0.5*np.sum(samps**2, axis=1) scores = pymc.geweke(ll) pymc.Matplot.geweke_plot(scores, 'test') pymc.raftery_lewis(ll, q=0.025, r=0.01) pymc.Matplot.autocorrelation(ll, 'test')
{ "pile_set_name": "Github" }
define(['UIAbstractView', 'text!T_UISelect', 'UIScroll'], function (UIAbstractView, template, UIScroll) { /* 该组件使用时,其父容器一定是显示状态,如果不是显示状态,高度计算会失效 */ return _.inherit(UIAbstractView, { propertys: function ($super) { $super(); //html模板 this.template = template; //默认datamodel this.curClass = 'active'; this.data = []; this.key = null; this.index = 0; this.animatTime = 100; this.stepTime = 150; this.itemNum = this.data.length; //这里便只有一个接口了 this.displayNum = 5; //选择时候的偏移量 this.scrollOffset = 0; //滚动对象 this.scroll = null; this.changed = function (item) { console.log(item); }; }, getViewModel: function () { return this._getDefaultViewModel(['curClass', 'data', 'key', 'index']); }, //要求唯一标识,根据id确定index resetPropery: function () { this._resetNum(); this._resetIndex(); }, _resetIndex: function () { if (!this.key) return; for (var i = 0, len = this.data.length; i < len; i++) { if (this.key === this.data[i].id) { this.index = i; break; } } }, _resetNum: function () { this.displayNum = this.displayNum % 2 == 0 ? this.displayNum + 1 : this.displayNum; this.itemNum = this.data.length; }, initElement: function () { //几个容器的高度必须统一 this.swrapper = this.$('.js_wrapper'); this.scroller = this.$('.js_scroller'); }, initSize: function () { //偶尔不能正确获取高度,这里要处理 // if (this.itemHeight == 0) { this.itemHeight = parseInt(window.getComputedStyle && getComputedStyle(this.scroller.find('li').eq(0)[0]).height); this.scroller.height(this.itemHeight * this.itemNum); // } this.swrapper.height(this.itemHeight * this.displayNum); this.scrollOffset = ((this.displayNum - 1) / 2) * (this.itemHeight); }, //修正位置信息 adjustPosition: function (hasAnimate) { if (!this.scroll) return; if (this.index < 0) this.index = 0 if (this.index > this.itemNum - 1) this.index = this.itemNum - 1; var index = this.index, _top, time = 0; //index数据验证 _top = (this.itemHeight * index) * (-1) + this.scrollOffset; if (hasAnimate) time = this.animatTime; this.scroll.scrollTo(0, _top, time); }, _initScroll: function () { if (this.scroll) { this.scroll.refresh(); return; } this.scroll = new UIScroll({ scrollbars: false, scrollOffset: this.scrollOffset, step: this.itemHeight, wrapper: this.swrapper, bounceTime: 200, scroller: this.scroller }); this.scroll.on('scrollEnd', $.proxy(function () { this.setIndex(this.getIndexByPosition(), true) }, this)); //为了解决鼠标离屏幕时导致的问题 this.scroll.on('scrollCancel', $.proxy(function () { this.setIndex(this.getIndexByPosition(), false) }, this)); }, reload: function (data) { if (data) this.setOption(data); if (this.scroll) { this.scroll.destroy(); this.scroll = null; } //执行reload的话,数据源便发生了变化 this._dataChanged = true; this.refresh(); }, //检测当前选项是否可选,首次不予关注 checkDisable: function (dir) { dir = dir || 'down'; //默认向下搜索 var isFind = false, index = this.index; if (this.data[index] && (typeof this.data[index].disabled != 'undefined' && this.data[index].disabled == false)) { //向下的情况 if (dir == 'up') { this.index = this._checkSelectedDown(index); if (typeof this.index != 'number') this.index = this._checkSelectedUp(index); } else { this.index = this._checkSelectedUp(index); if (typeof this.index != 'number') this.index = this._checkSelectedDown(index); } } if (typeof this.index != 'number') this.index = index; }, /** * @class _checkSelectedUp * @param index {int} 索引 * @description 向上搜索 */ _checkSelectedUp: function (index) { var isFind = false; for (var i = index; i != -1; i--) { if (this.data[i] && (typeof this.data[i].disabled == 'undefined' || this.data[i].disabled == true)) { index = i; isFind = true; break; } } return isFind ? index : null; }, /** * @class _checkSelectedDown * @param index {int} 索引 * @description 向下搜索 */ _checkSelectedDown: function (index) { var isFind = false; for (var i = index, len = this.data.length; i < len; i++) { if (this.data[i] && (typeof this.data[i].disabled == 'undefined' || this.data[i].disabled == true)) { index = i; isFind = true; break; } } return isFind ? index : null }, //这里要处理不可选的状况 /* 这段逻辑比较复杂,处理的逻辑较多 1 每次赋值时候判断是否改变,改变需要触发changed事件 2 每次赋值还得判断当前选项是否是disabled的,如果是disabled的话还得重置index 3 以上逻辑会加重changed触发事件以及重新设置index的复杂度 */ setIndex: function (i, noPosition, noEvent) { if (typeof noPosition == 'undefined' && i == this.index) noPosition = true; var tmpIndex = i; var tmpIndex2; //index值是否改变 var isChange = this.index != i; var dir = i > this.index ? 'up' : 'down'; i = parseInt(i); if (i < 0 || i >= this.itemNum) return; tmpIndex2 = this.index; this.index = i; this.checkDisable(dir); //被改变过了 if (tmpIndex2 != this.index) { isChange = true; } else { isChange = false; } if (tmpIndex != this.index) { noPosition = false; } if (!noPosition) this.adjustPosition(true); this.resetCss(); //如果数据源发生变化一定会执行changed事件,否则一定会判断原有逻辑 if (this._dataChanged) { this.triggerChangedAction(); this._dataChanged = false; } else { if (noEvent !== true && isChange) this.triggerChangedAction(); } }, //触发change事件 triggerChangedAction: function () { this.changed && this.changed.call(this, this.getSelected()); }, resetCss: function () { this.$('li').removeClass('active'); this.$('li[data-index="' + this.index + '"]').addClass('active'); }, resetIndex: function () { this.setIndex(this.index, true, true); }, getIndex: function () { return this.index; }, setId: function (id) { if (!id) return; var index = -1, i, len; for (i = 0, len = this.data.length; i < len; i++) { if (this.data[i].id == id) { index = i; break; } } if (index == -1) return; this.index = index; this.setIndex(index, false); }, getId: function () { return this.getSelected().id; }, getSelected: function () { return this.data[this.index]; }, //根据位置信息重新设置当前选项 getIndexByPosition: function () { var pos = this.scroll.y - this.scrollOffset; var index = Math.abs(pos) / this.itemHeight; return Math.round(index); }, addEvent: function ($super) { $super(); //这个要在第一位,因为后面会执行父类的position方法居中,尺寸没有就不行 this.on('onShow', function () { this.initSize(); this._initScroll(); this.adjustPosition(); this.resetCss(); //防止初始化定义index为不可选index this.resetIndex(); }, 1); this.on('onHide', function () { if (this.scroll) { this.scroll.destroy(); this.scroll = null; } }); } }); });
{ "pile_set_name": "Github" }
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Windows.Forms; namespace ICSharpCode.SharpDevelop.Project { public interface IProjectNodeBuilder { bool CanBuildProjectTree(IProject project); TreeNode AddProjectNode(TreeNode motherNode, IProject project); } }
{ "pile_set_name": "Github" }
builder > A.scala B.scala compiling Set(A.scala, B.scala) Changes: Map() builder > A.scala compiling Set(A.scala) Changes: Map(trait A -> List(Changed(Definition(A.S))[type S changed from A.this.S[_] to A.this.S flags: <deferred>])) invalidate B.scala because inherited method changed [Changed(Definition(A.S))[type S changed from A.this.S[_] to A.this.S flags: <deferred>]] compiling Set(B.scala) B.scala:2: error: B.this.S does not take type parameters type F = S[Int] ^
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <window> <defaultcontrol>100</defaultcontrol> <coordinates> <system>1</system> <posx>0</posx> <posy>0</posy> </coordinates> <backgroundcolor>0xff111111</backgroundcolor> <controls> <control type="group"> <control type="group" id="100"> <!-- <visible>Integer.IsGreater(Container(101).NumItems,0) + String.IsEmpty(Window.Property(drawing))</visible> --> <defaultcontrol>101</defaultcontrol> <posx>750</posx> <posy>140</posy> <width>1170</width> <height>800</height> <control type="image"> <posx>0</posx> <posy>0</posy> <width>1170</width> <height>800</height> <texture>script.plex/white-square.png</texture> <colordiffuse>B3111111</colordiffuse> </control> <control type="list" id="101"> <posx>0</posx> <posy>0</posy> <width>1170</width> <height>800</height> <onup>200</onup> <onright>152</onright> <onleft>300</onleft> <scrolltime>200</scrolltime> <orientation>vertical</orientation> <preloaditems>4</preloaditems> <pagecontrol>152</pagecontrol> <!-- ITEM LAYOUT ########################################## --> <itemlayout height="101"> <control type="group"> <posx>120</posx> <posy>24</posy> <control type="label"> <visible>String.IsEmpty(ListItem.Property(playing))</visible> <posx>-10</posx> <posy>0</posy> <width>60</width> <height>100</height> <font>font10</font> <align>center</align> <aligny>center</aligny> <textcolor>D8FFFFFF</textcolor> <label>[B]$INFO[ListItem.Property(track.number)][/B]</label> </control> <control type="image"> <visible>!String.IsEmpty(ListItem.Property(playing))</visible> <posx>2</posx> <posy>32.5</posy> <width>35</width> <height>35</height> <texture>script.plex/indicators/playing-circle.png</texture> <colordiffuse>FFE5A00D</colordiffuse> </control> <control type="group"> <visible>String.IsEmpty(ListItem.Property(video))</visible> <control type="image"> <posx>63</posx> <posy>11</posy> <width>74</width> <height>74</height> <texture>$INFO[ListItem.Thumb]</texture> <aspectratio>scale</aspectratio> </control> <control type="group"> <posx>168</posx> <posy>0</posy> <control type="label"> <posx>0</posx> <posy>15</posy> <width>692</width> <height>30</height> <font>font10</font> <align>left</align> <aligny>center</aligny> <textcolor>FFFFFFFF</textcolor> <label>[B]$INFO[ListItem.Label][/B]</label> </control> <control type="label"> <posx>0</posx> <posy>50</posy> <width>692</width> <height>30</height> <font>font10</font> <align>left</align> <aligny>center</aligny> <textcolor>B8FFFFFF</textcolor> <label>$INFO[ListItem.Label2]</label> </control> </control> </control> <control type="group"> <visible>!String.IsEmpty(ListItem.Property(video))</visible> <control type="image"> <posx>63</posx> <posy>11</posy> <width>132</width> <height>74</height> <texture>$INFO[ListItem.Thumb]</texture> <aspectratio>scale</aspectratio> </control> <control type="image"> <visible>String.IsEmpty(ListItem.Property(watched))</visible> <posx>895</posx> <posy>-1</posy> <width>35</width> <height>35</height> <texture>script.plex/indicators/unwatched.png</texture> </control> <control type="group"> <posx>226</posx> <posy>0</posy> <control type="label"> <posx>0</posx> <posy>15</posy> <width>584</width> <height>30</height> <font>font10</font> <align>left</align> <aligny>center</aligny> <textcolor>FFFFFFFF</textcolor> <label>[B]$INFO[ListItem.Label][/B]</label> </control> <control type="label"> <posx>0</posx> <posy>50</posy> <width>584</width> <height>30</height> <font>font10</font> <align>left</align> <aligny>center</aligny> <textcolor>B8FFFFFF</textcolor> <label>$INFO[ListItem.Label2]</label> </control> </control> </control> <control type="label"> <posx>730</posx> <posy>0</posy> <width>200</width> <height>100</height> <font>font10</font> <align>right</align> <aligny>center</aligny> <textcolor>D8FFFFFF</textcolor> <label>[B]$INFO[ListItem.Property(track.duration)][/B]</label> </control> <control type="image"> <visible>String.IsEmpty(ListItem.Property(is.footer))</visible> <posx>0</posx> <posy>98</posy> <width>930</width> <height>2</height> <texture>script.plex/white-square.png</texture> <colordiffuse>40000000</colordiffuse> </control> </control> </itemlayout> <!-- FOCUSED LAYOUT ####################################### --> <focusedlayout height="100"> <control type="group"> <control type="group"> <visible>!Control.HasFocus(101)</visible> <posx>120</posx> <posy>24</posy> <control type="label"> <visible>String.IsEmpty(ListItem.Property(playing))</visible> <posx>-10</posx> <posy>0</posy> <width>60</width> <height>100</height> <font>font10</font> <align>center</align> <aligny>center</aligny> <textcolor>D8FFFFFF</textcolor> <label>[B]$INFO[ListItem.Property(track.number)][/B]</label> </control> <control type="image"> <visible>!String.IsEmpty(ListItem.Property(playing))</visible> <posx>0</posx> <posy>32.5</posy> <width>35</width> <height>35</height> <texture>script.plex/indicators/playing-circle.png</texture> <colordiffuse>FFE5A00D</colordiffuse> </control> <control type="group"> <visible>String.IsEmpty(ListItem.Property(video))</visible> <control type="image"> <posx>63</posx> <posy>11</posy> <width>74</width> <height>74</height> <texture>$INFO[ListItem.Thumb]</texture> <aspectratio>scale</aspectratio> </control> <control type="group"> <posx>168</posx> <posy>0</posy> <control type="label"> <posx>0</posx> <posy>15</posy> <width>692</width> <height>30</height> <font>font10</font> <align>left</align> <aligny>center</aligny> <textcolor>FFFFFFFF</textcolor> <label>[B]$INFO[ListItem.Label][/B]</label> </control> <control type="label"> <posx>0</posx> <posy>50</posy> <width>692</width> <height>30</height> <font>font10</font> <align>left</align> <aligny>center</aligny> <textcolor>B8FFFFFF</textcolor> <label>$INFO[ListItem.Label2]</label> </control> </control> </control> <control type="group"> <visible>!String.IsEmpty(ListItem.Property(video))</visible> <control type="image"> <posx>63</posx> <posy>11</posy> <width>132</width> <height>74</height> <texture>$INFO[ListItem.Thumb]</texture> <aspectratio>scale</aspectratio> </control> <control type="image"> <visible>String.IsEmpty(ListItem.Property(watched))</visible> <posx>895</posx> <posy>-1</posy> <width>35</width> <height>35</height> <texture>script.plex/indicators/unwatched.png</texture> </control> <control type="group"> <posx>226</posx> <posy>0</posy> <control type="label"> <posx>0</posx> <posy>15</posy> <width>584</width> <height>30</height> <font>font10</font> <align>left</align> <aligny>center</aligny> <textcolor>FFFFFFFF</textcolor> <label>[B]$INFO[ListItem.Label][/B]</label> </control> <control type="label"> <posx>0</posx> <posy>50</posy> <width>584</width> <height>30</height> <font>font10</font> <align>left</align> <aligny>center</aligny> <textcolor>B8FFFFFF</textcolor> <label>$INFO[ListItem.Label2]</label> </control> </control> </control> <control type="label"> <posx>756</posx> <posy>0</posy> <width>200</width> <height>100</height> <font>font10</font> <align>right</align> <aligny>center</aligny> <textcolor>D8FFFFFF</textcolor> <label>[B]$INFO[ListItem.Property(track.duration)][/B]</label> </control> <control type="image"> <visible>String.IsEmpty(ListItem.Property(is.footer))</visible> <posx>0</posx> <posy>97</posy> <width>930</width> <height>2</height> <texture>script.plex/white-square.png</texture> <colordiffuse>40000000</colordiffuse> </control> </control> <control type="group"> <visible>Control.HasFocus(101)</visible> <posx>63</posx> <posy>21</posy> <control type="image"> <posx>-40</posx> <posy>-40</posy> <width>1124</width> <height>180</height> <texture border="40">script.plex/square-rounded-shadow.png</texture> </control> <control type="image"> <posx>0</posx> <posy>0</posy> <width>1044</width> <height>100</height> <texture border="12">script.plex/white-square-rounded.png</texture> <colordiffuse>FFE5A00D</colordiffuse> </control> <!-- comment the previous and uncomment the following for re-enabling options button --> <!--<control type="image"> <posx>0</posx> <posy>0</posy> <width>999</width> <height>100</height> <texture border="12">script.plex/white-square-left-rounded.png</texture> <colordiffuse>FFE5A00D</colordiffuse> </control> <control type="image"> <posx>999</posx> <posy>0</posy> <width>45</width> <height>100</height> <texture>script.plex/buttons/more-vertical.png</texture> <colordiffuse>99FFFFFF</colordiffuse> </control>--> <control type="label"> <visible>String.IsEmpty(ListItem.Property(playing))</visible> <posx>24</posx> <posy>0</posy> <width>60</width> <height>100</height> <font>font12</font> <align>center</align> <aligny>center</aligny> <textcolor>B8000000</textcolor> <label>[B]$INFO[ListItem.Property(track.number)][/B]</label> </control> <control type="image"> <visible>!String.IsEmpty(ListItem.Property(playing))</visible> <posx>36</posx> <posy>32.5</posy> <width>35</width> <height>35</height> <texture>script.plex/indicators/playing-circle.png</texture> <colordiffuse>FF000000</colordiffuse> </control> <control type="group"> <visible>String.IsEmpty(ListItem.Property(video))</visible> <control type="image"> <visible>String.IsEmpty(ListItem.Property(video))</visible> <posx>103</posx> <posy>0</posy> <width>100</width> <height>100</height> <texture>$INFO[ListItem.Thumb]</texture> <aspectratio>scale</aspectratio> </control> <control type="group"> <posx>235</posx> <posy>0</posy> <control type="label"> <posx>0</posx> <posy>16</posy> <width>638</width> <height>30</height> <font>font12</font> <align>left</align> <aligny>center</aligny> <textcolor>DF000000</textcolor> <label>[B]$INFO[ListItem.Label][/B]</label> </control> <control type="label"> <posx>0</posx> <posy>51</posy> <width>638</width> <height>30</height> <font>font10</font> <align>left</align> <aligny>center</aligny> <textcolor>98000000</textcolor> <label>$INFO[ListItem.Label2]</label> </control> </control> </control> <control type="group"> <visible>!String.IsEmpty(ListItem.Property(video))</visible> <control type="image"> <posx>103</posx> <posy>0</posy> <width>178</width> <height>100</height> <texture>$INFO[ListItem.Thumb]</texture> <aspectratio>scale</aspectratio> </control> <control type="image"> <visible>String.IsEmpty(ListItem.Property(watched))</visible> <posx>951</posx> <posy>0</posy> <width>48</width> <height>48</height> <texture>script.plex/indicators/unwatched.png</texture> </control> <control type="group"> <posx>313</posx> <posy>0</posy> <control type="label"> <posx>0</posx> <posy>16</posy> <width>510</width> <height>30</height> <font>font12</font> <align>left</align> <aligny>center</aligny> <textcolor>DF000000</textcolor> <label>[B]$INFO[ListItem.Label][/B]</label> </control> <control type="label"> <posx>0</posx> <posy>51</posy> <width>510</width> <height>30</height> <font>font10</font> <align>left</align> <aligny>center</aligny> <textcolor>98000000</textcolor> <label>$INFO[ListItem.Label2]</label> </control> </control> </control> <control type="label"> <posx>802</posx> <posy>0</posy> <width>200</width> <height>100</height> <font>font12</font> <align>right</align> <aligny>center</aligny> <textcolor>B8000000</textcolor> <label>[B]$INFO[ListItem.Property(track.duration)][/B]</label> </control> </control> </control> </focusedlayout> </control> <control type="scrollbar" id="152"> <hitrect x="1108" y="33" w="90" h="734" /> <left>1128</left> <top>33</top> <width>10</width> <height>734</height> <onleft>101</onleft> <visible>true</visible> <texturesliderbackground colordiffuse="40000000" border="5">script.plex/white-square-rounded.png</texturesliderbackground> <texturesliderbar colordiffuse="77FFFFFF" border="5">script.plex/white-square-rounded.png</texturesliderbar> <texturesliderbarfocus colordiffuse="FFE5A00D" border="5">script.plex/white-square-rounded.png</texturesliderbarfocus> <textureslidernib>-</textureslidernib> <textureslidernibfocus>-</textureslidernibfocus> <pulseonselect>false</pulseonselect> <orientation>vertical</orientation> <showonepage>false</showonepage> <onleft>151</onleft> </control> </control> </control> </controls> </window>
{ "pile_set_name": "Github" }
/* SPDX-License-Identifier: MIT */ #ifndef __NVBIOS_EXTDEV_H__ #define __NVBIOS_EXTDEV_H__ enum nvbios_extdev_type { NVBIOS_EXTDEV_LM89 = 0x02, NVBIOS_EXTDEV_VT1103M = 0x40, NVBIOS_EXTDEV_PX3540 = 0x41, NVBIOS_EXTDEV_VT1105M = 0x42, /* or close enough... */ NVBIOS_EXTDEV_INA219 = 0x4c, NVBIOS_EXTDEV_INA209 = 0x4d, NVBIOS_EXTDEV_INA3221 = 0x4e, NVBIOS_EXTDEV_ADT7473 = 0x70, /* can also be a LM64 */ NVBIOS_EXTDEV_HDCP_EEPROM = 0x90, NVBIOS_EXTDEV_NONE = 0xff, }; struct nvbios_extdev_func { u8 type; u8 addr; u8 bus; }; int nvbios_extdev_parse(struct nvkm_bios *, int, struct nvbios_extdev_func *); int nvbios_extdev_find(struct nvkm_bios *, enum nvbios_extdev_type, struct nvbios_extdev_func *); bool nvbios_extdev_skip_probe(struct nvkm_bios *); #endif
{ "pile_set_name": "Github" }
// CLOSE ICONS // ----------- .close { float: right; font-size: 20px; font-weight: bold; line-height: @baseLineHeight; color: @black; text-shadow: 0 1px 0 rgba(255,255,255,1); .opacity(20); &:hover { color: @black; text-decoration: none; .opacity(40); cursor: pointer; } }
{ "pile_set_name": "Github" }
using FSO.Client.Controllers; using FSO.Client.Controllers.Panels; using FSO.Client.UI.Controls; using FSO.Client.UI.Framework; using FSO.Client.UI.Screens; using FSO.Client.Utils; using FSO.Common; using FSO.Common.DataService.Model; using FSO.Common.Utils; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FSO.Client.UI.Panels { public class UISandboxSelector : UIDialog { public UIButton CloseButton { get; set; } public UIListBox BookmarkListBox { get; set; } public UIListBoxTextStyle BookmarkListBoxColors { get; set; } public UISlider BookmarkListSlider { get; set; } public UIButton BookmarkListScrollUpButton { get; set; } public UIButton BookmarkScrollDownButton { get; set; } public UIButton SimsTabButton { get; set; } public UIButton IgnoreTabButton { get; set; } public UIImage SimsTab { get; set; } public UIImage IgnoreTab { get; set; } public Binding<Avatar> Binding; public UISandboxSelector() : base(UIDialogStyle.Close, true) { if (GlobalSettings.Default.DebugBody == 0) { GameThread.NextUpdate(x => FSOFacade.Controller.ShowPersonCreation(null)); } var ui = this.RenderScript("bookmarks.uis"); Caption = "Host a lot on :37564"; //var background = ui.Create<UIImage>("BookmarkBackground"); //SimsTab = ui.Create<UIImage>("SimsTab"); //AddAt(0, SimsTab); //IgnoreTab = ui.Create<UIImage>("IgnoreTab"); //AddAt(0, IgnoreTab); //IgnoreTab.Visible = false; //AddAt(0, ui.Create<UIImage>("Tab1Background")); //AddAt(0, ui.Create<UIImage>("Tab2Background")); var listBg = ui.Create<UIImage>("ListBoxBackground"); AddAt(4, listBg); //AddAt(0, background); //UIUtils.MakeDraggable(background, this, true); listBg.With9Slice(25, 25, 25, 25); listBg.Height += 180; BookmarkListBox.VisibleRows += 10; BookmarkListSlider.SetSize(10, 170 + 180); BookmarkScrollDownButton.Y += 180; BookmarkListSlider.AttachButtons(BookmarkListScrollUpButton, BookmarkScrollDownButton, 1); BookmarkListBox.AttachSlider(BookmarkListSlider); BookmarkListBox.OnDoubleClick += BookmarkListBox_OnDoubleClick; BookmarkListBoxColors = ui.Create<UIListBoxTextStyle>("BookmarkListBoxColors", BookmarkListBox.FontStyle); Remove(CloseButton); Remove(SimsTabButton); Remove(IgnoreTabButton); base.CloseButton.OnButtonClick += CloseButton_OnButtonClick; //IgnoreTabButton.OnButtonClick += (btn) => { ChangeType(BookmarkType.IGNORE_AVATAR); }; //SimsTabButton.OnButtonClick += (btn) => { ChangeType(BookmarkType.AVATAR); }; populateWithXMLHouses(); var joinButton = new UIButton(); joinButton.Caption = "Join a server"; joinButton.OnButtonClick += (btn) => { UIAlert alert = null; alert = UIScreen.GlobalShowAlert(new UIAlertOptions() { Message = "Enter the address of the server you wish to connect to. (can optionally include port, eg localhost:6666)", Width = 400, TextEntry = true, Buttons = new UIAlertButton[] { new UIAlertButton(UIAlertButtonType.Cancel, (btn2) => { UIScreen.RemoveDialog(alert); }), new UIAlertButton(UIAlertButtonType.OK, (btn2) => { UIScreen.RemoveDialog(alert); var addr = alert.ResponseText; if (!addr.Contains(':')) { addr += ":37564"; } UIScreen.RemoveDialog(this); LotSwitch(addr, true); }) } }, true); alert.ResponseText = "127.0.0.1"; }; joinButton.Width = 190; joinButton.X = 25; joinButton.Y = 500 - 50; Add(joinButton); var casButton = new UIButton(); casButton.Caption = "CAS"; casButton.OnButtonClick += (btn) => { if (UIScreen.Current is SandboxGameScreen) { ((SandboxGameScreen)UIScreen.Current).CleanupLastWorld(); } FSOFacade.Controller.ShowPersonCreation(null); }; casButton.Width = 50; casButton.X = 300-(25+50); casButton.Y = 500 - 50; Add(casButton); SetSize(300, 500); } public void LotSwitch(string location, bool external) { if (UIScreen.Current is SandboxGameScreen) { var sand = (SandboxGameScreen)UIScreen.Current; sand.Initialize(location, external); } else { FSOFacade.Controller.EnterSandboxMode(location, external); } } public void populateWithXMLHouses() { var xmlHouses = new List<UIXMLLotEntry>(); string[] paths = Directory.GetFiles(Path.Combine(FSOEnvironment.ContentDir, "Blueprints/"), "*.xml", SearchOption.AllDirectories); for (int i = 0; i < paths.Length; i++) { string entry = paths[i]; string filename = Path.GetFileName(entry); xmlHouses.Add(new UIXMLLotEntry { Filename = filename, Path = entry }); } paths = Directory.GetFiles(Path.Combine(GlobalSettings.Default.StartupPath, @"housedata/blueprints/"), "*.xml", SearchOption.AllDirectories); for (int i = 0; i < paths.Length; i++) { string entry = paths[i]; string filename = Path.GetFileName(entry); xmlHouses.Add(new UIXMLLotEntry { Filename = filename, Path = entry }); } try { paths = Directory.GetFiles(Path.Combine(GlobalSettings.Default.TS1HybridPath, @"UserData/Houses/"), "House**.iff", SearchOption.AllDirectories); for (int i = 0; i < paths.Length; i++) { string entry = paths[i]; string filename = Path.GetFileName(entry); xmlHouses.Add(new UIXMLLotEntry { Filename = filename, Path = entry }); } } catch { } try { paths = Directory.GetFiles(Path.Combine(FSOEnvironment.ContentDir, "LocalHouse/"), "*", SearchOption.AllDirectories); for (int i = 0; i < paths.Length; i++) { string entry = paths[i]; if (!entry.ToLowerInvariant().EndsWith(".fsor")) entry = entry.Substring(0, entry.Length - 5) + ".xml"; string filename = Path.GetFileName(entry); if (!xmlHouses.Any(x => x.Filename == filename)) { xmlHouses.Add(new UIXMLLotEntry { Filename = filename, Path = entry }); } } } catch { } BookmarkListBox.Columns[0].Alignment = TextAlignment.Left | TextAlignment.Top; BookmarkListBox.Columns[0].Width = (int)BookmarkListBox.Width; BookmarkListBox.Items = xmlHouses.Select(x => new UIListBoxItem(x, x.Filename.Substring(0, x.Filename.Length-4))).ToList(); } private void ChangeType(BookmarkType type) { var bookmark = type == BookmarkType.AVATAR; SimsTabButton.Selected = bookmark; SimsTab.Visible = bookmark; IgnoreTabButton.Selected = !bookmark; IgnoreTab.Visible = !bookmark; } private void BookmarkListBox_OnDoubleClick(UIElement button) { if (BookmarkListBox.SelectedItem == null) { return; } var item = (UIXMLLotEntry)BookmarkListBox.SelectedItem.Data; UIScreen.RemoveDialog(this); LotSwitch(item.Path, false); } private void CloseButton_OnButtonClick(UIElement button) { UIScreen.RemoveDialog(this); } } }
{ "pile_set_name": "Github" }
/************************************************************************* * Copyright 2017 Ent. Services Development Corporation LP * * Redistribution and use of this software in source and binary forms, * with or without modification, are permitted provided that the * following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ************************************************************************/ package com.eucalyptus.autoscaling.service; import static com.eucalyptus.util.RestrictedTypes.getIamActionByMessageType; import java.util.Map; import javax.annotation.Nonnull; import com.eucalyptus.auth.AuthContextSupplier; import com.eucalyptus.auth.Permissions; import com.eucalyptus.autoscaling.common.msgs.AutoScalingMessage; import com.eucalyptus.autoscaling.common.policy.AutoScalingPolicySpec; import com.eucalyptus.component.annotation.ComponentNamed; import com.eucalyptus.context.Contexts; import com.eucalyptus.context.ServiceAdvice; /** * */ @ComponentNamed public class AutoScalingServiceAdvice extends ServiceAdvice { @Override protected void beforeService( @Nonnull final Object requestObject ) throws Exception { if ( requestObject instanceof AutoScalingMessage ) { final AutoScalingMessage request = (AutoScalingMessage) requestObject; final AuthContextSupplier user = Contexts.lookup( ).getAuthContext( ); // Authorization check if ( !Permissions.perhapsAuthorized( AutoScalingPolicySpec.VENDOR_AUTOSCALING, getIamActionByMessageType( request ), user ) ) { throw new AutoScalingAuthorizationException( "UnauthorizedOperation", "You are not authorized to perform this operation." ); } // Validation final Map<String,String> validationErrorsByField = request.validate(); if ( !validationErrorsByField.isEmpty() ) { throw new AutoScalingClientException( "ValidationError", validationErrorsByField.values().iterator().next() ); } } else { throw new AutoScalingAuthorizationException( "UnauthorizedOperation", "You are not authorized to perform this operation." ); } } }
{ "pile_set_name": "Github" }
// // NSString+KIFAdditions.h // KIF // // Created by Alex Odawa on 1/28/16. // // #import <Foundation/Foundation.h> #pragma mark - NSString @interface NSString (KIFAdditions) - (BOOL)KIF_isEqualToStringOrAttributedString:(id)aString; @end
{ "pile_set_name": "Github" }
/* CoordinateSharp is a .NET standard library that is intended to ease geographic coordinate format conversions and location based celestial calculations. https://github.com/Tronald/CoordinateSharp Many celestial formulas in this library are based on Jean Meeus's Astronomical Algorithms (2nd Edition). Comments that reference only a chapter are referring to this work. License CoordinateSharp is split licensed and may be licensed under the GNU Affero General Public License version 3 or a commercial use license as stated. Copyright (C) 2019, Signature Group, LLC This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation with the addition of the following permission added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY Signature Group, LLC. Signature Group, LLC DISCLAIMS THE WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program; if not, see http://www.gnu.org/licenses or write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA, 02110-1301 USA, or download the license from the following URL: https://www.gnu.org/licenses/agpl-3.0.html The interactive user interfaces in modified source and object code versions of this program must display Appropriate Legal Notices, as required under Section 5 of the GNU Affero General Public License. You can be released from the requirements of the license by purchasing a commercial license. Buying such a license is mandatory as soon as you develop commercial activities involving the CoordinateSharp software without disclosing the source code of your own applications. These activities include: offering paid services to customers as an ASP, on the fly location based calculations in a web application, or shipping CoordinateSharp with a closed source product. Organizations or use cases that fall under the following conditions may receive a free commercial use license upon request. -Department of Defense -Department of Homeland Security -Open source contributors to this library -Scholarly or scientific uses on a case by case basis. -Emergency response / management uses on a case by case basis. For more information, please contact Signature Group, LLC at this address: [email protected] */ using System; using System.Text.RegularExpressions; using System.Linq; using System.Globalization; namespace CoordinateSharp { internal partial class FormatFinder { private static bool TryDecimalDegree(string s, out double[] d) { d = null; if (Regex.Matches(s, @"[a-zA-Z]").Count != 2) { return false; } //Should only contain 1 letter per part. string[] sA = SpecialSplit(s, true); if (sA.Count() == 2 || sA.Count() == 4) { double lat; double lng; int latR = 1; //Sets negative if South int lngR = 1; //Sets negative if West //Contact get both directional indicator together with string if (sA.Count() == 4) { sA[0] += sA[1]; sA[1] = sA[2] + sA[3]; } string latString = string.Empty; string longString = string.Empty; //Find Directions (new struct allows for reverse formatted coordinate) DirectionFinder p1 = new DirectionFinder(sA[0]); DirectionFinder p2 = new DirectionFinder(sA[1]); if (p1.Success) { if (p1.CoordinateType.Value == CoordinateType.Lat) { latString = p1.PartString; latR = p1.Rad; } else { longString = p1.PartString; lngR = p1.Rad; } } if (p2.Success) { if (p2.CoordinateType.Value == CoordinateType.Lat) { latString = p2.PartString; latR = p2.Rad; } else { longString = p2.PartString; lngR = p2.Rad; } } //Either lat or long not provided in this case if (string.IsNullOrEmpty(latString) || string.IsNullOrEmpty(longString)) { return false; } latString = Regex.Replace(latString, "[^0-9.]", ""); longString = Regex.Replace(longString, "[^0-9.]", ""); if (!double.TryParse(latString, NumberStyles.Any, CultureInfo.InvariantCulture, out lat)) { return false; } if (!double.TryParse(longString, NumberStyles.Any, CultureInfo.InvariantCulture, out lng)) { return false; } lat *= latR; lng *= lngR; d = new double[] { lat, lng }; return true; } return false; } } }
{ "pile_set_name": "Github" }
#ifndef BOOST_MPL_AUX_NA_ASSERT_HPP_INCLUDED #define BOOST_MPL_AUX_NA_ASSERT_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2001-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id$ // $Date$ // $Revision$ #include <boost/mpl/aux_/na.hpp> #include <boost/mpl/aux_/config/msvc.hpp> #include <boost/mpl/aux_/config/workaround.hpp> #if !BOOST_WORKAROUND(_MSC_FULL_VER, <= 140050601) \ && !BOOST_WORKAROUND(__EDG_VERSION__, <= 243) # include <boost/mpl/assert.hpp> # define BOOST_MPL_AUX_ASSERT_NOT_NA(x) \ BOOST_MPL_ASSERT_NOT((boost::mpl::is_na<type>)) \ /**/ #else # include <boost/static_assert.hpp> # define BOOST_MPL_AUX_ASSERT_NOT_NA(x) \ BOOST_STATIC_ASSERT(!boost::mpl::is_na<x>::value) \ /**/ #endif #endif // BOOST_MPL_AUX_NA_ASSERT_HPP_INCLUDED
{ "pile_set_name": "Github" }
## Grandfather directory: select and deselect. actions: + dir-1 - dir-1 results: 0 dir-1 0 dir-1/dir-2 0 dir-1/dir-2/file-5.txt 0 dir-1/dir-2/file-6.txt 0 dir-1/file-3.txt 0 dir-1/file-4.txt 0 file-1.txt 0 file-2.txt
{ "pile_set_name": "Github" }
// Configuration Parameters for whole Agent #include "stdafx.h" #include "commander.h" #include <string> #include "cfg.h" #include "logger.h" namespace cma::commander { std::mutex run_command_processor_lock; bool RunCommand(std::string_view peer, std::string_view cmd) { if (!cma::tools::IsEqual(peer, kMainPeer)) { XLOG::d("Peer name '{}' is invalid", peer); return false; } if (cmd.empty()) return false; if (cma::tools::IsEqual(cmd, kReload)) { XLOG::l.t("Commander: Reload"); cma::ReloadConfig(); // command line return true; } if (cma::tools::IsEqual(cmd, kPassTrue)) { XLOG::l.t("Commander: Pass True"); return true; } if (cma::tools::IsEqual(cmd, kUninstallAlert)) { XLOG::l.t("Commander: Alert of Uninstall"); if (cma::IsTest()) return false; if (!cma::IsService()) return false; cma::G_UninstallALert.set(); return true; } XLOG::l("Commander: Unknown command '{}'", cmd); return false; } // #TODO global. MOVE TO THE service processor // #GLOBAL RunCommandProcessor g_rcp = RunCommand; RunCommandProcessor ObtainRunCommandProcessor() { std::lock_guard lk(run_command_processor_lock); return g_rcp; } void ChangeRunCommandProcessor(RunCommandProcessor rcp) { std::lock_guard lk(run_command_processor_lock); g_rcp = rcp; } } // namespace cma::commander
{ "pile_set_name": "Github" }