code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
#ifndef TAI_H #define TAI_H #ifdef _MSC_VER typedef __int64 int64_t; typedef unsigned __int64 uint64_t; #else #include <inttypes.h> /* more portable than stdint.h */ #endif #ifdef _MSC_VER #define LL(x) x ## i64 #define ULL(x) x ## ui64 #else #define LL(x) x ## LL #define ULL(x) x ## ULL #endif struct tai { uint64_t x; } ; extern void tai_now(struct tai *t); /* JW: MSVC cannot convert unsigned to double :-( */ #define tai_approx(t) ((double) ((int64_t)(t)->x)) extern void tai_add(struct tai *t, struct tai *u, struct tai *v); extern void tai_sub(struct tai *t, struct tai *u, struct tai *v); #define tai_less(t,u) ((t)->x < (u)->x) #define TAI_PACK 8 extern void tai_pack(char *s, struct tai *t); extern void tai_unpack(char *s, struct tai *t); #endif
edechter/swipl-devel
src/libtai/tai.h
C
lgpl-2.1
771
<?php require_once('../_include.php'); /* Make sure that the user has admin access rights. */ SimpleSAML\Utils\Auth::requireAdmin(); phpinfo();
dialogik/simplesamlphp
www/admin/phpinfo.php
PHP
lgpl-2.1
147
/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #ifndef JOULEHEATING_H #define JOULEHEATING_H #include "Kernel.h" //Forward Declarations class JouleHeating; class Function; template<> InputParameters validParams<JouleHeating>(); class JouleHeating : public Kernel { public: JouleHeating(const std::string & name, InputParameters parameters); protected: virtual Real computeQpResidual(); VariableGradient& _grad_potential; MaterialProperty<Real> & _thermal_conductivity; }; #endif
cpritam/moose
modules/misc/include/JouleHeating.h
C
lgpl-2.1
1,320
/** * * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. * * 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, see <http://www.gnu.org/licenses/>. * **/ package lucee.runtime.tag; import lucee.runtime.exp.TagNotSupported; import lucee.runtime.ext.tag.TagImpl; /** * Used in a cfgrid, cfgridupdate allows you to perform updates to data sources directly from edited * grid data. The cfgridupdate tag provides a direct interface with your data source. * The cfgridupdate tag applies delete row actions first, then INSERT row actions, and then UPDATE row * actions. If an error is encountered, row processing stops. * * * **/ public final class GridUpdate extends TagImpl { private String password; private String datasource; private String providerdsn; private boolean keyonly; private String tablename; private String connectstring; private String dbtype; private String grid; private String dbname; private String username; private String dbserver; private String tableowner; private String provider; private String tablequalifier; /** * constructor for the tag class **/ public GridUpdate() throws TagNotSupported { throw new TagNotSupported("GridUpdate"); } /** set the value password * If specified, password overrides the password value specified in the ODBC setup. * @param password value to set **/ public void setPassword(String password) { this.password=password; } /** set the value datasource * The name of the data source for the update action. * @param datasource value to set **/ public void setDatasource(String datasource) { this.datasource=datasource; } /** set the value providerdsn * Data source name for the COM provider (OLE-DB only). * @param providerdsn value to set **/ public void setProviderdsn(String providerdsn) { this.providerdsn=providerdsn; } /** set the value keyonly * Yes or No. Yes specifies that in the update action, the WHERE criteria is confined to the key * values. No specifies that in addition to the key values, the original values of any changed fields * are included in the WHERE criteria. Default is Yes. * @param keyonly value to set **/ public void setKeyonly(boolean keyonly) { this.keyonly=keyonly; } /** set the value tablename * The name of the table to update. * @param tablename value to set **/ public void setTablename(String tablename) { this.tablename=tablename; } public void setConnectstring(String connectstring) { this.connectstring=connectstring; } /** set the value dbtype * The database driver type * @param dbtype value to set **/ public void setDbtype(String dbtype) { this.dbtype=dbtype; } /** set the value grid * The name of the cfgrid form element that is the source for the update action. * @param grid value to set **/ public void setGrid(String grid) { this.grid=grid; } /** set the value dbname * The database name (Sybase System 11 driver and SQLOLEDB provider only). If specified, * dbName overrides the default database specified in the data source. * @param dbname value to set **/ public void setDbname(String dbname) { this.dbname=dbname; } /** set the value username * If specified, username overrides the username value specified in the ODBC setup. * @param username value to set **/ public void setUsername(String username) { this.username=username; } /** set the value dbserver * For native database drivers and the SQLOLEDB provider, specifies the name of the database * server computer. If specified, dbServer overrides the server specified in the data source. * @param dbserver value to set **/ public void setDbserver(String dbserver) { this.dbserver=dbserver; } /** set the value tableowner * For data sources that support table ownership (such as SQL Server, Oracle, and Sybase SQL * Anywhere), use this field to specify the owner of the table. * @param tableowner value to set **/ public void setTableowner(String tableowner) { this.tableowner=tableowner; } /** set the value provider * COM provider (OLE-DB only). * @param provider value to set **/ public void setProvider(String provider) { this.provider=provider; } /** set the value tablequalifier * For data sources that support table qualifiers, use this field to specify the qualifier for the * table. The purpose of table qualifiers varies across drivers. For SQL Server and Oracle, the qualifier * refers to the name of the database that contains the table. For the Intersolv dBase driver, the qualifier * refers to the directory where the DBF files are located. * @param tablequalifier value to set **/ public void setTablequalifier(String tablequalifier) { this.tablequalifier=tablequalifier; } @Override public int doStartTag() { return SKIP_BODY; } @Override public int doEndTag() { return EVAL_PAGE; } @Override public void release() { super.release(); password=""; datasource=""; providerdsn=""; keyonly=false; tablename=""; connectstring=""; dbtype=""; grid=""; dbname=""; username=""; dbserver=""; tableowner=""; provider=""; tablequalifier=""; } }
lucee/unoffical-Lucee-no-jre
source/java/core/src/lucee/runtime/tag/GridUpdate.java
Java
lgpl-2.1
5,754
// --------------------------------------------------------------------- // // Copyright (C) 2000 - 2016 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // test internal::extract_dofs_by_component for some corner cases that // I was unsure about when refactoring some code in there // // this particular test checks the call path to // internal::extract_dofs_by_component from DoFTools::extract_dofs via // the BlockMask argument #include "../tests.h" #include <deal.II/base/logstream.h> #include <deal.II/grid/tria.h> #include <deal.II/grid/tria_iterator.h> #include <deal.II/grid/tria_accessor.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/hp/dof_handler.h> #include <deal.II/fe/fe_q.h> #include <deal.II/fe/fe_raviart_thomas.h> #include <deal.II/fe/fe_nedelec.h> #include <deal.II/fe/fe_system.h> #include <deal.II/dofs/dof_tools.h> #include <fstream> template <int dim> void check () { Triangulation<dim> tr(Triangulation<dim>:: limit_level_difference_at_vertices); GridGenerator::hyper_cube(tr, -1,1); tr.refine_global (1); tr.begin_active()->set_refine_flag(); tr.execute_coarsening_and_refinement(); FESystem<dim> element (FE_Q<dim>(2), 1, FE_Nedelec<dim>(0), 1); DoFHandler<dim> dof(tr); dof.distribute_dofs(element); dof.distribute_mg_dofs(element); // try all possible block // masks, which we encode as bit // strings for (unsigned int int_mask=0; int_mask<(1U<<element[0].n_blocks()); ++int_mask) { std::vector<bool> component_mask (element[0].n_blocks()); for (unsigned int c=0; c<element[0].n_blocks(); ++c) component_mask[c] = (int_mask & (1<<c)); for (unsigned int level=0; level<tr.n_levels(); ++level) { deallog << "level=" << level << std::endl; std::vector<bool> dofs (dof.n_dofs(level)); DoFTools::extract_level_dofs (level, dof, BlockMask(component_mask), dofs); for (unsigned int d=0; d<dofs.size(); ++d) deallog << dofs[d]; deallog << std::endl; } } } int main () { std::ofstream logfile ("output"); deallog << std::setprecision (2); deallog << std::fixed; deallog.attach(logfile); deallog.push ("2d"); check<2> (); deallog.pop (); deallog.push ("3d"); check<3> (); deallog.pop (); }
pesser/dealii
tests/dofs/extract_dofs_by_component_02_mg.cc
C++
lgpl-2.1
2,818
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube 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 3 of the License, or (at your option) any later version. * * SonarQube 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.computation.issue; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Collections2; import java.util.Collection; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.server.user.index.UserDoc; import org.sonar.server.user.index.UserIndex; import org.sonar.server.util.cache.CacheLoader; /** * Loads the association between a SCM account and a SQ user */ public class ScmAccountToUserLoader implements CacheLoader<String, String> { private static final Logger log = Loggers.get(ScmAccountToUserLoader.class); private final UserIndex index; public ScmAccountToUserLoader(UserIndex index) { this.index = index; } @Override public String load(String scmAccount) { List<UserDoc> users = index.getAtMostThreeActiveUsersForScmAccount(scmAccount); if (users.size() == 1) { return users.get(0).login(); } if (!users.isEmpty()) { // multiple users are associated to the same SCM account, for example // the same email Collection<String> logins = Collections2.transform(users, UserDocToLogin.INSTANCE); log.warn(String.format("Multiple users share the SCM account '%s': %s", scmAccount, Joiner.on(", ").join(logins))); } return null; } @Override public Map<String, String> loadAll(Collection<? extends String> scmAccounts) { throw new UnsupportedOperationException("Loading by multiple scm accounts is not supported yet"); } private enum UserDocToLogin implements Function<UserDoc, String> { INSTANCE; @Nullable @Override public String apply(@Nonnull UserDoc user) { return user.login(); } } }
sulabh-msft/sonarqube
server/sonar-server/src/main/java/org/sonar/server/computation/issue/ScmAccountToUserLoader.java
Java
lgpl-3.0
2,728
<div class="toolbar toolbar-{$toolbar}" role="toolbar"> {if $toolbar == "top" } <div class="sorter-container"> <span class="amount">{if ($amount > 1)}{intl l="%nb Items" nb="{$amount}"}{else}{intl l="%nb Item" nb="{$amount}"}{/if}</span> <span class="limiter"> <label for="limit-top">{intl l="Show"}</label> <select id="limit-top" name="limit"> <option value="{url path={navigate to="current"} limit="4"}" {if $limit==4}selected{/if}>4</option> <option value="{url path={navigate to="current"} limit="8"}" {if $limit==8}selected{/if}>8</option> <option value="{url path={navigate to="current"} limit="12"}" {if $limit==12}selected{/if}>12</option> <option value="{url path={navigate to="current"} limit="50"}"{if $limit==50}selected{/if}>50</option> <option value="{url path={navigate to="current"} limit="100000"}" {if $limit==100000}selected{/if}>{intl l="All"}</option> </select> <span class="per-page">{intl l="per page"}</span> </span><!-- /.limiter --> <span class="sort-by"> <label for="sortby-top">{intl l="Sort By"}</label> <select id="sortby-top" name="sortby"> {*<option value="{url path="{category attr="url"}" order="manual"}">{intl l="Position"}</option>*} <option value="{url path={navigate to="current"} limit=$limit order="alpha"}" {if $order=="alpha"}selected{/if}>{intl l="Name ascending"}</option> <option value="{url path={navigate to="current"} limit=$limit order="alpha_reverse"}" {if $order=="alpha_reverse"}selected{/if}>{intl l="Name descending"}</option> <option value="{url path={navigate to="current"} limit=$limit order="min_price"}" {if $order=="min_price"}selected{/if}>{intl l="Price ascending"}</option> <option value="{url path={navigate to="current"} limit=$limit order="max_price"}" {if $order=="max_price"}selected{/if}>{intl l="Price descending"}</option> {*<option value="{url path="{category attr="url"}" order="rating"}">{intl l="Rating"}</option>*} </select> </span><!-- /.sort-by --> <span class="view-mode"> <span class="view-mode-label">{intl l="View as"}:</span> <span class="view-mode-btn"> <a href="{url path="{navigate to="current"}" mode="grid"}" data-toggle="view" role="button" title="{intl l="Grid"}" rel="nofollow" class="btn btn-grid"><i class="icon-grid"></i></a> <a href="{url path="{navigate to="current"}" mode="list"}" data-toggle="view" role="button" title="{intl l="List"}" rel="nofollow" class="btn btn-list"><i class="icon-list"></i></a> </span> </span><!-- /.view-mode --> </div><!-- /.sorter --> {else} {if $amount > $limit} <div class="pagination-container" role="pagination" aria-labelledby="pagination-label-{$toolbar}"> <strong id="pagination-label-{$toolbar}" class="pagination-label">{intl l="Pagination"}</strong> <ul class="pagination"> {if $product_page le 1} <li class="disabled"> <span class="prev"><i class="icon-prev"></i></span> </li> {else} <li> <a href="{url path={navigate to="current"} page={$product_page-1} }" title="{intl l="Previous"}" class="prev"><i class="icon-prev"></i></a> </li> {/if} {pageloop rel="product_list"} <li{if $PAGE eq $CURRENT} class="active"{/if}> <a href="{url path={navigate to="current"} page=$PAGE }"> {$PAGE} </a> </li> {if $PAGE eq $LAST} {if $CURRENT eq $LAST} <li class="disabled"> <span class="next"><i class="icon-next"></i></span> </li> {else} <li> <a href="{url path={navigate to="current"} page={$NEXT} }" title="{intl l="Next"}" class="next"><i class="icon-next"></i></a> </li> {/if} {/if} {/pageloop} </ul> </div> {/if} {/if} </div>
40thoughts/WEB-Random-Lab.io
templates/frontOffice/randomlab/includes/toolbar.html
HTML
lgpl-3.0
4,610
<?php /** * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program 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 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ class StickItem extends Item{ public function __construct($meta = 0, $count = 1){ parent::__construct(STICK, 0, $count, "Stick"); } }
linuxboytoo/pocketmine
src/material/item/generic/Stick.php
PHP
lgpl-3.0
853
--- title: docker/ucp dump-certs description: Print the public certificates used by this UCP web server keywords: docker, ucp, cli, dump-certs --- Print the public certificates used by this UCP web server ## Description This command outputs the public certificates for the UCP web server running on this node. By default it prints the contents of the ca.pem and cert.pem files. When integrating UCP and DTR, use this command with the `--cluster --ca` flags to configure DTR. ## Options | Option | Description | |:--------------------------|:---------------------------| |`--debug, D`|Enable debug mode| |`--jsonlog`|Produce json formatted output for easier parsing| |`--ca`|Only print the contents of the ca.pem file| |`--cluster`|Print the internal UCP swarm root CA and cert instead of the public server cert|
anweiss/docker.github.io
datacenter/ucp/2.1/reference/cli/dump-certs.md
Markdown
apache-2.0
853
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute.Models { /// <summary> /// Parameters supplied to the Create Virtual Machine operation. /// </summary> public partial class VirtualMachineCreateParameters { private string _availabilitySetName; /// <summary> /// Optional. Specifies the name of an availability set to which to add /// the virtual machine. This value controls the virtual machine /// allocation in the Azure environment. Virtual machines specified in /// the same availability set are allocated to different nodes to /// maximize availability. /// </summary> public string AvailabilitySetName { get { return this._availabilitySetName; } set { this._availabilitySetName = value; } } private IList<ConfigurationSet> _configurationSets; /// <summary> /// Optional. Contains the collection of configuration sets that /// contain system and application configuration settings. /// </summary> public IList<ConfigurationSet> ConfigurationSets { get { return this._configurationSets; } set { this._configurationSets = value; } } private IList<DataVirtualHardDisk> _dataVirtualHardDisks; /// <summary> /// Optional. Contains the parameters Azure used to create the data /// disk for the virtual machine. /// </summary> public IList<DataVirtualHardDisk> DataVirtualHardDisks { get { return this._dataVirtualHardDisks; } set { this._dataVirtualHardDisks = value; } } private Uri _mediaLocation; /// <summary> /// Optional. Location where VMImage VHDs should be copied, for /// published VMImages. /// </summary> public Uri MediaLocation { get { return this._mediaLocation; } set { this._mediaLocation = value; } } private OSVirtualHardDisk _oSVirtualHardDisk; /// <summary> /// Optional. Contains the parameters Azure used to create the /// operating system disk for the virtual machine. /// </summary> public OSVirtualHardDisk OSVirtualHardDisk { get { return this._oSVirtualHardDisk; } set { this._oSVirtualHardDisk = value; } } private bool? _provisionGuestAgent; /// <summary> /// Optional. Indicates whether the WindowsAzureGuestAgent service is /// installed on the Virtual Machine. To run a resource extension in a /// Virtual Machine, this service must be installed. /// </summary> public bool? ProvisionGuestAgent { get { return this._provisionGuestAgent; } set { this._provisionGuestAgent = value; } } private IList<ResourceExtensionReference> _resourceExtensionReferences; /// <summary> /// Optional. Contains a collection of resource extensions that are to /// be installed on the Virtual Machine. This element is used if /// ProvisionGuestAgent is set to true. /// </summary> public IList<ResourceExtensionReference> ResourceExtensionReferences { get { return this._resourceExtensionReferences; } set { this._resourceExtensionReferences = value; } } private string _roleName; /// <summary> /// Required. Specifies the name for the virtual machine. The name must /// be unique within the deployment. /// </summary> public string RoleName { get { return this._roleName; } set { this._roleName = value; } } private string _roleSize; /// <summary> /// Optional. The size of the virtual machine. /// </summary> public string RoleSize { get { return this._roleSize; } set { this._roleSize = value; } } private string _vMImageName; /// <summary> /// Optional. Name of the VMImage from which this Role is to be /// created. If the OSDisk in the VMImage was Specialized, then no /// WindowsProvisioningConfigurationSet or /// LinuxProvisioningConfigurationSet should be provided. No /// OSVirtualHardDisk or DataVirtualHardDisk should be specified when /// using this argument. /// </summary> public string VMImageName { get { return this._vMImageName; } set { this._vMImageName = value; } } /// <summary> /// Initializes a new instance of the VirtualMachineCreateParameters /// class. /// </summary> public VirtualMachineCreateParameters() { this.ConfigurationSets = new LazyList<ConfigurationSet>(); this.DataVirtualHardDisks = new LazyList<DataVirtualHardDisk>(); this.ResourceExtensionReferences = new LazyList<ResourceExtensionReference>(); } /// <summary> /// Initializes a new instance of the VirtualMachineCreateParameters /// class with required arguments. /// </summary> public VirtualMachineCreateParameters(string roleName) : this() { if (roleName == null) { throw new ArgumentNullException("roleName"); } this.RoleName = roleName; } } }
djoelz/azure-sdk-for-net
src/ComputeManagement/Generated/Models/VirtualMachineCreateParameters.cs
C#
apache-2.0
6,700
/* * Copyright 2012 Amadeus s.a.s. * 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. */ var Aria = require("../Aria"); var ariaTouchEvent = require("./Event"); var ariaCoreBrowser = require("../core/Browser"); /** * Contains delegated handler for a tap event */ module.exports = Aria.classDefinition({ $singleton : true, $classpath : "aria.touch.ClickBuster", $statics : { RADIO : 25, DELAY : 500 }, $constructor : function () { this.isDesktop = ariaCoreBrowser.isDesktopView; this.lastEvt = null; }, $prototype : { registerTap : function (event) { this.lastEvt = { pos : { x : event.detail.currentX, y : event.detail.currentY }, date : new Date() }; }, preventGhostClick : function (event) { if (this._alreadyHandled(event)) { event.preventDefault(); event.stopPropagation(); return false; } return true; }, _alreadyHandled : function (e) { var position = ariaTouchEvent.getPositions(e)[0]; return (this.lastEvt && this._isShortDelay(this.lastEvt.date, new Date()) && this._isSameArea(this.lastEvt.pos, position)); }, _isSameArea : function (pos1, pos2) { return (Math.abs(pos1.x - pos2.x) < this.RADIO && Math.abs(pos1.y - pos2.y) < this.RADIO); }, _isShortDelay : function (date1, date2) { return (date2 - date1 <= this.DELAY); } } });
fbasso/ariatemplates
src/aria/touch/ClickBuster.js
JavaScript
apache-2.0
2,140
//===--- UnownedTypeInfo.h - Supplemental API for [unowned] -----*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines UnownedTypeInfo, which supplements the FixedTypeInfo // interface for types that implement [unowned] references. // //===----------------------------------------------------------------------===// #ifndef SWIFT_IRGEN_UNOWNEDTYPEINFO_H #define SWIFT_IRGEN_UNOWNEDTYPEINFO_H #include "LoadableTypeInfo.h" namespace swift { namespace irgen { /// \brief An abstract class designed for use when implementing a /// ReferenceStorageType with [unowned] ownership. class UnownedTypeInfo : public LoadableTypeInfo { protected: UnownedTypeInfo(llvm::Type *type, Size size, const SpareBitVector &spareBits, Alignment align) : LoadableTypeInfo(type, size, spareBits, align, IsNotPOD, IsFixedSize, STIK_Unowned) {} UnownedTypeInfo(llvm::Type *type, Size size, SpareBitVector &&spareBits, Alignment align) : LoadableTypeInfo(type, size, std::move(spareBits), align, IsNotPOD, IsFixedSize, STIK_Unowned) {} public: // No API yet. static bool classof(const UnownedTypeInfo *type) { return true; } static bool classof(const TypeInfo *type) { return type->getSpecialTypeInfoKind() == STIK_Unowned; } }; } } #endif
kentya6/swift
lib/IRGen/UnownedTypeInfo.h
C
apache-2.0
1,751
<!--- 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. --> # CameraError onError callback function that provides an error message. function(message) { // Show a helpful message } ### Parameters - __message__: The message is provided by the device's native code. _(String)_
AppGyver/steroids-docs
docs/en/stable/cordova/camera/parameter/cameraError.md
Markdown
apache-2.0
1,056
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.api.GroovyPolyVariantReference; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; public interface GrIndexProperty extends GrExpression { @NotNull GrExpression getInvokedExpression(); @NotNull GrArgumentList getArgumentList(); @Nullable GroovyPolyVariantReference getLValueReference(); @Nullable GroovyPolyVariantReference getRValueReference(); }
vvv1559/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/expressions/path/GrIndexProperty.java
Java
apache-2.0
1,302
------------------------------------------------------------------------------- -- cms catalog ------------------------------------------------------------------------------- CREATE TABLE CMS_CATALOG( ID BIGINT NOT NULL, NAME VARCHAR(50), CODE VARCHAR(200), LOGO VARCHAR(200), TYPE INT, TEMPLATE_INDEX VARCHAR(200), TEMPLATE_LIST VARCHAR(200), TEMPLATE_DETAIL VARCHAR(200), KEYWORD VARCHAR(200), DESCRIPTION VARCHAR(200), PARENT_ID BIGINT, CONSTRAINT PK_CMS_CATALOG PRIMARY KEY(ID), CONSTRAINT FK_CMS_CATALOG_PARENT FOREIGN KEY(PARENT_ID) REFERENCES CMS_CATALOG(ID) );
NJU-STP/STP
src/main/resources/dbmigrate/hsql/cms/V0_0_1__cms_catalog.sql
SQL
apache-2.0
621
package devops // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/tracing" "net/http" ) // PipelineTemplateDefinitionsClient is the azure DevOps Resource Provider type PipelineTemplateDefinitionsClient struct { BaseClient } // NewPipelineTemplateDefinitionsClient creates an instance of the PipelineTemplateDefinitionsClient client. func NewPipelineTemplateDefinitionsClient(subscriptionID string) PipelineTemplateDefinitionsClient { return NewPipelineTemplateDefinitionsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewPipelineTemplateDefinitionsClientWithBaseURI creates an instance of the PipelineTemplateDefinitionsClient client. func NewPipelineTemplateDefinitionsClientWithBaseURI(baseURI string, subscriptionID string) PipelineTemplateDefinitionsClient { return PipelineTemplateDefinitionsClient{NewWithBaseURI(baseURI, subscriptionID)} } // List lists all pipeline templates which can be used to configure an Azure Pipeline. func (client PipelineTemplateDefinitionsClient) List(ctx context.Context) (result PipelineTemplateDefinitionListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/PipelineTemplateDefinitionsClient.List") defer func() { sc := -1 if result.ptdlr.Response.Response != nil { sc = result.ptdlr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listNextResults req, err := client.ListPreparer(ctx) if err != nil { err = autorest.NewErrorWithError(err, "devops.PipelineTemplateDefinitionsClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.ptdlr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "devops.PipelineTemplateDefinitionsClient", "List", resp, "Failure sending request") return } result.ptdlr, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "devops.PipelineTemplateDefinitionsClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. func (client PipelineTemplateDefinitionsClient) ListPreparer(ctx context.Context) (*http.Request, error) { const APIVersion = "2019-07-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPath("/providers/Microsoft.DevOps/pipelineTemplateDefinitions"), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client PipelineTemplateDefinitionsClient) ListSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) return autorest.SendWithSender(client, req, sd...) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client PipelineTemplateDefinitionsClient) ListResponder(resp *http.Response) (result PipelineTemplateDefinitionListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listNextResults retrieves the next set of results, if any. func (client PipelineTemplateDefinitionsClient) listNextResults(ctx context.Context, lastResults PipelineTemplateDefinitionListResult) (result PipelineTemplateDefinitionListResult, err error) { req, err := lastResults.pipelineTemplateDefinitionListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "devops.PipelineTemplateDefinitionsClient", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "devops.PipelineTemplateDefinitionsClient", "listNextResults", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "devops.PipelineTemplateDefinitionsClient", "listNextResults", resp, "Failure responding to next results request") } return } // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client PipelineTemplateDefinitionsClient) ListComplete(ctx context.Context) (result PipelineTemplateDefinitionListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/PipelineTemplateDefinitionsClient.List") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.List(ctx) return }
pweil-/origin
vendor/github.com/Azure/azure-sdk-for-go/services/preview/devops/mgmt/2019-07-01-preview/devops/pipelinetemplatedefinitions.go
GO
apache-2.0
6,010
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. #include <google/protobuf/compiler/cpp/cpp_primitive_field.h> #include <google/protobuf/compiler/cpp/cpp_helpers.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> namespace google { namespace protobuf { namespace compiler { namespace cpp { using internal::WireFormatLite; namespace { // For encodings with fixed sizes, returns that size in bytes. Otherwise // returns -1. int FixedSize(FieldDescriptor::Type type) { switch (type) { case FieldDescriptor::TYPE_INT32 : return -1; case FieldDescriptor::TYPE_INT64 : return -1; case FieldDescriptor::TYPE_UINT32 : return -1; case FieldDescriptor::TYPE_UINT64 : return -1; case FieldDescriptor::TYPE_SINT32 : return -1; case FieldDescriptor::TYPE_SINT64 : return -1; case FieldDescriptor::TYPE_FIXED32 : return WireFormatLite::kFixed32Size; case FieldDescriptor::TYPE_FIXED64 : return WireFormatLite::kFixed64Size; case FieldDescriptor::TYPE_SFIXED32: return WireFormatLite::kSFixed32Size; case FieldDescriptor::TYPE_SFIXED64: return WireFormatLite::kSFixed64Size; case FieldDescriptor::TYPE_FLOAT : return WireFormatLite::kFloatSize; case FieldDescriptor::TYPE_DOUBLE : return WireFormatLite::kDoubleSize; case FieldDescriptor::TYPE_BOOL : return WireFormatLite::kBoolSize; case FieldDescriptor::TYPE_ENUM : return -1; case FieldDescriptor::TYPE_STRING : return -1; case FieldDescriptor::TYPE_BYTES : return -1; case FieldDescriptor::TYPE_GROUP : return -1; case FieldDescriptor::TYPE_MESSAGE : return -1; // No default because we want the compiler to complain if any new // types are added. } GOOGLE_LOG(FATAL) << "Can't get here."; return -1; } void SetPrimitiveVariables(const FieldDescriptor* descriptor, map<string, string>* variables) { SetCommonFieldVariables(descriptor, variables); (*variables)["type"] = PrimitiveTypeName(descriptor->cpp_type()); (*variables)["default"] = DefaultValue(descriptor); (*variables)["tag"] = SimpleItoa(internal::WireFormat::MakeTag(descriptor)); int fixed_size = FixedSize(descriptor->type()); if (fixed_size != -1) { (*variables)["fixed_size"] = SimpleItoa(fixed_size); } (*variables)["wire_format_field_type"] = "::google::protobuf::internal::WireFormatLite::" + FieldDescriptorProto_Type_Name( static_cast<FieldDescriptorProto_Type>(descriptor->type())); } } // namespace // =================================================================== PrimitiveFieldGenerator:: PrimitiveFieldGenerator(const FieldDescriptor* descriptor) : descriptor_(descriptor) { SetPrimitiveVariables(descriptor, &variables_); } PrimitiveFieldGenerator::~PrimitiveFieldGenerator() {} void PrimitiveFieldGenerator:: GeneratePrivateMembers(io::Printer* printer) const { printer->Print(variables_, "$type$ $name$_;\n"); } void PrimitiveFieldGenerator:: GenerateAccessorDeclarations(io::Printer* printer) const { printer->Print(variables_, "inline $type$ $name$() const$deprecation$;\n" "inline void set_$name$($type$ value)$deprecation$;\n"); } void PrimitiveFieldGenerator:: GenerateInlineAccessorDefinitions(io::Printer* printer) const { printer->Print(variables_, "inline $type$ $classname$::$name$() const {\n" " return $name$_;\n" "}\n" "inline void $classname$::set_$name$($type$ value) {\n" " set_has_$name$();\n" " $name$_ = value;\n" "}\n"); } void PrimitiveFieldGenerator:: GenerateClearingCode(io::Printer* printer) const { printer->Print(variables_, "$name$_ = $default$;\n"); } void PrimitiveFieldGenerator:: GenerateMergingCode(io::Printer* printer) const { printer->Print(variables_, "set_$name$(from.$name$());\n"); } void PrimitiveFieldGenerator:: GenerateSwappingCode(io::Printer* printer) const { printer->Print(variables_, "std::swap($name$_, other->$name$_);\n"); } void PrimitiveFieldGenerator:: GenerateConstructorCode(io::Printer* printer) const { printer->Print(variables_, "$name$_ = $default$;\n"); } void PrimitiveFieldGenerator:: GenerateMergeFromCodedStream(io::Printer* printer) const { printer->Print(variables_, "DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n" " $type$, $wire_format_field_type$>(\n" " input, &$name$_)));\n" "set_has_$name$();\n"); } void PrimitiveFieldGenerator:: GenerateSerializeWithCachedSizes(io::Printer* printer) const { printer->Print(variables_, "::google::protobuf::internal::WireFormatLite::Write$declared_type$(" "$number$, this->$name$(), output);\n"); } void PrimitiveFieldGenerator:: GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { printer->Print(variables_, "target = ::google::protobuf::internal::WireFormatLite::Write$declared_type$ToArray(" "$number$, this->$name$(), target);\n"); } void PrimitiveFieldGenerator:: GenerateByteSize(io::Printer* printer) const { int fixed_size = FixedSize(descriptor_->type()); if (fixed_size == -1) { printer->Print(variables_, "total_size += $tag_size$ +\n" " ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n" " this->$name$());\n"); } else { printer->Print(variables_, "total_size += $tag_size$ + $fixed_size$;\n"); } } // =================================================================== RepeatedPrimitiveFieldGenerator:: RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor) : descriptor_(descriptor) { SetPrimitiveVariables(descriptor, &variables_); if (descriptor->options().packed()) { variables_["packed_reader"] = "ReadPackedPrimitive"; variables_["repeated_reader"] = "ReadRepeatedPrimitiveNoInline"; } else { variables_["packed_reader"] = "ReadPackedPrimitiveNoInline"; variables_["repeated_reader"] = "ReadRepeatedPrimitive"; } } RepeatedPrimitiveFieldGenerator::~RepeatedPrimitiveFieldGenerator() {} void RepeatedPrimitiveFieldGenerator:: GeneratePrivateMembers(io::Printer* printer) const { printer->Print(variables_, "::google::protobuf::RepeatedField< $type$ > $name$_;\n"); if (descriptor_->options().packed() && HasGeneratedMethods(descriptor_->file())) { printer->Print(variables_, "mutable int _$name$_cached_byte_size_;\n"); } } void RepeatedPrimitiveFieldGenerator:: GenerateAccessorDeclarations(io::Printer* printer) const { printer->Print(variables_, "inline $type$ $name$(int index) const$deprecation$;\n" "inline void set_$name$(int index, $type$ value)$deprecation$;\n" "inline void add_$name$($type$ value)$deprecation$;\n"); printer->Print(variables_, "inline const ::google::protobuf::RepeatedField< $type$ >&\n" " $name$() const$deprecation$;\n" "inline ::google::protobuf::RepeatedField< $type$ >*\n" " mutable_$name$()$deprecation$;\n"); } void RepeatedPrimitiveFieldGenerator:: GenerateInlineAccessorDefinitions(io::Printer* printer) const { printer->Print(variables_, "inline $type$ $classname$::$name$(int index) const {\n" " return $name$_.Get(index);\n" "}\n" "inline void $classname$::set_$name$(int index, $type$ value) {\n" " $name$_.Set(index, value);\n" "}\n" "inline void $classname$::add_$name$($type$ value) {\n" " $name$_.Add(value);\n" "}\n"); printer->Print(variables_, "inline const ::google::protobuf::RepeatedField< $type$ >&\n" "$classname$::$name$() const {\n" " return $name$_;\n" "}\n" "inline ::google::protobuf::RepeatedField< $type$ >*\n" "$classname$::mutable_$name$() {\n" " return &$name$_;\n" "}\n"); } void RepeatedPrimitiveFieldGenerator:: GenerateClearingCode(io::Printer* printer) const { printer->Print(variables_, "$name$_.Clear();\n"); } void RepeatedPrimitiveFieldGenerator:: GenerateMergingCode(io::Printer* printer) const { printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n"); } void RepeatedPrimitiveFieldGenerator:: GenerateSwappingCode(io::Printer* printer) const { printer->Print(variables_, "$name$_.Swap(&other->$name$_);\n"); } void RepeatedPrimitiveFieldGenerator:: GenerateConstructorCode(io::Printer* printer) const { // Not needed for repeated fields. } void RepeatedPrimitiveFieldGenerator:: GenerateMergeFromCodedStream(io::Printer* printer) const { printer->Print(variables_, "DO_((::google::protobuf::internal::WireFormatLite::$repeated_reader$<\n" " $type$, $wire_format_field_type$>(\n" " $tag_size$, $tag$, input, this->mutable_$name$())));\n"); } void RepeatedPrimitiveFieldGenerator:: GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const { printer->Print(variables_, "DO_((::google::protobuf::internal::WireFormatLite::$packed_reader$<\n" " $type$, $wire_format_field_type$>(\n" " input, this->mutable_$name$())));\n"); } void RepeatedPrimitiveFieldGenerator:: GenerateSerializeWithCachedSizes(io::Printer* printer) const { if (descriptor_->options().packed()) { // Write the tag and the size. printer->Print(variables_, "if (this->$name$_size() > 0) {\n" " ::google::protobuf::internal::WireFormatLite::WriteTag(" "$number$, " "::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, " "output);\n" " output->WriteVarint32(_$name$_cached_byte_size_);\n" "}\n"); } printer->Print(variables_, "for (int i = 0; i < this->$name$_size(); i++) {\n"); if (descriptor_->options().packed()) { printer->Print(variables_, " ::google::protobuf::internal::WireFormatLite::Write$declared_type$NoTag(\n" " this->$name$(i), output);\n"); } else { printer->Print(variables_, " ::google::protobuf::internal::WireFormatLite::Write$declared_type$(\n" " $number$, this->$name$(i), output);\n"); } printer->Print("}\n"); } void RepeatedPrimitiveFieldGenerator:: GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { if (descriptor_->options().packed()) { // Write the tag and the size. printer->Print(variables_, "if (this->$name$_size() > 0) {\n" " target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(\n" " $number$,\n" " ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n" " target);\n" " target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(\n" " _$name$_cached_byte_size_, target);\n" "}\n"); } printer->Print(variables_, "for (int i = 0; i < this->$name$_size(); i++) {\n"); if (descriptor_->options().packed()) { printer->Print(variables_, " target = ::google::protobuf::internal::WireFormatLite::\n" " Write$declared_type$NoTagToArray(this->$name$(i), target);\n"); } else { printer->Print(variables_, " target = ::google::protobuf::internal::WireFormatLite::\n" " Write$declared_type$ToArray($number$, this->$name$(i), target);\n"); } printer->Print("}\n"); } void RepeatedPrimitiveFieldGenerator:: GenerateByteSize(io::Printer* printer) const { printer->Print(variables_, "{\n" " int data_size = 0;\n"); printer->Indent(); int fixed_size = FixedSize(descriptor_->type()); if (fixed_size == -1) { printer->Print(variables_, "for (int i = 0; i < this->$name$_size(); i++) {\n" " data_size += ::google::protobuf::internal::WireFormatLite::\n" " $declared_type$Size(this->$name$(i));\n" "}\n"); } else { printer->Print(variables_, "data_size = $fixed_size$ * this->$name$_size();\n"); } if (descriptor_->options().packed()) { printer->Print(variables_, "if (data_size > 0) {\n" " total_size += $tag_size$ +\n" " ::google::protobuf::internal::WireFormatLite::Int32Size(data_size);\n" "}\n" "_$name$_cached_byte_size_ = data_size;\n" "total_size += data_size;\n"); } else { printer->Print(variables_, "total_size += $tag_size$ * this->$name$_size() + data_size;\n"); } printer->Outdent(); printer->Print("}\n"); } } // namespace cpp } // namespace compiler } // namespace protobuf } // namespace google
tst-mswartz/earthenterprise
earth_enterprise/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc
C++
apache-2.0
14,048
drop table if exists ACT_HI_IDENTITYLINK cascade;
dbmalkovsky/flowable-engine
modules/flowable-identitylink-service/src/main/resources/org/flowable/identitylink/service/db/drop/flowable.postgres.drop.identitylink.history.sql
SQL
apache-2.0
49
#include "tensorflow/core/util/work_sharder.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/lib/core/threadpool.h" #include "tensorflow/core/platform/port.h" #include "tensorflow/core/platform/test_benchmark.h" #include <gtest/gtest.h> namespace tensorflow { namespace { void RunSharding(int64 num_workers, int64 total, int64 cost_per_unit) { thread::ThreadPool threads(Env::Default(), "test", 16); mutex mu; int64 num_shards = 0; int64 num_done_work = 0; std::vector<bool> work(total, false); Shard(num_workers, &threads, total, cost_per_unit, [&mu, &num_shards, &num_done_work, &work](int start, int limit) { VLOG(1) << "Shard [" << start << "," << limit << ")"; mutex_lock l(mu); ++num_shards; for (; start < limit; ++start) { EXPECT_FALSE(work[start]); // No duplicate ++num_done_work; work[start] = true; } }); EXPECT_LE(num_shards, num_workers + 1); EXPECT_EQ(num_done_work, total); LOG(INFO) << num_workers << " " << total << " " << cost_per_unit << " " << num_shards; } TEST(Shard, Basic) { for (auto workers : {0, 1, 2, 3, 5, 7, 10, 11, 15, 100, 1000}) { for (auto total : {0, 1, 7, 10, 64, 100, 256, 1000, 9999}) { for (auto cost_per_unit : {0, 1, 11, 102, 1003, 10005, 1000007}) { RunSharding(workers, total, cost_per_unit); } } } } void BM_Sharding(int iters, int arg) { thread::ThreadPool threads(Env::Default(), "test", 16); const int64 total = 1LL << 30; auto lambda = [](int64 start, int64 limit) {}; auto work = std::cref(lambda); for (; iters > 0; iters -= arg) { Shard(arg - 1, &threads, total, 1, work); } } BENCHMARK(BM_Sharding)->Range(1, 128); } // namespace } // namespace tensorflow
liyu1990/tensorflow
tensorflow/core/util/work_sharder_test.cc
C++
apache-2.0
1,824
package org.keycloak.testsuite.sssd; import java.io.InputStream; import java.util.Arrays; import java.util.List; import javax.ws.rs.core.Response; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.jboss.arquillian.graphene.page.Page; import org.jboss.logging.Logger; import org.junit.Assume; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.keycloak.common.Profile; import org.keycloak.common.util.MultivaluedHashMap; import org.keycloak.representations.idm.ComponentRepresentation; import org.keycloak.representations.idm.GroupRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.storage.UserStorageProvider; import org.keycloak.testsuite.AbstractKeycloakTest; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.arquillian.annotation.DisableFeature; import org.keycloak.testsuite.pages.AccountPasswordPage; import org.keycloak.testsuite.pages.AccountUpdateProfilePage; import org.keycloak.testsuite.pages.LoginPage; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; @DisableFeature(value = Profile.Feature.ACCOUNT2, skipRestart = true) // TODO remove this (KEYCLOAK-16228) public class SSSDTest extends AbstractKeycloakTest { private static final Logger log = Logger.getLogger(SSSDTest.class); private static final String DISPLAY_NAME = "Test user federation"; private static final String PROVIDER_NAME = "sssd"; private static final String REALM_NAME = "test"; private static final String sssdConfigPath = "sssd/sssd.properties"; private static final String DISABLED_USER = "disabled"; private static final String NO_EMAIL_USER = "noemail"; private static final String ADMIN_USER = "admin"; private static PropertiesConfiguration sssdConfig; @Page protected LoginPage accountLoginPage; @Page protected AccountPasswordPage changePasswordPage; @Page protected AccountUpdateProfilePage profilePage; @Rule public AssertEvents events = new AssertEvents(this); private String SSSDFederationID; @Override public void addTestRealms(List<RealmRepresentation> testRealms) { RealmRepresentation realm = new RealmRepresentation(); realm.setRealm(REALM_NAME); realm.setEnabled(true); testRealms.add(realm); } @BeforeClass public static void loadSSSDConfiguration() throws ConfigurationException { log.info("Reading SSSD configuration from classpath from: " + sssdConfigPath); InputStream is = SSSDTest.class.getClassLoader().getResourceAsStream(sssdConfigPath); sssdConfig = new PropertiesConfiguration(); sssdConfig.load(is); sssdConfig.setListDelimiter(','); } @Before public void createUserFederation() { ComponentRepresentation userFederation = new ComponentRepresentation(); MultivaluedHashMap<String, String> config = new MultivaluedHashMap<>(); userFederation.setConfig(config); userFederation.setName(DISPLAY_NAME); userFederation.getConfig().putSingle("priority", "0"); userFederation.setProviderType(UserStorageProvider.class.getName()); userFederation.setProviderId(PROVIDER_NAME); Response response = adminClient.realm(REALM_NAME).components().add(userFederation); SSSDFederationID = ApiUtil.getCreatedId(response); response.close(); } @Test public void testInvalidPassword() { String username = getUsername(); log.debug("Testing invalid password for user " + username); profilePage.open(); assertThat("Browser should be on login page now", driver.getTitle(), is("Sign in to " + REALM_NAME)); accountLoginPage.login(username, "invalid-password"); assertThat(accountLoginPage.getInputError(), is("Invalid username or password.")); } @Test public void testDisabledUser() { String username = getUser(DISABLED_USER); Assume.assumeTrue("Ignoring test no disabled user configured", username != null); log.debug("Testing disabled user " + username); profilePage.open(); assertThat("Browser should be on login page now", driver.getTitle(), is("Sign in to " + REALM_NAME)); accountLoginPage.login(username, getPassword(username)); assertThat(accountLoginPage.getInputError(), is("Invalid username or password.")); } @Test public void testAdmin() { String username = getUser(ADMIN_USER); Assume.assumeTrue("Ignoring test no admin user configured", username != null); log.debug("Testing password for user " + username); profilePage.open(); assertThat("Browser should be on login page now", driver.getTitle(), is("Sign in to " + REALM_NAME)); accountLoginPage.login(username, getPassword(username)); assertThat(profilePage.isCurrent(), is(true)); } @Test public void testExistingUserLogIn() { log.debug("Testing correct password"); for (String username : getUsernames()) { profilePage.open(); assertThat("Browser should be on login page now", driver.getTitle(), is("Sign in to " + REALM_NAME)); accountLoginPage.login(username, getPassword(username)); assertThat(profilePage.isCurrent(), is(true)); verifyUserGroups(username, getGroups(username)); profilePage.logout(); } } @Test public void testExistingUserWithNoEmailLogIn() { log.debug("Testing correct password, but no e-mail provided"); String username = getUser(NO_EMAIL_USER); profilePage.open(); assertThat("Browser should be on login page now", driver.getTitle(), is("Sign in to " + REALM_NAME)); accountLoginPage.login(username, getPassword(username)); assertThat(profilePage.isCurrent(), is(true)); } @Test public void testDeleteSSSDFederationProvider() { log.debug("Testing correct password"); profilePage.open(); String username = getUsername(); assertThat("Browser should be on login page now", driver.getTitle(), is("Sign in to " + REALM_NAME)); accountLoginPage.login(username, getPassword(username)); assertThat(profilePage.isCurrent(), is(true)); verifyUserGroups(username, getGroups(username)); int componentsListSize = adminClient.realm(REALM_NAME).components().query().size(); adminClient.realm(REALM_NAME).components().component(SSSDFederationID).remove(); assertThat(adminClient.realm(REALM_NAME).components().query().size(), is(componentsListSize - 1)); } @Test public void changeReadOnlyProfile() { String username = getUsername(); profilePage.open(); accountLoginPage.login(username, getPassword(username)); assertThat(profilePage.getUsername(), is(username)); assertThat(sssdConfig.getProperty("user." + username + ".firstname"), is(profilePage.getFirstName())); assertThat(sssdConfig.getProperty("user." + username + ".lastname"), is(profilePage.getLastName())); assertThat(sssdConfig.getProperty("user." + username + ".mail"), is(profilePage.getEmail())); profilePage.updateProfile("New first", "New last", "new@email.com"); assertThat(profilePage.getError(), is("You can't update your account as it is read-only.")); } @Test public void changeReadOnlyPassword() { String username = getUsername(); changePasswordPage.open(); accountLoginPage.login(username, getPassword(username)); changePasswordPage.changePassword(getPassword(username), "new-password", "new-password"); assertThat(profilePage.getError(), is("You can't update your password as your account is read only.")); } private void verifyUserGroups(String username, List<String> groups) { List<UserRepresentation> users = adminClient.realm(REALM_NAME).users().search(username, 0, 1); assertThat("There must be at least one user", users.size(), greaterThan(0)); assertThat("Exactly our test user", users.get(0).getUsername(), is(username)); List<GroupRepresentation> assignedGroups = adminClient.realm(REALM_NAME).users().get(users.get(0).getId()).groups(); assertThat("User must have exactly " + groups.size() + " groups", assignedGroups.size(), is(groups.size())); for (GroupRepresentation group : assignedGroups) { assertThat(groups.contains(group.getName()), is(true)); } } private String getUsername() { return sssdConfig.getStringArray("usernames")[0]; } private String getUser(String type) { return sssdConfig.getString("user." + type); } private List<String> getUsernames() { return Arrays.asList(sssdConfig.getStringArray("usernames")); } private String getPassword(String username) { return sssdConfig.getString("user." + username + ".password"); } private List<String> getGroups(String username) { return Arrays.asList(sssdConfig.getStringArray("user." + username + ".groups")); } }
keycloak/keycloak
testsuite/integration-arquillian/tests/other/sssd/src/test/java/org/keycloak/testsuite/sssd/SSSDTest.java
Java
apache-2.0
9,493
//===----------------------------------------------------------------------===// // // Peloton // // tpch_workload_q1.cpp // // Identification: src/main/tpch/tpch_workload_q1.cpp // // Copyright (c) 2015-17, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "benchmark/tpch/tpch_workload.h" #include "concurrency/transaction_manager_factory.h" #include "expression/comparison_expression.h" #include "expression/conjunction_expression.h" #include "expression/constant_value_expression.h" #include "expression/operator_expression.h" #include "expression/tuple_value_expression.h" #include "planner/aggregate_plan.h" #include "planner/order_by_plan.h" #include "planner/seq_scan_plan.h" namespace peloton { namespace benchmark { namespace tpch { static constexpr int32_t _1997_01_01 = 852094800; static constexpr int32_t _1998_01_01 = 883630800; std::unique_ptr<planner::AbstractPlan> TPCHBenchmark::ConstructQ6Plan() const { auto &lineitem = db_.GetTable(TableId::Lineitem); ////////////////////////////////////////////////////////////////////////////// /// THE PREDICATE FOR THE SCAN OVER LINEITEM ////////////////////////////////////////////////////////////////////////////// auto shipdate_gte = std::unique_ptr<expression::AbstractExpression>{ new expression::ComparisonExpression( ExpressionType::COMPARE_GREATERTHANOREQUALTO, new expression::TupleValueExpression(type::TypeId::DATE, 0, 10), new expression::ConstantValueExpression( type::ValueFactory::GetDateValue(_1997_01_01)))}; auto shipdate_lt = std::unique_ptr<expression::AbstractExpression>{ new expression::ComparisonExpression( ExpressionType::COMPARE_LESSTHAN, new expression::TupleValueExpression(type::TypeId::DATE, 0, 10), new expression::ConstantValueExpression( type::ValueFactory::GetDateValue(_1998_01_01)))}; auto discount_gt = std::unique_ptr<expression::AbstractExpression>{ new expression::ComparisonExpression( ExpressionType::COMPARE_GREATERTHAN, new expression::TupleValueExpression(type::TypeId::DECIMAL, 0, 6), new expression::OperatorExpression( ExpressionType::OPERATOR_MINUS, type::TypeId::DECIMAL, new expression::ConstantValueExpression(type::ValueFactory::GetDecimalValue(0.07)), new expression::ConstantValueExpression(type::ValueFactory::GetDecimalValue(0.01)) ) ) }; auto discount_lt = std::unique_ptr<expression::AbstractExpression>{ new expression::ComparisonExpression( ExpressionType::COMPARE_LESSTHAN, new expression::TupleValueExpression(type::TypeId::DECIMAL, 0, 6), new expression::OperatorExpression( ExpressionType::OPERATOR_PLUS, type::TypeId::DECIMAL, new expression::ConstantValueExpression(type::ValueFactory::GetDecimalValue(0.07)), new expression::ConstantValueExpression(type::ValueFactory::GetDecimalValue(0.01)) ) ) }; auto quantity_lt = std::unique_ptr<expression::AbstractExpression>{ new expression::ComparisonExpression( ExpressionType::COMPARE_LESSTHAN, new expression::TupleValueExpression(type::TypeId::INTEGER, 0, 4), new expression::ConstantValueExpression(type::ValueFactory::GetIntegerValue(24)) ) }; auto lineitem_pred = std::unique_ptr<expression::AbstractExpression>{ new expression::ConjunctionExpression(ExpressionType::CONJUNCTION_AND, quantity_lt.release(), new expression::ConjunctionExpression(ExpressionType::CONJUNCTION_AND, new expression::ConjunctionExpression(ExpressionType::CONJUNCTION_AND, shipdate_gte.release(), shipdate_lt.release()), new expression::ConjunctionExpression(ExpressionType::CONJUNCTION_AND, discount_gt.release(), discount_lt.release()) ) ) }; ////////////////////////////////////////////////////////////////////////////// /// THE SCAN PLAN ////////////////////////////////////////////////////////////////////////////// // Lineitem scan auto lineitem_scan = std::unique_ptr<planner::AbstractPlan>{ new planner::SeqScanPlan(&lineitem, lineitem_pred.release(), {5,6})}; ////////////////////////////////////////////////////////////////////////////// /// THE GLOBAL AGGREGATION ////////////////////////////////////////////////////////////////////////////// // sum(l_extendedprice * l_discount) as revenue planner::AggregatePlan::AggTerm revenue_agg{ ExpressionType::AGGREGATE_SUM, new expression::OperatorExpression( ExpressionType::OPERATOR_MULTIPLY, type::TypeId::DECIMAL, new expression::TupleValueExpression(type::TypeId::DECIMAL, 0, 0), new expression::TupleValueExpression(type::TypeId::DECIMAL, 0, 1))}; revenue_agg.agg_ai.type = type::TypeId::DECIMAL; auto output_schema = std::shared_ptr<const catalog::Schema>{new catalog::Schema( {{type::TypeId::DECIMAL, kDecimalSize, "revenue"}})}; DirectMapList dml = {{0, {1, 0}}}; std::unique_ptr<const planner::ProjectInfo> agg_project{ new planner::ProjectInfo(TargetList{}, std::move(dml))}; auto agg_terms = {revenue_agg}; auto aggregation_plan = std::unique_ptr<planner::AbstractPlan>{ new planner::AggregatePlan(std::move(agg_project), nullptr, std::move(agg_terms), {}, output_schema, AggregateType::HASH)}; aggregation_plan->AddChild(std::move(lineitem_scan)); return aggregation_plan; } } // namespace tpch } // namespace benchmark } // namespace peloton
yingjunwu/peloton
src/main/tpch/tpch_workload_q6.cpp
C++
apache-2.0
5,803
// Boost.Range library // // Copyright Neil Groves 2009. Use, modification and // distribution is subject to 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) // // // For more information, see http://www.boost.org/libs/range/ // #include <boost/range/adaptor/adjacent_filtered.hpp> #include <boost/test/test_tools.hpp> #include <boost/test/unit_test.hpp> #include <boost/assign.hpp> #include <algorithm> #include <list> #include <set> #include <string> #include <vector> namespace boost { namespace { template< class Container > void adjacent_filtered_test_impl( Container& c ) { using namespace boost::adaptors; typedef BOOST_DEDUCED_TYPENAME Container::value_type value_t; // This is my preferred syntax using the | operator. std::vector< value_t > test_result1 = boost::copy_range< std::vector< value_t > >( c | adjacent_filtered(std::not_equal_to< value_t >())); // This is an alternative syntax preferred by some. std::vector< value_t > test_result2 = boost::copy_range< std::vector< value_t > >( adaptors::adjacent_filter(c, std::not_equal_to< value_t >())); // Calculate the reference result. std::vector< value_t > reference_result; typedef BOOST_DEDUCED_TYPENAME Container::const_iterator iter_t; value_t prev_v = value_t(); for (iter_t it = c.begin(); it != c.end(); ++it) { if (it == c.begin()) { reference_result.push_back(*it); } else if (*it != prev_v) { reference_result.push_back(*it); } prev_v = *it; } BOOST_CHECK_EQUAL_COLLECTIONS( reference_result.begin(), reference_result.end(), test_result1.begin(), test_result1.end() ); BOOST_CHECK_EQUAL_COLLECTIONS( reference_result.begin(), reference_result.end(), test_result2.begin(), test_result2.end() ); } template< class Collection > void adjacent_filtered_test_impl() { using namespace boost::assign; Collection c; // test empty collection adjacent_filtered_test_impl(c); // test one element; c += 1; adjacent_filtered_test_impl(c); // test many elements; c += 1,2,2,2,3,4,4,4,4,5,6,7,8,9,9; adjacent_filtered_test_impl(c); } void adjacent_filtered_test() { adjacent_filtered_test_impl< std::vector< int > >(); adjacent_filtered_test_impl< std::list< int > >(); adjacent_filtered_test_impl< std::set< int > >(); adjacent_filtered_test_impl< std::multiset< int > >(); } } } boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) { boost::unit_test::test_suite* test = BOOST_TEST_SUITE( "RangeTestSuite.adaptor.adjacent_filtered" ); test->add( BOOST_TEST_CASE( &boost::adjacent_filtered_test ) ); return test; }
flingone/frameworks_base_cmds_remoted
libs/boost/libs/range/test/adaptor_test/adjacent_filtered.cpp
C++
apache-2.0
3,662
// 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitYieldBreakStatement(BoundYieldBreakStatement node) { var result = (BoundStatement)base.VisitYieldBreakStatement(node); // We also add sequence points for the implicit "yield break" statement at the end of the method body // (added by FlowAnalysisPass.AppendImplicitReturn). Implicitly added "yield break" for async method // does not need sequence points added here since it would be done later (presumably during Async rewrite). if (this.Instrument && (!node.WasCompilerGenerated || (node.Syntax.Kind() == SyntaxKind.Block && _factory.CurrentFunction?.IsAsync == false))) { result = _instrumenter.InstrumentYieldBreakStatement(node, result); } return result; } public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node) { var result = (BoundStatement)base.VisitYieldReturnStatement(node); if (this.Instrument && !node.WasCompilerGenerated) { result = _instrumenter.InstrumentYieldReturnStatement(node, result); } return result; } } }
OmarTawfik/roslyn
src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Yield.cs
C#
apache-2.0
1,639
/* * 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.facebook.presto.hive.util; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.Executor; import java.util.function.Function; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.util.concurrent.Futures.immediateFuture; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import static java.util.Objects.requireNonNull; @ThreadSafe public class AsyncQueue<T> { private final int targetQueueSize; @GuardedBy("this") private Queue<T> elements; // This future is completed when the queue transitions from full to not. But it will be replaced by a new instance of future immediately. @GuardedBy("this") private SettableFuture<?> notFullSignal = SettableFuture.create(); // This future is completed when the queue transitions from empty to not. But it will be replaced by a new instance of future immediately. @GuardedBy("this") private SettableFuture<?> notEmptySignal = SettableFuture.create(); @GuardedBy("this") private boolean finishing; @GuardedBy("this") private int borrowerCount; private final Executor executor; public AsyncQueue(int targetQueueSize, Executor executor) { checkArgument(targetQueueSize >= 1, "targetQueueSize must be at least 1"); this.targetQueueSize = targetQueueSize; this.elements = new ArrayDeque<>(targetQueueSize * 2); this.executor = requireNonNull(executor); } /** * Returns <tt>true</tt> if all future attempts to retrieve elements from this queue * are guaranteed to return empty. */ public synchronized boolean isFinished() { return finishing && borrowerCount == 0 && elements.size() == 0; } public synchronized void finish() { if (finishing) { return; } finishing = true; signalIfFinishing(); } private synchronized void signalIfFinishing() { if (finishing && borrowerCount == 0) { if (elements.size() == 0) { // Reset elements queue after finishing to avoid holding on to the full sized empty array inside elements = new ArrayDeque<>(0); completeAsync(executor, notEmptySignal); notEmptySignal = SettableFuture.create(); } else if (elements.size() >= targetQueueSize) { completeAsync(executor, notFullSignal); notFullSignal = SettableFuture.create(); } } } public synchronized ListenableFuture<?> offer(T element) { requireNonNull(element); if (finishing && borrowerCount == 0) { return immediateFuture(null); } elements.add(element); int newSize = elements.size(); if (newSize == 1) { completeAsync(executor, notEmptySignal); notEmptySignal = SettableFuture.create(); } if (newSize >= targetQueueSize) { return notFullSignal; } return immediateFuture(null); } private synchronized List<T> getBatch(int maxSize) { int oldSize = elements.size(); int reduceBy = Math.min(maxSize, oldSize); if (reduceBy == 0) { return ImmutableList.of(); } List<T> result = new ArrayList<>(reduceBy); for (int i = 0; i < reduceBy; i++) { result.add(elements.remove()); } // This checks that the queue size changed from above threshold to below. Therefore, writers shall be notified. if (oldSize >= targetQueueSize && oldSize - reduceBy < targetQueueSize) { completeAsync(executor, notFullSignal); notFullSignal = SettableFuture.create(); } return result; } public synchronized ListenableFuture<List<T>> getBatchAsync(int maxSize) { return borrowBatchAsync(maxSize, elements -> new BorrowResult<>(ImmutableList.of(), elements)); } /** * Invoke {@code function} with up to {@code maxSize} elements removed from the head of the queue, * and insert elements in the return value to the tail of the queue. * <p> * If no element is currently available, invocation of {@code function} will be deferred until some * element is available, or no more elements will be. Spurious invocation of {@code function} is * possible. * <p> * Insertion through return value of {@code function} will be effective even if {@link #finish()} has been invoked. * When borrow (of a non-empty list) is ongoing, {@link #isFinished()} will return false. * If an empty list is supplied to {@code function}, it must not return a result indicating intention * to insert elements into the queue. */ public <O> ListenableFuture<O> borrowBatchAsync(int maxSize, Function<List<T>, BorrowResult<T, O>> function) { checkArgument(maxSize >= 0, "maxSize must be at least 0"); ListenableFuture<List<T>> borrowedListFuture; synchronized (this) { List<T> list = getBatch(maxSize); if (!list.isEmpty()) { borrowedListFuture = immediateFuture(list); borrowerCount++; } else if (finishing && borrowerCount == 0) { borrowedListFuture = immediateFuture(ImmutableList.of()); } else { borrowedListFuture = Futures.transform( notEmptySignal, ignored -> { synchronized (this) { List<T> batch = getBatch(maxSize); if (!batch.isEmpty()) { borrowerCount++; } return batch; } }, executor); } } return Futures.transform( borrowedListFuture, elements -> { // The borrowerCount field was only incremented for non-empty lists. // Decrements should only happen for non-empty lists. // When it should, it must always happen even if the caller-supplied function throws. try { BorrowResult<T, O> borrowResult = function.apply(elements); if (elements.isEmpty()) { checkArgument(borrowResult.getElementsToInsert().isEmpty(), "Function must not insert anything when no element is borrowed"); return borrowResult.getResult(); } for (T element : borrowResult.getElementsToInsert()) { offer(element); } return borrowResult.getResult(); } finally { if (!elements.isEmpty()) { synchronized (this) { borrowerCount--; signalIfFinishing(); } } } }, directExecutor()); } private static void completeAsync(Executor executor, SettableFuture<?> future) { executor.execute(() -> future.set(null)); } public static final class BorrowResult<T, R> { private final List<T> elementsToInsert; private final R result; public BorrowResult(List<T> elementsToInsert, R result) { this.elementsToInsert = ImmutableList.copyOf(elementsToInsert); this.result = result; } public List<T> getElementsToInsert() { return elementsToInsert; } public R getResult() { return result; } } }
facebook/presto
presto-hive/src/main/java/com/facebook/presto/hive/util/AsyncQueue.java
Java
apache-2.0
8,963
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.aggregations.bucket; /** * A bucket aggregator that doesn't create new buckets. */ public interface SingleBucketAggregator { }
gingerwizard/elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/bucket/SingleBucketAggregator.java
Java
apache-2.0
952
> 编写:[jdneo](https://github.com/jdneo) > 校对: # 创建Stub授权器 Sync Adapter框架假定你的Sync Adapter在同步数据时,设备存储会有一个账户,服务器存储端会有登录验证。因此,框架期望你提供一个叫做授权器的组件作为你的Sync Adapter的一部分。该组件会植入Android账户及认证框架,并提供一个标准的接口来处理用户凭据,比如登录信息。 甚至,如果你的应用不使用账户,你仍然需要提供一个授权器组件。如果你不使用账户或者服务器登录,授权器所处理的信息将被忽略,所以你可以提供一个授权器组件,它包括了一个“空”的实现(译者注:也即标题中的Stub)。同时你需要提供一个捆绑的[Service](http://developer.android.com/reference/android/app/Service.html),来允许Sync Adapter框架来调用授权器的方法。 这节课将向你展示如何定义一个Stub授权器的所有满足其实现要求的部件。如果你想要提供一个真实的处理用户账户的授权器,可以阅读:[AbstractAccountAuthenticator](http://developer.android.com/reference/android/accounts/AbstractAccountAuthenticator.html)。 ## 添加一个Stub授权器组件 要在你的应用中添加一个Stub授权器,创建一个继承[AbstractAccountAuthenticator](http://developer.android.com/reference/android/accounts/AbstractAccountAuthenticator.html)的类,并将要覆写的方法置空(这样就不会做任何处理了),返回null或者抛出异常。 下面的代码片段是一个Stub授权器的例子: ```java /* * Implement AbstractAccountAuthenticator and stub out all * of its methods */ public class Authenticator extends AbstractAccountAuthenticator { // Simple constructor public Authenticator(Context context) { super(context); } // Editing properties is not supported @Override public Bundle editProperties( AccountAuthenticatorResponse r, String s) { throw new UnsupportedOperationException(); } // Don't add additional accounts @Override public Bundle addAccount( AccountAuthenticatorResponse r, String s, String s2, String[] strings, Bundle bundle) throws NetworkErrorException { return null; } // Ignore attempts to confirm credentials @Override public Bundle confirmCredentials( AccountAuthenticatorResponse r, Account account, Bundle bundle) throws NetworkErrorException { return null; } // Getting an authentication token is not supported @Override public Bundle getAuthToken( AccountAuthenticatorResponse r, Account account, String s, Bundle bundle) throws NetworkErrorException { throw new UnsupportedOperationException(); } // Getting a label for the auth token is not supported @Override public String getAuthTokenLabel(String s) { throw new UnsupportedOperationException(); } // Updating user credentials is not supported @Override public Bundle updateCredentials( AccountAuthenticatorResponse r, Account account, String s, Bundle bundle) throws NetworkErrorException { throw new UnsupportedOperationException(); } // Checking features for the account is not supported @Override public Bundle hasFeatures( AccountAuthenticatorResponse r, Account account, String[] strings) throws NetworkErrorException { throw new UnsupportedOperationException(); } } ``` ## 将授权器绑定到框架 为了让Sync Adapter框架可以访问你的授权器,你必须为它创建一个捆绑服务。这一服务提供一个Android binder对象,允许框架调用你的授权器,并且在授权器和框架间传输数据。 因为框架会在它第一次访问授权器时启动[Service](http://developer.android.com/reference/android/app/Service.html),你也可以使用服务来实例化授权器,方法是通过在服务的[Service.onCreate()](http://developer.android.com/reference/android/app/Service.html#onCreate\(\))方法中调用授权器的构造函数。 下面的代码样例展示了如何定义绑定[Service](http://developer.android.com/reference/android/app/Service.html): ```java /** * A bound Service that instantiates the authenticator * when started. */ public class AuthenticatorService extends Service { ... // Instance field that stores the authenticator object private Authenticator mAuthenticator; @Override public void onCreate() { // Create a new authenticator object mAuthenticator = new Authenticator(this); } /* * When the system binds to this Service to make the RPC call * return the authenticator's IBinder. */ @Override public IBinder onBind(Intent intent) { return mAuthenticator.getIBinder(); } } ``` ## 添加授权器的元数据文件 要将你的授权器组件插入到Sync Adapter和账户框架中,你需要为框架提供带有描述组件的元数据。该元数据声明了你创建的Sync Adapter的账户类型以及系统所显示的用户接口元素(如果你希望将你的账户类型对用户可见)。在你的项目目录:“/res/xml/”下,将元数据声明于一个XML文件中。你可以随便为它起一个名字,一般来说,可以叫“authenticator.xml” 在这个XML文件中,包含单个元素`<account-authenticator>`,它有下列一些属性: **android:accountType** Sync Adapter框架需要每一个适配器以域名的形式拥有一个账户类型。框架会将它作为其内部的标识。对于需要登录的服务器,账户类型会和账户一起发送到服务端作为登录凭据的一部分。 如果你的服务不需要登录,你仍然需要提供一个账户类型。值的话就用你能控制的一个域名即可。由于框架会使用它来管理Sync Adapter,所以值不会发送到服务器上。 **android:icon** 指向一个包含一个图标的[Drawable](http://developer.android.com/guide/topics/resources/drawable-resource.html)资源的指针。如果你在“res/xml/syncadapter.xml”中通过指定android:userVisible="true"让Sync Adapter可见,那么你必须提供图标资源。它会在系统的设置中的账户这一栏内显示。 **android:smallIcon** 指向一个包含一个微小版本图标的[Drawable](http://developer.android.com/guide/topics/resources/drawable-resource.html)资源的指针。结合具体的屏幕大小,这一资源可能会替代“android:icon”中所指定的图标资源。 **android:label** 将指明了用户账户类型的string本地化。如果你在“res/xml/syncadapter.xml”中通过指定android:userVisible="true"让Sync Adapter可见,那么你需要提供这个string。它会在系统的设置中的账户这一栏内显示,就在你定义的图标旁边。 下面的代码样例展示了你之前为授权器创建的XML文件: ```xml <?xml version="1.0" encoding="utf-8"?> <account-authenticator xmlns:android="http://schemas.android.com/apk/res/android" android:accountType="example.com" android:icon="@drawable/ic_launcher" android:smallIcon="@drawable/ic_launcher" android:label="@string/app_name"/> ``` ## 在清单文件中声明授权器 在之前的步骤中,你创建了一个捆绑服务,将授权器和Sync Adapter框架连接起来。要标识这个服务,你需要再清单文件中添加[`<service>`](http://developer.android.com/guide/topics/manifest/service-element.html)标签,将它作为[`<application>`](http://developer.android.com/guide/topics/manifest/application-element.html)的子标签: ```xml <service android:name="com.example.android.syncadapter.AuthenticatorService"> <intent-filter> <action android:name="android.accounts.AccountAuthenticator"/> </intent-filter> <meta-data android:name="android.accounts.AccountAuthenticator" android:resource="@xml/authenticator" /> </service> ``` 标签[`<intent-filter>`](http://developer.android.com/guide/topics/manifest/intent-filter-element.html)配置了一个由android.accounts.AccountAuthenticator的intent所激活的过滤器,这一intent会在系统要运行授权器时由系统发出。当过滤器被激活,系统会启动AuthenticatorService,它是你之前用来封装授权器的捆绑[Service](http://developer.android.com/reference/android/app/Service.html)。 [`<meta-data>`](http://developer.android.com/guide/topics/manifest/meta-data-element.html)标签声明了授权器的元数据。[android:name](http://developer.android.com/guide/topics/manifest/meta-data-element.html#nm)属性将元数据和授权器框架连接起来。[android:resource](http://developer.android.com/guide/topics/manifest/meta-data-element.html#rsrc)指定了你之前所创建的授权器元数据文件的名字。 除了一个授权器,一个Sync Adapter框架需要一个内容提供器(content provider)。如果你的应用不适用内容提供器,可以阅读下一节课程,在下节课中将会创建一个空的内容提供器;如果你的应用适用的话,可以直接阅读:[Creating a Sync Adapter](除了一个授权器,一个Sync Adapter框架需要一个内容提供器(content provider)。如果你的应用不适用内容提供器,可以阅读下一节课程,在下节课中将会创建一个空的内容提供器;如果你的应用适用的话,可以直接阅读:[创建Sync Adapter](creating-sync-adapter.html)。
lord19871207/android-training-course-in-chinese
connectivity/sync-adapters/create-authenticator.md
Markdown
apache-2.0
9,807
--- layout: "docs_api" version: "1.0.1" versionHref: "/docs" path: "api/utility/ionic.EventController/" title: "ionic.EventController" header_sub_title: "Utility in module ionic" doc: "ionic.EventController" docType: "utility" --- <div class="improve-docs"> <a href='http://github.com/driftyco/ionic/tree/master/js/utils/events.js#L44'> View Source </a> &nbsp; <a href='http://github.com/driftyco/ionic/edit/master/js/utils/events.js#L44'> Improve this doc </a> </div> <h1 class="api-title"> ionic.EventController </h1> ## Methods <div id="trigger"></div> <h2> <code>trigger(eventType, data, [bubbles], [cancelable])</code><small>(alias: ionic.trigger)</small> </h2> <table class="table" style="margin:0;"> <thead> <tr> <th>Param</th> <th>Type</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td> eventType </td> <td> <code>string</code> </td> <td> <p>The event to trigger.</p> </td> </tr> <tr> <td> data </td> <td> <code>object</code> </td> <td> <p>The data for the event. Hint: pass in <code>{target: targetElement}</code></p> </td> </tr> <tr> <td> bubbles <div><em>(optional)</em></div> </td> <td> <code>boolean</code> </td> <td> <p>Whether the event should bubble up the DOM.</p> </td> </tr> <tr> <td> cancelable <div><em>(optional)</em></div> </td> <td> <code>boolean</code> </td> <td> <p>Whether the event should be cancelable.</p> </td> </tr> </tbody> </table> <div id="on"></div> <h2> <code>on(type, callback, element)</code><small>(alias: ionic.on)</small> </h2> Listen to an event on an element. <table class="table" style="margin:0;"> <thead> <tr> <th>Param</th> <th>Type</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td> type </td> <td> <code>string</code> </td> <td> <p>The event to listen for.</p> </td> </tr> <tr> <td> callback </td> <td> <code>function</code> </td> <td> <p>The listener to be called.</p> </td> </tr> <tr> <td> element </td> <td> <code>DOMElement</code> </td> <td> <p>The element to listen for the event on.</p> </td> </tr> </tbody> </table> <div id="off"></div> <h2> <code>off(type, callback, element)</code><small>(alias: ionic.off)</small> </h2> Remove an event listener. <table class="table" style="margin:0;"> <thead> <tr> <th>Param</th> <th>Type</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td> type </td> <td> <code>string</code> </td> <td> </td> </tr> <tr> <td> callback </td> <td> <code>function</code> </td> <td> </td> </tr> <tr> <td> element </td> <td> <code>DOMElement</code> </td> <td> </td> </tr> </tbody> </table> <div id="onGesture"></div> <h2> <code>onGesture(eventType, callback, element, options)</code><small>(alias: ionic.onGesture)</small> </h2> Add an event listener for a gesture on an element. Available eventTypes (from [hammer.js](http://eightmedia.github.io/hammer.js/)): `hold`, `tap`, `doubletap`, `drag`, `dragstart`, `dragend`, `dragup`, `dragdown`, <br/> `dragleft`, `dragright`, `swipe`, `swipeup`, `swipedown`, `swipeleft`, `swiperight`, <br/> `transform`, `transformstart`, `transformend`, `rotate`, `pinch`, `pinchin`, `pinchout`, </br> `touch`, `release` <table class="table" style="margin:0;"> <thead> <tr> <th>Param</th> <th>Type</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td> eventType </td> <td> <code>string</code> </td> <td> <p>The gesture event to listen for.</p> </td> </tr> <tr> <td> callback </td> <td> <code>function(e)</code> </td> <td> <p>The function to call when the gesture happens.</p> </td> </tr> <tr> <td> element </td> <td> <code>DOMElement</code> </td> <td> <p>The angular element to listen for the event on.</p> </td> </tr> <tr> <td> options </td> <td> <code>object</code> </td> <td> <p>object.</p> </td> </tr> </tbody> </table> * Returns: <code>ionic.Gesture</code> The gesture object (use this to remove the gesture later on). <div id="offGesture"></div> <h2> <code>offGesture(gesture, eventType, callback)</code><small>(alias: ionic.offGesture)</small> </h2> Remove an event listener for a gesture created on an element. <table class="table" style="margin:0;"> <thead> <tr> <th>Param</th> <th>Type</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td> gesture </td> <td> <code>ionic.Gesture</code> </td> <td> <p>The gesture that should be removed.</p> </td> </tr> <tr> <td> eventType </td> <td> <code>string</code> </td> <td> <p>The gesture event to remove the listener for.</p> </td> </tr> <tr> <td> callback </td> <td> <code>function(e)</code> </td> <td> <p>The listener to remove.</p> </td> </tr> </tbody> </table>
thiagofelix/ionic-site
docs/api/utility/ionic.EventController/index.md
Markdown
apache-2.0
6,548
/*eslint curly:0, no-redeclare:0, quotes:0 */ /*jshint ignore:start */ /*eslint-disable */ global.DEFINE_MODULE('path', (function () { 'use strict' /*eslint-enable */ const module = {}; const isWindows = require('internal').platform.substr(0, 3) === 'win'; function assertPath (path) { if (typeof path !== 'string') { throw new TypeError(`Path must be a string. Received ${path}`); } } // Copyright Node.js contributors. All rights reserved. // // 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. // resolves . and .. elements in a path array with directory names there // must be no slashes or device names (c:\) in the array // (so also no leading and trailing slashes - it does not distinguish // relative and absolute paths) function normalizeArray (parts, allowAboveRoot) { var res = []; for (var i = 0; i < parts.length; i++) { var p = parts[i]; // ignore empty parts if (!p || p === '.') continue; if (p === '..') { if (res.length && res[res.length - 1] !== '..') { res.pop(); } else if (allowAboveRoot) { res.push('..'); } } else { res.push(p); } } return res; } // Returns an array with empty elements removed from either end of the input // array or the original array if no elements need to be removed function trimArray (arr) { var lastIndex = arr.length - 1; var start = 0; for (; start <= lastIndex; start++) { if (arr[start]) break; } var end = lastIndex; for (; end >= 0; end--) { if (arr[end]) break; } if (start === 0 && end === lastIndex) return arr; if (start > end) return []; return arr.slice(start, end + 1); } // Regex to split a windows path into three parts: [*, device, slash, // tail] windows-only const splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; // Regex to split the tail part of the above into [*, dir, basename, ext] const splitTailRe = /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/; var win32 = {}; // Function to split a filename into [root, dir, basename, ext] function win32SplitPath (filename) { // Separate device+slash from tail var result = splitDeviceRe.exec(filename), device = (result[1] || '') + (result[2] || ''), tail = result[3]; // Split the tail into dir, basename and extension var result2 = splitTailRe.exec(tail), dir = result2[1], basename = result2[2], ext = result2[3]; return [device, dir, basename, ext]; } function win32StatPath (path) { var result = splitDeviceRe.exec(path), device = result[1] || '', isUnc = !!device && device[1] !== ':'; return { device, isUnc, isAbsolute: isUnc || !!result[2], // UNC paths are always absolute tail: result[3] }; } function normalizeUNCRoot (device) { return '\\\\' + device.replace(/^[\\\/]+/, '').replace(/[\\\/]+/g, '\\'); } // path.resolve([from ...], to) win32.resolve = function () { var resolvedDevice = '', resolvedTail = '', resolvedAbsolute = false; for (var i = arguments.length - 1; i >= -1; i--) { var path; if (i >= 0) { path = arguments[i]; } else if (!resolvedDevice) { path = process.cwd(); } else { // Windows has the concept of drive-specific current working // directories. If we've resolved a drive letter but not yet an // absolute path, get cwd for that drive. We're sure the device is not // an unc path at this points, because unc paths are always absolute. path = process.env['=' + resolvedDevice]; // Verify that a drive-local cwd was found and that it actually points // to our drive. If not, default to the drive's root. if (!path || path.substr(0, 3).toLowerCase() !== resolvedDevice.toLowerCase() + '\\') { path = resolvedDevice + '\\'; } } assertPath(path); // Skip empty entries if (path === '') { continue; } var result = win32StatPath(path), device = result.device, isUnc = result.isUnc, isAbsolute = result.isAbsolute, tail = result.tail; if (device && resolvedDevice && device.toLowerCase() !== resolvedDevice.toLowerCase()) { // This path points to another device so it is not applicable continue; } if (!resolvedDevice) { resolvedDevice = device; } if (!resolvedAbsolute) { resolvedTail = tail + '\\' + resolvedTail; resolvedAbsolute = isAbsolute; } if (resolvedDevice && resolvedAbsolute) { break; } } // Convert slashes to backslashes when `resolvedDevice` points to an UNC // root. Also squash multiple slashes into a single one where appropriate. if (isUnc) { resolvedDevice = normalizeUNCRoot(resolvedDevice); } // At this point the path should be resolved to a full absolute path, // but handle relative paths to be safe (might happen when process.cwd() // fails) // Normalize the tail path resolvedTail = normalizeArray(resolvedTail.split(/[\\\/]+/), !resolvedAbsolute).join('\\'); return (resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail) || '.'; }; win32.normalize = function (path) { assertPath(path); var result = win32StatPath(path), device = result.device, isUnc = result.isUnc, isAbsolute = result.isAbsolute, tail = result.tail, trailingSlash = /[\\\/]$/.test(tail); // Normalize the tail path tail = normalizeArray(tail.split(/[\\\/]+/), !isAbsolute).join('\\'); if (!tail && !isAbsolute) { tail = '.'; } if (tail && trailingSlash) { tail += '\\'; } // Convert slashes to backslashes when `device` points to an UNC root. // Also squash multiple slashes into a single one where appropriate. if (isUnc) { device = normalizeUNCRoot(device); } return device + (isAbsolute ? '\\' : '') + tail; }; win32.isAbsolute = function (path) { assertPath(path); return win32StatPath(path).isAbsolute; }; win32.join = function () { var paths = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; assertPath(arg); if (arg) { paths.push(arg); } } var joined = paths.join('\\'); // Make sure that the joined path doesn't start with two slashes, because // normalize() will mistake it for an UNC path then. // // This step is skipped when it is very clear that the user actually // intended to point at an UNC path. This is assumed when the first // non-empty string arguments starts with exactly two slashes followed by // at least one more non-slash character. // // Note that for normalize() to treat a path as an UNC path it needs to // have at least 2 components, so we don't filter for that here. // This means that the user can use join to construct UNC paths from // a server name and a share name; for example: // path.join('//server', 'share') -> '\\\\server\\share\') if (!/^[\\\/]{2}[^\\\/]/.test(paths[0])) { joined = joined.replace(/^[\\\/]{2,}/, '\\'); } return win32.normalize(joined); }; // path.relative(from, to) // it will solve the relative path from 'from' to 'to', for instance: // from = 'C:\\orandea\\test\\aaa' // to = 'C:\\orandea\\impl\\bbb' // The output of the function should be: '..\\..\\impl\\bbb' win32.relative = function (from, to) { assertPath(from); assertPath(to); from = win32.resolve(from); to = win32.resolve(to); // windows is not case sensitive var lowerFrom = from.toLowerCase(); var lowerTo = to.toLowerCase(); var toParts = trimArray(to.split('\\')); var lowerFromParts = trimArray(lowerFrom.split('\\')); var lowerToParts = trimArray(lowerTo.split('\\')); var length = Math.min(lowerFromParts.length, lowerToParts.length); var samePartsLength = length; for (var i = 0; i < length; i++) { if (lowerFromParts[i] !== lowerToParts[i]) { samePartsLength = i; break; } } if (samePartsLength === 0) { return to; } var outputParts = []; for (var i = samePartsLength; i < lowerFromParts.length; i++) { outputParts.push('..'); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('\\'); }; win32._makeLong = function (path) { return path; // UNC path building is currently deactivated. // The reason is that the internal file access functions cannot handle // UNC names at all. They would need to be changed to use the special // Windows wide-char file system function variants. /* // Note: this will *probably* throw somewhere. if (typeof path !== 'string') return path if (!path) { return '' } var resolvedPath = win32.resolve(path) if (/^[a-zA-Z]\:\\/.test(resolvedPath)) { // path is local filesystem path, which needs to be converted // to long UNC path. return '\\\\?\\' + resolvedPath } else if (/^\\\\[^?.]/.test(resolvedPath)) { // path is network UNC path, which needs to be converted // to long UNC path. return '\\\\?\\UNC\\' + resolvedPath.substring(2) } return path */ }; win32.dirname = function (path) { var result = win32SplitPath(path), root = result[0], dir = result[1]; if (!root && !dir) { // No dirname whatsoever return '.'; } if (dir) { // It has a dirname, strip trailing slash dir = dir.substr(0, dir.length - 1); } return root + dir; }; win32.basename = function (path, ext) { if (ext !== undefined && typeof ext !== 'string') throw new TypeError('ext must be a string'); var f = win32SplitPath(path)[2]; // TODO: make this comparison case-insensitive on windows? if (ext && f.substr(-1 * ext.length) === ext) { f = f.substr(0, f.length - ext.length); } return f; }; win32.extname = function (path) { return win32SplitPath(path)[3]; }; win32.format = function (pathObject) { if (pathObject === null || typeof pathObject !== 'object') { throw new TypeError( "Parameter 'pathObject' must be an object, not " + typeof pathObject ); } var root = pathObject.root || ''; if (typeof root !== 'string') { throw new TypeError( "'pathObject.root' must be a string or undefined, not " + typeof pathObject.root ); } var dir = pathObject.dir; var base = pathObject.base || ''; if (!dir) { return base; } if (dir[dir.length - 1] === win32.sep) { return dir + base; } return dir + win32.sep + base; }; win32.parse = function (pathString) { assertPath(pathString); var allParts = win32SplitPath(pathString); return { root: allParts[0], dir: allParts[0] + allParts[1].slice(0, -1), base: allParts[2], ext: allParts[3], name: allParts[2].slice(0, allParts[2].length - allParts[3].length) }; }; win32.sep = '\\'; win32.delimiter = ';'; // Split a filename into [root, dir, basename, ext], unix version // 'root' is just a slash, or nothing. const splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; var posix = {}; function posixSplitPath (filename) { return splitPathRe.exec(filename).slice(1); } // path.resolve([from ...], to) // posix version posix.resolve = function () { var resolvedPath = '', resolvedAbsolute = false; for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { var path = (i >= 0) ? arguments[i] : process.cwd(); assertPath(path); // Skip empty entries if (path === '') { continue; } resolvedPath = path + '/' + resolvedPath; resolvedAbsolute = path[0] === '/'; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeArray(resolvedPath.split('/'), !resolvedAbsolute).join('/'); return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; }; // path.normalize(path) // posix version posix.normalize = function (path) { assertPath(path); var isAbsolute = posix.isAbsolute(path), trailingSlash = path && path[path.length - 1] === '/'; // Normalize the path path = normalizeArray(path.split('/'), !isAbsolute).join('/'); if (!path && !isAbsolute) { path = '.'; } if (path && trailingSlash) { path += '/'; } return (isAbsolute ? '/' : '') + path; }; // posix version posix.isAbsolute = function (path) { assertPath(path); return !!path && path[0] === '/'; }; // posix version posix.join = function () { var path = ''; for (var i = 0; i < arguments.length; i++) { var segment = arguments[i]; assertPath(segment); if (segment) { if (!path) { path += segment; } else { path += '/' + segment; } } } return posix.normalize(path); }; // path.relative(from, to) // posix version posix.relative = function (from, to) { assertPath(from); assertPath(to); from = posix.resolve(from).substr(1); to = posix.resolve(to).substr(1); var fromParts = trimArray(from.split('/')); var toParts = trimArray(to.split('/')); var length = Math.min(fromParts.length, toParts.length); var samePartsLength = length; for (var i = 0; i < length; i++) { if (fromParts[i] !== toParts[i]) { samePartsLength = i; break; } } var outputParts = []; for (var i = samePartsLength; i < fromParts.length; i++) { outputParts.push('..'); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('/'); }; posix._makeLong = function (path) { return path; }; posix.dirname = function (path) { var result = posixSplitPath(path), root = result[0], dir = result[1]; if (!root && !dir) { // No dirname whatsoever return '.'; } if (dir) { // It has a dirname, strip trailing slash dir = dir.substr(0, dir.length - 1); } return root + dir; }; posix.basename = function (path, ext) { if (ext !== undefined && typeof ext !== 'string') throw new TypeError('ext must be a string'); var f = posixSplitPath(path)[2]; if (ext && f.substr(-1 * ext.length) === ext) { f = f.substr(0, f.length - ext.length); } return f; }; posix.extname = function (path) { return posixSplitPath(path)[3]; }; posix.format = function (pathObject) { if (pathObject === null || typeof pathObject !== 'object') { throw new TypeError( "Parameter 'pathObject' must be an object, not " + typeof pathObject ); } var root = pathObject.root || ''; if (typeof root !== 'string') { throw new TypeError( "'pathObject.root' must be a string or undefined, not " + typeof pathObject.root ); } var dir = pathObject.dir ? pathObject.dir + posix.sep : ''; var base = pathObject.base || ''; return dir + base; }; posix.parse = function (pathString) { assertPath(pathString); var allParts = posixSplitPath(pathString); return { root: allParts[0], dir: allParts[0] + allParts[1].slice(0, -1), base: allParts[2], ext: allParts[3], name: allParts[2].slice(0, allParts[2].length - allParts[3].length) }; }; posix.sep = '/'; posix.delimiter = ':'; if (isWindows) module.exports = win32; else /* posix */ module.exports = posix; module.exports.posix = posix; module.exports.win32 = win32; return module.exports; }()));
arangodb/arangodb
js/common/bootstrap/modules/path.js
JavaScript
apache-2.0
17,346
.btn-up-1{ background: #999;} .btn-up-1 .fa{ background: #fff; color: #999;} .navPop-1 .navPop-btn{ background: #999;} .navPop-1 .navPop-btn .fa{ background: #fff; color: #999;} .navPop-wrap>div a{ background: #999; color: #fff; }
royalwang/saivi
tpl/static/tpl/1117/css/index36.css
CSS
apache-2.0
241
/* * 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.accumulo.monitor.util; /** * Simple utility class to validate Accumulo Monitor Query and Path parameters */ public interface ParameterValidator { String ALPHA_NUM_REGEX = "\\w+"; // Allow the special default table IDs String ALPHA_NUM_REGEX_TABLE_ID = "[!+]?\\w+"; String ALPHA_NUM_REGEX_BLANK_OK = "\\w*"; String PROBLEM_TYPE_REGEX = "FILE_READ|FILE_WRITE|TABLET_LOAD"; String RESOURCE_REGEX = "(?:)(.*)"; // host name and port String HOSTNAME_PORT_REGEX = "[a-zA-Z0-9.-]+:[0-9]{2,5}"; }
milleruntime/accumulo
server/monitor/src/main/java/org/apache/accumulo/monitor/util/ParameterValidator.java
Java
apache-2.0
1,336
/* * 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.drill.exec.store; import org.apache.drill.exec.record.VectorAccessible; import java.io.IOException; import java.util.Map; public interface StatisticsRecordWriter extends StatisticsRecordCollector { /** * Initialize the writer. * * @param writerOptions Contains key, value pair of settings. * @throws IOException */ void init(Map<String, String> writerOptions); /** * Update the schema in RecordWriter. Called at least once before starting writing the records. * @param batch * @throws IOException */ void updateSchema(VectorAccessible batch); /** * Check if the writer should start a new partition, and if so, start a new partition */ public void checkForNewPartition(int index); /** * Returns if the writer is a blocking writer i.e. consumes all input before writing it out * @return TRUE, if writer is blocking. FALSE, otherwise */ boolean isBlockingWriter(); /** * For a blocking writer, called after processing all the records to flush out the writes * @throws IOException */ void flushBlockingWriter() throws IOException; void abort(); void cleanup(); }
apache/drill
exec/java-exec/src/main/java/org/apache/drill/exec/store/StatisticsRecordWriter.java
Java
apache-2.0
1,963
import unittest, time, sys, random, math, getpass sys.path.extend(['.','..','../..','py']) import h2o, h2o_cmd, h2o_import as h2i, h2o_util, h2o_browse as h2b, h2o_print as h2p import h2o_summ DO_TRY_SCIPY = False if getpass.getuser()=='kevin' or getpass.getuser()=='jenkins': DO_TRY_SCIPY = True DO_MEDIAN = True # FIX!. we seem to lose accuracy with fewer bins -> more iterations. Maybe we're leaking or ?? # this test failed (if run as user kevin) with 10 bins MAX_QBINS = 1000 # pass MAX_QBINS = 1000 # pass # this one doesn't fail with 10 bins # this failed. interestingly got same number as 1000 bin summary2 (the 7.433.. # on runifA.csv (2nd col?) # MAX_QBINS = 20 # Exception: h2o quantile multipass is not approx. same as sort algo. h2o_util.assertApproxEqual failed comparing 7.43337413296 and 8.26268245. {'tol': 2e-07}. MAX_QBINS = 27 class Basic(unittest.TestCase): def tearDown(self): h2o.check_sandbox_for_errors() @classmethod def setUpClass(cls): global SEED SEED = h2o.setup_random_seed() h2o.init() @classmethod def tearDownClass(cls): # h2o.sleep(3600) h2o.tear_down_cloud() def test_summary2_unifiles(self): SYNDATASETS_DIR = h2o.make_syn_dir() # new with 1000 bins. copy expected from R tryList = [ ('cars.csv', 'c.hex', [ (None, None,None,None,None,None), ('economy (mpg)', None,None,None,None,None), ('cylinders', None,None,None,None,None), ], ), ('runifA.csv', 'A.hex', [ (None, 1.00, 25.00, 50.00, 75.00, 100.0), ('x', -99.9, -44.7, 8.26, 58.00, 91.7), ], ), # colname, (min, 25th, 50th, 75th, max) ('runif.csv', 'x.hex', [ (None, 1.00, 5000.0, 10000.0, 15000.0, 20000.00), ('D', -5000.00, -3735.0, -2443, -1187.0, 99.8), ('E', -100000.0, -49208.0, 1783.8, 50621.9, 100000.0), ('F', -1.00, -0.4886, 0.00868, 0.5048, 1.00), ], ), ('runifB.csv', 'B.hex', [ (None, 1.00, 2501.00, 5001.00, 7501.00, 10000.00), ('x', -100.00, -50.1, 0.974, 51.7, 100,00), ], ), ('runifC.csv', 'C.hex', [ (None, 1.00, 25002.00, 50002.00, 75002.00, 100000.00), ('x', -100.00, -50.45, -1.135, 49.28, 100.00), ], ), ] timeoutSecs = 15 trial = 1 n = h2o.nodes[0] lenNodes = len(h2o.nodes) timeoutSecs = 60 for (csvFilename, hex_key, expectedCols) in tryList: csvPathname = csvFilename csvPathnameFull = h2i.find_folder_and_filename('smalldata', csvPathname, returnFullPath=True) parseResult = h2i.import_parse(bucket='smalldata', path=csvPathname, schema='put', hex_key=hex_key, timeoutSecs=10, doSummary=False) print "Parse result['destination_key']:", parseResult['destination_key'] # We should be able to see the parse result? inspect = h2o_cmd.runInspect(None, parseResult['destination_key']) print "\n" + csvFilename numRows = inspect["numRows"] numCols = inspect["numCols"] # okay to get more cols than we want # okay to vary MAX_QBINS because we adjust the expected accuracy summaryResult = h2o_cmd.runSummary(key=hex_key, max_qbins=MAX_QBINS) h2o.verboseprint("summaryResult:", h2o.dump_json(summaryResult)) summaries = summaryResult['summaries'] scipyCol = 0 for expected, column in zip(expectedCols, summaries): colname = column['colname'] if expected[0]: self.assertEqual(colname, expected[0]), colname, expected[0] else: # if the colname is None, skip it (so we don't barf on strings on the h2o quantile page scipyCol += 1 continue quantile = 0.5 if DO_MEDIAN else .999 # h2o has problem if a list of columns (or dictionary) is passed to 'column' param q = h2o.nodes[0].quantiles(source_key=hex_key, column=column['colname'], quantile=quantile, max_qbins=MAX_QBINS, multiple_pass=2, interpolation_type=7) # for comparing to summary2 qresult = q['result'] qresult_single = q['result_single'] h2p.blue_print("h2o quantiles result:", qresult) h2p.blue_print("h2o quantiles result_single:", qresult_single) h2p.blue_print("h2o quantiles iterations:", q['iterations']) h2p.blue_print("h2o quantiles interpolated:", q['interpolated']) print h2o.dump_json(q) # ('', '1.00', '25002.00', '50002.00', '75002.00', '100000.00'), coltype = column['type'] nacnt = column['nacnt'] stats = column['stats'] stattype= stats['type'] print stattype # FIX! we should compare mean and sd to expected? # enums don't have mean or sd? if stattype!='Enum': mean = stats['mean'] sd = stats['sd'] zeros = stats['zeros'] mins = stats['mins'] maxs = stats['maxs'] print "colname:", colname, "mean (2 places):", h2o_util.twoDecimals(mean) print "colname:", colname, "std dev. (2 places):", h2o_util.twoDecimals(sd) pct = stats['pct'] print "pct:", pct print "" # the thresholds h2o used, should match what we expected expectedPct= [0.01, 0.05, 0.1, 0.25, 0.33, 0.5, 0.66, 0.75, 0.9, 0.95, 0.99] pctile = stats['pctile'] # figure out the expected max error # use this for comparing to sklearn/sort if expected[1] and expected[5]: expectedRange = expected[5] - expected[1] # because of floor and ceil effects due we potentially lose 2 bins (worst case) # the extra bin for the max value, is an extra bin..ignore expectedBin = expectedRange/(MAX_QBINS-2) maxErr = 0.5 * expectedBin # should we have some fuzz for fp? else: print "Test won't calculate max expected error" maxErr = 0 # hack..assume just one None is enough to ignore for cars.csv if expected[1]: h2o_util.assertApproxEqual(mins[0], expected[1], tol=maxErr, msg='min is not approx. expected') if expected[2]: h2o_util.assertApproxEqual(pctile[3], expected[2], tol=maxErr, msg='25th percentile is not approx. expected') if expected[3]: h2o_util.assertApproxEqual(pctile[5], expected[3], tol=maxErr, msg='50th percentile (median) is not approx. expected') if expected[4]: h2o_util.assertApproxEqual(pctile[7], expected[4], tol=maxErr, msg='75th percentile is not approx. expected') if expected[5]: h2o_util.assertApproxEqual(maxs[0], expected[5], tol=maxErr, msg='max is not approx. expected') hstart = column['hstart'] hstep = column['hstep'] hbrk = column['hbrk'] hcnt = column['hcnt'] for b in hcnt: # should we be able to check for a uniform distribution in the files? e = .1 * numRows # self.assertAlmostEqual(b, .1 * rowCount, delta=.01*rowCount, # msg="Bins not right. b: %s e: %s" % (b, e)) if stattype!='Enum': pt = h2o_util.twoDecimals(pctile) print "colname:", colname, "pctile (2 places):", pt mx = h2o_util.twoDecimals(maxs) mn = h2o_util.twoDecimals(mins) print "colname:", colname, "maxs: (2 places):", mx print "colname:", colname, "mins: (2 places):", mn # FIX! we should do an exec and compare using the exec quantile too actual = mn[0], pt[3], pt[5], pt[7], mx[0] print "min/25/50/75/max colname:", colname, "(2 places):", actual print "maxs colname:", colname, "(2 places):", mx print "mins colname:", colname, "(2 places):", mn # don't check if colname is empty..means it's a string and scipy doesn't parse right? # need to ignore the car names if colname!='' and expected[scipyCol]: # don't do for enums # also get the median with a sort (h2o_summ.percentileOnSortedlist() h2o_summ.quantile_comparisons( csvPathnameFull, skipHeader=True, col=scipyCol, datatype='float', quantile=0.5 if DO_MEDIAN else 0.999, # FIX! ignore for now h2oSummary2=pctile[5 if DO_MEDIAN else 10], h2oQuantilesApprox=qresult_single, h2oQuantilesExact=qresult, h2oSummary2MaxErr=maxErr, ) if False and h2o_util.approxEqual(pctile[5], 0.990238116744, tol=0.002, msg='stop here'): raise Exception("stopping to look") scipyCol += 1 trial += 1 if __name__ == '__main__': h2o.unit_main()
rowhit/h2o-2
py/testdir_single_jvm/test_summary2_unifiles.py
Python
apache-2.0
10,223
// This file was automatically generated on Fri Jun 04 12:51:34 2010 // by libs/config/tools/generate.cpp // Copyright John Maddock 2002-4. // Use, modification and distribution are subject to 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/config for the most recent version.// // Revision $Id: generate.cpp 49281 2008-10-11 15:40:44Z johnmaddock $ // // Test file for macro BOOST_NO_CXX11_HDR_TYPEINDEX // This file should not compile, if it does then // BOOST_NO_CXX11_HDR_TYPEINDEX should not be defined. // See file boost_no_cxx11_hdr_typeindex.ipp for details // Must not have BOOST_ASSERT_CONFIG set; it defeats // the objective of this file: #ifdef BOOST_ASSERT_CONFIG # undef BOOST_ASSERT_CONFIG #endif #include <boost/config.hpp> #include "test.hpp" #ifdef BOOST_NO_CXX11_HDR_TYPEINDEX #include "boost_no_cxx11_hdr_typeindex.ipp" #else #error "this file should not compile" #endif int main( int, char *[] ) { return boost_no_cxx11_hdr_typeindex::test(); }
flingone/frameworks_base_cmds_remoted
libs/boost/libs/config/test/no_cxx11_hdr_typeindex_fail.cpp
C++
apache-2.0
1,145
/* * 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.facebook.presto.hive; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.type.CharType; import com.facebook.presto.spi.type.DecimalType; import com.facebook.presto.spi.type.NamedTypeSignature; import com.facebook.presto.spi.type.Type; import com.facebook.presto.spi.type.TypeSignatureParameter; import com.facebook.presto.spi.type.VarcharType; import com.google.common.collect.ImmutableList; import org.apache.hadoop.hive.common.type.HiveChar; import org.apache.hadoop.hive.common.type.HiveVarchar; import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo; import static com.facebook.presto.hive.HiveType.HIVE_BINARY; import static com.facebook.presto.hive.HiveType.HIVE_BOOLEAN; import static com.facebook.presto.hive.HiveType.HIVE_BYTE; import static com.facebook.presto.hive.HiveType.HIVE_DATE; import static com.facebook.presto.hive.HiveType.HIVE_DOUBLE; import static com.facebook.presto.hive.HiveType.HIVE_FLOAT; import static com.facebook.presto.hive.HiveType.HIVE_INT; import static com.facebook.presto.hive.HiveType.HIVE_LONG; import static com.facebook.presto.hive.HiveType.HIVE_SHORT; import static com.facebook.presto.hive.HiveType.HIVE_STRING; import static com.facebook.presto.hive.HiveType.HIVE_TIMESTAMP; import static com.facebook.presto.hive.HiveUtil.isArrayType; import static com.facebook.presto.hive.HiveUtil.isMapType; import static com.facebook.presto.hive.HiveUtil.isRowType; import static com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.DateType.DATE; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; import static com.facebook.presto.spi.type.IntegerType.INTEGER; import static com.facebook.presto.spi.type.RealType.REAL; import static com.facebook.presto.spi.type.SmallintType.SMALLINT; import static com.facebook.presto.spi.type.TimestampType.TIMESTAMP; import static com.facebook.presto.spi.type.TinyintType.TINYINT; import static com.facebook.presto.spi.type.VarbinaryType.VARBINARY; import static java.lang.String.format; import static java.util.stream.Collectors.toList; import static org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory.getCharTypeInfo; import static org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory.getListTypeInfo; import static org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory.getMapTypeInfo; import static org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory.getStructTypeInfo; import static org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory.getVarcharTypeInfo; public class HiveTypeTranslator implements TypeTranslator { @Override public TypeInfo translate(Type type) { if (BOOLEAN.equals(type)) { return HIVE_BOOLEAN.getTypeInfo(); } if (BIGINT.equals(type)) { return HIVE_LONG.getTypeInfo(); } if (INTEGER.equals(type)) { return HIVE_INT.getTypeInfo(); } if (SMALLINT.equals(type)) { return HIVE_SHORT.getTypeInfo(); } if (TINYINT.equals(type)) { return HIVE_BYTE.getTypeInfo(); } if (REAL.equals(type)) { return HIVE_FLOAT.getTypeInfo(); } if (DOUBLE.equals(type)) { return HIVE_DOUBLE.getTypeInfo(); } if (type instanceof VarcharType) { VarcharType varcharType = (VarcharType) type; int varcharLength = varcharType.getLength(); if (varcharLength <= HiveVarchar.MAX_VARCHAR_LENGTH) { return getVarcharTypeInfo(varcharLength); } else if (varcharLength == VarcharType.MAX_LENGTH) { return HIVE_STRING.getTypeInfo(); } else { throw new PrestoException(NOT_SUPPORTED, format("Unsupported Hive type: %s. Supported VARCHAR types: VARCHAR(<=%d), VARCHAR.", type, HiveVarchar.MAX_VARCHAR_LENGTH)); } } if (type instanceof CharType) { CharType charType = (CharType) type; int charLength = charType.getLength(); if (charLength <= HiveChar.MAX_CHAR_LENGTH) { return getCharTypeInfo(charLength); } throw new PrestoException(NOT_SUPPORTED, format("Unsupported Hive type: %s. Supported CHAR types: CHAR(<=%d).", type, HiveChar.MAX_CHAR_LENGTH)); } if (VARBINARY.equals(type)) { return HIVE_BINARY.getTypeInfo(); } if (DATE.equals(type)) { return HIVE_DATE.getTypeInfo(); } if (TIMESTAMP.equals(type)) { return HIVE_TIMESTAMP.getTypeInfo(); } if (type instanceof DecimalType) { DecimalType decimalType = (DecimalType) type; return new DecimalTypeInfo(decimalType.getPrecision(), decimalType.getScale()); } if (isArrayType(type)) { TypeInfo elementType = translate(type.getTypeParameters().get(0)); return getListTypeInfo(elementType); } if (isMapType(type)) { TypeInfo keyType = translate(type.getTypeParameters().get(0)); TypeInfo valueType = translate(type.getTypeParameters().get(1)); return getMapTypeInfo(keyType, valueType); } if (isRowType(type)) { ImmutableList.Builder<String> fieldNames = ImmutableList.builder(); for (TypeSignatureParameter parameter : type.getTypeSignature().getParameters()) { if (!parameter.isNamedTypeSignature()) { throw new IllegalArgumentException(format("Expected all parameters to be named type, but got %s", parameter)); } NamedTypeSignature namedTypeSignature = parameter.getNamedTypeSignature(); fieldNames.add(namedTypeSignature.getName()); } return getStructTypeInfo( fieldNames.build(), type.getTypeParameters().stream() .map(this::translate) .collect(toList())); } throw new PrestoException(NOT_SUPPORTED, format("Unsupported Hive type: %s", type)); } }
dabaitu/presto
presto-hive/src/main/java/com/facebook/presto/hive/HiveTypeTranslator.java
Java
apache-2.0
7,003
#include <assert.h> #include <limits.h> #include <stdint.h> #include "blake2.h" #include "crypto_generichash_blake2b.h" #include "private/common.h" #include "private/implementations.h" int crypto_generichash_blake2b(unsigned char *out, size_t outlen, const unsigned char *in, unsigned long long inlen, const unsigned char *key, size_t keylen) { if (outlen <= 0U || outlen > BLAKE2B_OUTBYTES || keylen > BLAKE2B_KEYBYTES || inlen > UINT64_MAX) { return -1; } assert(outlen <= UINT8_MAX); assert(keylen <= UINT8_MAX); return blake2b((uint8_t *) out, in, key, (uint8_t) outlen, (uint64_t) inlen, (uint8_t) keylen); } int crypto_generichash_blake2b_salt_personal( unsigned char *out, size_t outlen, const unsigned char *in, unsigned long long inlen, const unsigned char *key, size_t keylen, const unsigned char *salt, const unsigned char *personal) { if (outlen <= 0U || outlen > BLAKE2B_OUTBYTES || keylen > BLAKE2B_KEYBYTES || inlen > UINT64_MAX) { return -1; } assert(outlen <= UINT8_MAX); assert(keylen <= UINT8_MAX); return blake2b_salt_personal((uint8_t *) out, in, key, (uint8_t) outlen, (uint64_t) inlen, (uint8_t) keylen, salt, personal); } int crypto_generichash_blake2b_init(crypto_generichash_blake2b_state *state, const unsigned char *key, const size_t keylen, const size_t outlen) { if (outlen <= 0U || outlen > BLAKE2B_OUTBYTES || keylen > BLAKE2B_KEYBYTES) { return -1; } assert(outlen <= UINT8_MAX); assert(keylen <= UINT8_MAX); COMPILER_ASSERT(sizeof(blake2b_state) <= sizeof *state); if (key == NULL || keylen <= 0U) { if (blake2b_init((blake2b_state *) (void *) state, (uint8_t) outlen) != 0) { return -1; /* LCOV_EXCL_LINE */ } } else if (blake2b_init_key((blake2b_state *) (void *) state, (uint8_t) outlen, key, (uint8_t) keylen) != 0) { return -1; /* LCOV_EXCL_LINE */ } return 0; } int crypto_generichash_blake2b_init_salt_personal( crypto_generichash_blake2b_state *state, const unsigned char *key, const size_t keylen, const size_t outlen, const unsigned char *salt, const unsigned char *personal) { if (outlen <= 0U || outlen > BLAKE2B_OUTBYTES || keylen > BLAKE2B_KEYBYTES) { return -1; } assert(outlen <= UINT8_MAX); assert(keylen <= UINT8_MAX); if (key == NULL || keylen <= 0U) { if (blake2b_init_salt_personal((blake2b_state *) (void *) state, (uint8_t) outlen, salt, personal) != 0) { return -1; /* LCOV_EXCL_LINE */ } } else if (blake2b_init_key_salt_personal((blake2b_state *) (void *) state, (uint8_t) outlen, key, (uint8_t) keylen, salt, personal) != 0) { return -1; /* LCOV_EXCL_LINE */ } return 0; } int crypto_generichash_blake2b_update(crypto_generichash_blake2b_state *state, const unsigned char *in, unsigned long long inlen) { return blake2b_update((blake2b_state *) (void *) state, (const uint8_t *) in, (uint64_t) inlen); } int crypto_generichash_blake2b_final(crypto_generichash_blake2b_state *state, unsigned char *out, const size_t outlen) { assert(outlen <= UINT8_MAX); return blake2b_final((blake2b_state *) (void *) state, (uint8_t *) out, (uint8_t) outlen); } int _crypto_generichash_blake2b_pick_best_implementation(void) { return blake2b_pick_best_implementation(); }
lmctv/pynacl
src/libsodium/src/libsodium/crypto_generichash/blake2b/ref/generichash_blake2b.c
C
apache-2.0
3,977
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/distributed_runtime/session_mgr.h" #include "tensorflow/core/distributed_runtime/rpc/rpc_rendezvous_mgr.h" #include "tensorflow/core/distributed_runtime/worker_env.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/protobuf/cluster.pb.h" namespace tensorflow { class FakeDevice : public Device { private: explicit FakeDevice(const DeviceAttributes& device_attributes) : Device(nullptr, device_attributes) {} public: Status Sync() override { return errors::Unimplemented("FakeDevice::Sync()"); } Allocator* GetAllocator(AllocatorAttributes attr) override { return nullptr; } static std::unique_ptr<Device> MakeCPU(const string& name) { DeviceAttributes device_attributes; device_attributes.set_name(name); device_attributes.set_device_type(DeviceType("FakeCPU").type()); return std::unique_ptr<Device>(new FakeDevice(device_attributes)); } }; class SessionMgrTest : public ::testing::Test { protected: SessionMgrTest() : mgr_(&env_, "/job:mnist/replica:0/task:0", std::unique_ptr<WorkerCacheInterface>(), factory_) { device_mgr_ = absl::make_unique<StaticDeviceMgr>( FakeDevice::MakeCPU("/job:mnist/replica:0/task:0/device:fakecpu:0")); env_.local_devices = device_mgr_->ListDevices(); env_.device_mgr = device_mgr_.get(); } std::unique_ptr<DeviceMgr> device_mgr_; WorkerEnv env_; SessionMgr::WorkerCacheFactory factory_ = [](const ServerDef& server_def, WorkerCacheInterface** worker_cache) { *worker_cache = nullptr; // Set to null to make debugging easier. return Status::OK(); }; SessionMgr mgr_; }; TEST_F(SessionMgrTest, CreateSessionSimple) { ServerDef server_def; server_def.set_job_name("worker"); server_def.set_task_index(3); string session_handle = "test_session_handle"; TF_EXPECT_OK(mgr_.CreateSession(session_handle, server_def, true)); std::shared_ptr<WorkerSession> session; TF_EXPECT_OK(mgr_.WorkerSessionForSession(session_handle, &session)); EXPECT_NE(nullptr, session) << "Session for " << session_handle << "was null"; EXPECT_NE(mgr_.LegacySession(), session); TF_EXPECT_OK(mgr_.DeleteSession(session_handle)); } TEST_F(SessionMgrTest, CreateSessionClusterDefWorkerName) { ServerDef server_def; server_def.set_job_name("worker"); server_def.set_task_index(3); auto job = server_def.mutable_cluster()->add_job(); job->set_name("worker"); job->mutable_tasks()->insert({3, "localhost:3333"}); protobuf::RepeatedPtrField<DeviceAttributes> cluster_device_attributes; DeviceAttributes* local_cpu = cluster_device_attributes.Add(); local_cpu->set_name("/job:worker/replica:0/task:3/device:fakecpu:0"); DeviceAttributes* remote_cpu = cluster_device_attributes.Add(); remote_cpu->set_name("/job:coordinator/replica:0/task:0/device:fakecpu:0"); string session_handle = "test_session_handle"; TF_EXPECT_OK(mgr_.CreateSession(session_handle, server_def, cluster_device_attributes, true)); std::shared_ptr<WorkerSession> session; TF_EXPECT_OK(mgr_.WorkerSessionForSession(session_handle, &session)); Device* device; // remote_device_mgr should show the local device as actually local TF_EXPECT_OK( session->remote_device_mgr()->LookupDevice(local_cpu->name(), &device)); EXPECT_TRUE(device->IsLocal()); EXPECT_NE(nullptr, session) << "Session for " << session_handle << "was null"; EXPECT_EQ("/job:worker/replica:0/task:3", session->worker_name()); TF_EXPECT_OK(mgr_.DeleteSession(session_handle)); } TEST_F(SessionMgrTest, CreateSessionDefaultWorkerName) { ServerDef server_def; string session_handle = "test_session_handle"; TF_EXPECT_OK(mgr_.CreateSession(session_handle, server_def, true)); std::shared_ptr<WorkerSession> session; TF_EXPECT_OK(mgr_.WorkerSessionForSession(session_handle, &session)); EXPECT_NE(nullptr, session) << "Session for " << session_handle << "was null"; EXPECT_EQ("/job:mnist/replica:0/task:0", session->worker_name()); TF_EXPECT_OK(mgr_.DeleteSession(session_handle)); } TEST_F(SessionMgrTest, CreateSessionIsolateSessionState) { ServerDef server_def; server_def.set_job_name("worker"); server_def.set_task_index(3); TF_EXPECT_OK(mgr_.CreateSession("handle_1", server_def, false)); std::shared_ptr<WorkerSession> session_1; TF_EXPECT_OK(mgr_.WorkerSessionForSession("handle_1", &session_1)); std::vector<Device*> devices_1 = session_1->device_mgr()->ListDevices(); EXPECT_EQ(1, devices_1.size()); TF_EXPECT_OK(mgr_.CreateSession("handle_2", server_def, false)); std::shared_ptr<WorkerSession> session_2; TF_EXPECT_OK(mgr_.WorkerSessionForSession("handle_2", &session_2)); std::vector<Device*> devices_2 = session_2->device_mgr()->ListDevices(); EXPECT_EQ(1, devices_2.size()); TF_EXPECT_OK(mgr_.CreateSession("handle_3", server_def, true)); std::shared_ptr<WorkerSession> session_3; TF_EXPECT_OK(mgr_.WorkerSessionForSession("handle_3", &session_3)); std::vector<Device*> devices_3 = session_3->device_mgr()->ListDevices(); EXPECT_EQ(1, devices_3.size()); TF_EXPECT_OK(mgr_.CreateSession("handle_4", server_def, true)); std::shared_ptr<WorkerSession> session_4; TF_EXPECT_OK(mgr_.WorkerSessionForSession("handle_4", &session_4)); std::vector<Device*> devices_4 = session_4->device_mgr()->ListDevices(); EXPECT_EQ(1, devices_4.size()); EXPECT_EQ(devices_1[0]->resource_manager(), devices_2[0]->resource_manager()); EXPECT_NE(devices_1[0]->resource_manager(), devices_3[0]->resource_manager()); EXPECT_NE(devices_1[0]->resource_manager(), devices_4[0]->resource_manager()); EXPECT_NE(devices_3[0]->resource_manager(), devices_4[0]->resource_manager()); } TEST_F(SessionMgrTest, CreateSessionWithMasterName) { ServerDef server_def; server_def.set_job_name("worker"); server_def.set_task_index(3); auto job = server_def.mutable_cluster()->add_job(); job->set_name("worker"); job->mutable_tasks()->insert({3, "localhost:3333"}); protobuf::RepeatedPtrField<DeviceAttributes> cluster_device_attributes; const string master_name = "/job:master/replica:0/task:1"; const int64 old_incarnation = random::New64(); const int64 new_incarnation = random::New64(); // Allow multiple worker sessions to be created by the same master string sess_handle1 = "test_session_handle_1"; TF_EXPECT_OK(mgr_.CreateSession(sess_handle1, server_def, cluster_device_attributes, true, master_name, old_incarnation)); string sess_handle2 = "test_session_handle_2"; TF_EXPECT_OK(mgr_.CreateSession(sess_handle2, server_def, cluster_device_attributes, true, master_name, old_incarnation)); std::shared_ptr<WorkerSession> session; TF_EXPECT_OK(mgr_.WorkerSessionForSession(sess_handle1, &session)); EXPECT_NE(nullptr, session) << "Session for " << sess_handle1 << "was null"; TF_EXPECT_OK(mgr_.WorkerSessionForSession(sess_handle2, &session)); EXPECT_NE(nullptr, session) << "Session for " << sess_handle2 << "was null"; // When the master creates a WorkerSession with new incarnation, the old // WorkerSessions should be garbage collected. string sess_handle3 = "test_session_handle_3"; TF_EXPECT_OK(mgr_.CreateSession(sess_handle3, server_def, cluster_device_attributes, true, master_name, new_incarnation)); EXPECT_NE(mgr_.WorkerSessionForSession(sess_handle1, &session), tensorflow::Status::OK()) << "Session for " << sess_handle1 << " should have been garbage collected."; EXPECT_NE(mgr_.WorkerSessionForSession(sess_handle2, &session), tensorflow::Status::OK()) << "Session for " << sess_handle2 << " should have been garbage collected."; TF_EXPECT_OK(mgr_.WorkerSessionForSession(sess_handle3, &session)); EXPECT_NE(nullptr, session) << "Session for " << sess_handle3 << "was null"; TF_EXPECT_OK(mgr_.DeleteSession(sess_handle2)); TF_EXPECT_OK(mgr_.DeleteSession(sess_handle3)); } TEST_F(SessionMgrTest, CreateSessionWithoutMasterName) { ServerDef server_def; server_def.set_job_name("worker"); server_def.set_task_index(3); auto job = server_def.mutable_cluster()->add_job(); job->set_name("worker"); job->mutable_tasks()->insert({3, "localhost:3333"}); protobuf::RepeatedPtrField<DeviceAttributes> cluster_device_attributes; // WorkerSession will NOT be garbage collected for empty master names. string sess_handle1 = "test_session_handle_no_master_1"; TF_EXPECT_OK(mgr_.CreateSession(sess_handle1, server_def, cluster_device_attributes, true, "", 0)); string sess_handle2 = "test_session_handle_no_master_2"; TF_EXPECT_OK(mgr_.CreateSession(sess_handle2, server_def, cluster_device_attributes, true, "", 0)); std::shared_ptr<WorkerSession> session; TF_EXPECT_OK(mgr_.WorkerSessionForSession(sess_handle1, &session)); EXPECT_NE(nullptr, session) << "Session for " << sess_handle1 << "was null"; TF_EXPECT_OK(mgr_.WorkerSessionForSession(sess_handle2, &session)); EXPECT_NE(nullptr, session) << "Session for " << sess_handle2 << "was null"; TF_EXPECT_OK(mgr_.DeleteSession(sess_handle1)); TF_EXPECT_OK(mgr_.DeleteSession(sess_handle2)); } TEST_F(SessionMgrTest, LegacySession) { string session_handle = ""; std::shared_ptr<WorkerSession> session; TF_EXPECT_OK(mgr_.WorkerSessionForSession(session_handle, &session)); EXPECT_EQ(mgr_.LegacySession(), session); TF_EXPECT_OK(mgr_.DeleteSession(session_handle)); } TEST_F(SessionMgrTest, UnknownSessionHandle) { string session_handle = "unknown_session_handle"; std::shared_ptr<WorkerSession> session; Status s = mgr_.WorkerSessionForSession(session_handle, &session); EXPECT_TRUE(errors::IsAborted(s)); EXPECT_TRUE( absl::StrContains(s.error_message(), "Session handle is not found")); } TEST_F(SessionMgrTest, WorkerNameFromServerDef) { ServerDef server_def; server_def.set_job_name("worker"); server_def.set_task_index(3); string worker_name = SessionMgr::WorkerNameFromServerDef(server_def); EXPECT_EQ("/job:worker/replica:0/task:3", worker_name); } TEST_F(SessionMgrTest, DeleteLegacySession) { TF_EXPECT_OK(mgr_.DeleteSession("")); } } // namespace tensorflow
karllessard/tensorflow
tensorflow/core/distributed_runtime/session_mgr_test.cc
C++
apache-2.0
11,186
// Copyright (c) IPython Development Team. // Distributed under the terms of the Modified BSD License. define([ 'base/js/namespace', 'jqueryui', 'base/js/utils', ], function(IPython, $, utils) { "use strict"; var Pager = function (pager_selector, options) { /** * Constructor * * Parameters: * pager_selector: string * options: dictionary * Dictionary of keyword arguments. * events: $(Events) instance */ this.events = options.events; this.pager_element = $(pager_selector); this.pager_button_area = $('#pager-button-area'); this._default_end_space = 100; this.pager_element.resizable({handles: 'n', resize: $.proxy(this._resize, this)}); this.expanded = false; this.create_button_area(); this.bind_events(); }; Pager.prototype.create_button_area = function(){ var that = this; this.pager_button_area.append( $('<a>').attr('role', "button") .attr('title',"Open the pager in an external window") .addClass('ui-button') .click(function(){that.detach();}) .append( $('<span>').addClass("ui-icon ui-icon-extlink") ) ); this.pager_button_area.append( $('<a>').attr('role', "button") .attr('title',"Close the pager") .addClass('ui-button') .click(function(){that.collapse();}) .append( $('<span>').addClass("ui-icon ui-icon-close") ) ); }; Pager.prototype.bind_events = function () { var that = this; this.pager_element.bind('collapse_pager', function (event, extrap) { // Animate hiding of the pager. var time = (extrap && extrap.duration) ? extrap.duration : 'fast'; that.pager_element.animate({ height: 'toggle' }, { duration: time, done: function() { $('.end_space').css('height', that._default_end_space); } }); }); this.pager_element.bind('expand_pager', function (event, extrap) { // Clear the pager's height attr if it's set. This allows the // pager to size itself according to its contents. that.pager_element.height('initial'); // Animate the showing of the pager var time = (extrap && extrap.duration) ? extrap.duration : 'fast'; that.pager_element.show(time, function() { // Explicitly set pager height once the pager has shown itself. // This allows the pager-contents div to use percentage sizing. that.pager_element.height(that.pager_element.height()); that._resize(); }); }); this.events.on('open_with_text.Pager', function (event, payload) { // FIXME: support other mime types if (payload.data['text/plain'] && payload.data['text/plain'] !== "") { that.clear(); that.expand(); that.append_text(payload.data['text/plain']); } }); }; Pager.prototype.collapse = function (extrap) { if (this.expanded === true) { this.expanded = false; this.pager_element.trigger('collapse_pager', extrap); } }; Pager.prototype.expand = function (extrap) { if (this.expanded !== true) { this.expanded = true; this.pager_element.trigger('expand_pager', extrap); } }; Pager.prototype.toggle = function () { if (this.expanded === true) { this.collapse(); } else { this.expand(); } }; Pager.prototype.clear = function (text) { this.pager_element.find(".container").empty(); }; Pager.prototype.detach = function(){ var w = window.open("","_blank"); $(w.document.head) .append( $('<link>') .attr('rel',"stylesheet") .attr('href',"/static/css/notebook.css") .attr('type',"text/css") ) .append( $('<title>').text("Spark Notebook Pager") ); var pager_body = $(w.document.body); pager_body.css('overflow','scroll'); pager_body.append(this.pager_element.clone().children()); w.document.close(); this.collapse(); }; Pager.prototype.append_text = function (text) { /** * The only user content injected with this HTML call is escaped by * the fixConsole() method. */ this.pager_element.find(".container").append($('<pre/>').html(utils.fixCarriageReturn(utils.fixConsole(text)))); }; Pager.prototype._resize = function() { /** * Update document based on pager size. */ // Make sure the padding at the end of the notebook is large // enough that the user can scroll to the bottom of the // notebook. $('.end_space').css('height', Math.max(this.pager_element.height(), this._default_end_space)); }; // Backwards compatability. IPython.Pager = Pager; return {'Pager': Pager}; });
radek1st/spark-notebook
public/ipython/notebook/js/pager.js
JavaScript
apache-2.0
5,506
/* * * 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. * */ #include "options.hpp" #include <proton/connection.hpp> #include <proton/connection_options.hpp> #include <proton/container.hpp> #include <proton/delivery.hpp> #include <proton/link.hpp> #include <proton/message.hpp> #include <proton/message_id.hpp> #include <proton/messaging_handler.hpp> #include <proton/value.hpp> #include <iostream> #include <map> class simple_recv : public proton::messaging_handler { private: std::string url; std::string user; std::string password; proton::receiver receiver; int expected; int received; public: simple_recv(const std::string &s, const std::string &u, const std::string &p, int c) : url(s), user(u), password(p), expected(c), received(0) {} void on_container_start(proton::container &c) override { proton::connection_options co; if (!user.empty()) co.user(user); if (!password.empty()) co.password(password); receiver = c.open_receiver(url, co); } void on_message(proton::delivery &d, proton::message &msg) override { if (!msg.id().empty() && proton::coerce<int>(msg.id()) < received) { return; // Ignore if no id or duplicate } if (expected == 0 || received < expected) { std::cout << msg.body() << std::endl; received++; if (received == expected) { d.receiver().close(); d.connection().close(); } } } }; int main(int argc, char **argv) { std::string address("127.0.0.1:5672/examples"); std::string user; std::string password; int message_count = 100; example::options opts(argc, argv); opts.add_value(address, 'a', "address", "connect to and receive from URL", "URL"); opts.add_value(message_count, 'm', "messages", "receive COUNT messages", "COUNT"); opts.add_value(user, 'u', "user", "authenticate as USER", "USER"); opts.add_value(password, 'p', "password", "authenticate with PASSWORD", "PASSWORD"); try { opts.parse(); simple_recv recv(address, user, password, message_count); proton::container(recv).run(); return 0; } catch (const example::bad_option& e) { std::cout << opts << std::endl << e.what() << std::endl; } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } return 1; }
gemmellr/qpid-proton
cpp/examples/simple_recv.cpp
C++
apache-2.0
3,197
package org.apache.lucene.search.grouping.term; /* * 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. */ import java.io.IOException; import java.util.*; import org.apache.lucene.index.AtomicReaderContext; import org.apache.lucene.index.SortedDocValues; import org.apache.lucene.search.FieldCache; import org.apache.lucene.search.grouping.AbstractDistinctValuesCollector; import org.apache.lucene.search.grouping.SearchGroup; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.SentinelIntSet; /** * A term based implementation of {@link org.apache.lucene.search.grouping.AbstractDistinctValuesCollector} that relies * on {@link SortedDocValues} to count the distinct values per group. * * @lucene.experimental */ public class TermDistinctValuesCollector extends AbstractDistinctValuesCollector<TermDistinctValuesCollector.GroupCount> { private final String groupField; private final String countField; private final List<GroupCount> groups; private final SentinelIntSet ordSet; private final GroupCount groupCounts[]; private SortedDocValues groupFieldTermIndex; private SortedDocValues countFieldTermIndex; /** * Constructs {@link TermDistinctValuesCollector} instance. * * @param groupField The field to group by * @param countField The field to count distinct values for * @param groups The top N groups, collected during the first phase search */ public TermDistinctValuesCollector(String groupField, String countField, Collection<SearchGroup<BytesRef>> groups) { this.groupField = groupField; this.countField = countField; this.groups = new ArrayList<GroupCount>(groups.size()); for (SearchGroup<BytesRef> group : groups) { this.groups.add(new GroupCount(group.groupValue)); } ordSet = new SentinelIntSet(groups.size(), -2); groupCounts = new GroupCount[ordSet.keys.length]; } @Override public void collect(int doc) throws IOException { int slot = ordSet.find(groupFieldTermIndex.getOrd(doc)); if (slot < 0) { return; } GroupCount gc = groupCounts[slot]; int countOrd = countFieldTermIndex.getOrd(doc); if (doesNotContainOrd(countOrd, gc.ords)) { if (countOrd == -1) { gc.uniqueValues.add(null); } else { BytesRef br = new BytesRef(); countFieldTermIndex.lookupOrd(countOrd, br); gc.uniqueValues.add(br); } gc.ords = Arrays.copyOf(gc.ords, gc.ords.length + 1); gc.ords[gc.ords.length - 1] = countOrd; if (gc.ords.length > 1) { Arrays.sort(gc.ords); } } } private boolean doesNotContainOrd(int ord, int[] ords) { if (ords.length == 0) { return true; } else if (ords.length == 1) { return ord != ords[0]; } return Arrays.binarySearch(ords, ord) < 0; } @Override public List<GroupCount> getGroups() { return groups; } @Override public void setNextReader(AtomicReaderContext context) throws IOException { groupFieldTermIndex = FieldCache.DEFAULT.getTermsIndex(context.reader(), groupField); countFieldTermIndex = FieldCache.DEFAULT.getTermsIndex(context.reader(), countField); ordSet.clear(); for (GroupCount group : groups) { int groupOrd = group.groupValue == null ? -1 : groupFieldTermIndex.lookupTerm(group.groupValue); if (group.groupValue != null && groupOrd < 0) { continue; } groupCounts[ordSet.put(groupOrd)] = group; group.ords = new int[group.uniqueValues.size()]; Arrays.fill(group.ords, -2); int i = 0; for (BytesRef value : group.uniqueValues) { int countOrd = value == null ? -1 : countFieldTermIndex.lookupTerm(value); if (value == null || countOrd >= 0) { group.ords[i++] = countOrd; } } } } /** Holds distinct values for a single group. * * @lucene.experimental */ public static class GroupCount extends AbstractDistinctValuesCollector.GroupCount<BytesRef> { int[] ords; GroupCount(BytesRef groupValue) { super(groupValue); } } }
yintaoxue/read-open-source-code
solr-4.7.2/src/org/apache/lucene/search/grouping/term/TermDistinctValuesCollector.java
Java
apache-2.0
4,823
/** * 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.hadoop.yarn.server.nodemanager.containermanager.container; public enum ContainerEventType { // Producer: ContainerManager INIT_CONTAINER, KILL_CONTAINER, UPDATE_DIAGNOSTICS_MSG, CONTAINER_DONE, REINITIALIZE_CONTAINER, ROLLBACK_REINIT, // DownloadManager CONTAINER_INITED, RESOURCE_LOCALIZED, RESOURCE_FAILED, CONTAINER_RESOURCES_CLEANEDUP, // Producer: ContainersLauncher CONTAINER_LAUNCHED, CONTAINER_EXITED_WITH_SUCCESS, CONTAINER_EXITED_WITH_FAILURE, CONTAINER_KILLED_ON_REQUEST }
bitmybytes/hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/ContainerEventType.java
Java
apache-2.0
1,333
package com.cardpay.workflow.models; import com.wicresoft.jrad.base.database.model.BusinessModel; import com.wicresoft.jrad.base.database.model.ModelParam; @ModelParam(table = "wf_status_info") public class WfStatusInfo extends BusinessModel{ /** * */ private static final long serialVersionUID = -959284890543184723L; private String relationedProcess; private String isClosed; private String isStart; private String statusKeepTime; private String statusName; private String statusCode; public String getRelationedProcess() { return relationedProcess; } public void setRelationedProcess(String relationedProcess) { this.relationedProcess = relationedProcess; } public String getIsClosed() { return isClosed; } public void setIsClosed(String isClosed) { this.isClosed = isClosed; } public String getIsStart() { return isStart; } public void setIsStart(String isStart) { this.isStart = isStart; } public String getStatusKeepTime() { return statusKeepTime; } public void setStatusKeepTime(String statusKeepTime) { this.statusKeepTime = statusKeepTime; } public String getStatusName() { return statusName; } public void setStatusName(String statusName) { this.statusName = statusName; } public String getStatusCode() { return statusCode; } public void setStatusCode(String statusCode) { this.statusCode = statusCode; } }
zhuyuanyan/PCCredit_TY
src/java/com/cardpay/workflow/models/WfStatusInfo.java
Java
apache-2.0
1,453
using Nop.Core.Domain.Catalog; namespace Nop.Services.Catalog { /// <summary> /// Copy product service /// </summary> public partial interface ICopyProductService { /// <summary> /// Create a copy of product with all depended data /// </summary> /// <param name="product">The product to copy</param> /// <param name="newName">The name of product duplicate</param> /// <param name="isPublished">A value indicating whether the product duplicate should be published</param> /// <param name="copyImages">A value indicating whether the product images should be copied</param> /// <param name="copyAssociatedProducts">A value indicating whether the copy associated products</param> /// <returns>Product copy</returns> Product CopyProduct(Product product, string newName, bool isPublished = true, bool copyImages = true, bool copyAssociatedProducts = true); } }
jornfilho/nopCommerce
source/Libraries/Nop.Services/Catalog/ICopyProductService.cs
C#
apache-2.0
973
#include <linux/kernel.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/init.h> #include <mach/sys_config.h> #include <mach/gpio.h> #include <linux/proc_fs.h> #include "wifi_pm.h" #define wifi_pm_msg(...) do {printk("[wifi_pm]: "__VA_ARGS__);} while(0) struct wifi_pm_ops wifi_select_pm_ops; static char* wifi_mod[] = {" ", "bcm40181", /* 1 - BCM40181(BCM4330)*/ "bcm40183", /* 2 - BCM40183(BCM4330)*/ "rtl8723as", /* 3 - RTL8723AS(RF-SM02B) */ "rtl8189es", /* 4 - RTL8189ES(SM89E00) */ "rtl8192cu", /* 5 - RTL8192CU*/ "rtl8188eu", /* 6 - RTL8188EU*/ "ap6210", /* 7 - AP6210*/ "ap6330", /* 8 - AP6330*/ "ap6181", /* 9 - AP6181*/ "rtl8723au", /* 10 - RTL8723AU */ }; int wifi_pm_get_mod_type(void) { struct wifi_pm_ops *ops = &wifi_select_pm_ops; if (ops->wifi_used.val) return ops->module_sel.val; else { wifi_pm_msg("No select wifi, please check your config !!\n"); return 0; } } EXPORT_SYMBOL(wifi_pm_get_mod_type); int wifi_pm_gpio_ctrl(char* name, int level) { struct wifi_pm_ops *ops = &wifi_select_pm_ops; if (ops->wifi_used.val && ops->gpio_ctrl) return ops->gpio_ctrl(name, level); else { wifi_pm_msg("No select wifi, please check your config !!\n"); return -1; } } EXPORT_SYMBOL(wifi_pm_gpio_ctrl); void wifi_pm_power(int on) { struct wifi_pm_ops *ops = &wifi_select_pm_ops; int power = on; if (ops->wifi_used.val && ops->power) return ops->power(1, &power); else { wifi_pm_msg("No select wifi, please check your config !!\n"); return; } } EXPORT_SYMBOL(wifi_pm_power); #ifdef CONFIG_PROC_FS static int wifi_pm_power_stat(char *page, char **start, off_t off, int count, int *eof, void *data) { struct wifi_pm_ops *ops = (struct wifi_pm_ops *)data; char *p = page; int power = 0; if (ops->power) ops->power(0, &power); p += sprintf(p, "%s : power state %s\n", ops->mod_name, power ? "on" : "off"); return p - page; } static int wifi_pm_power_ctrl(struct file *file, const char __user *buffer, unsigned long count, void *data) { struct wifi_pm_ops *ops = (struct wifi_pm_ops *)data; int power = simple_strtoul(buffer, NULL, 10); power = power ? 1 : 0; if (ops->power) ops->power(1, &power); else wifi_pm_msg("No power control for %s\n", ops->mod_name); return sizeof(power); } static inline void awwifi_procfs_attach(void) { char proc_rootname[] = "driver/wifi-pm"; struct wifi_pm_ops *ops = &wifi_select_pm_ops; ops->proc_root = proc_mkdir(proc_rootname, NULL); if (IS_ERR(ops->proc_root)) { wifi_pm_msg("failed to create procfs \"driver/wifi-pm\".\n"); } ops->proc_power = create_proc_entry("power", 0644, ops->proc_root); if (IS_ERR(ops->proc_power)) { wifi_pm_msg("failed to create procfs \"power\".\n"); } ops->proc_power->data = ops; ops->proc_power->read_proc = wifi_pm_power_stat; ops->proc_power->write_proc = wifi_pm_power_ctrl; } static inline void awwifi_procfs_remove(void) { struct wifi_pm_ops *ops = &wifi_select_pm_ops; char proc_rootname[] = "driver/wifi-pm"; remove_proc_entry("power", ops->proc_root); remove_proc_entry(proc_rootname, NULL); } #else static inline void awwifi_procfs_attach(void) {} static inline void awwifi_procfs_remove(void) {} #endif static int wifi_pm_get_res(void) { script_item_value_type_e type; struct wifi_pm_ops *ops = &wifi_select_pm_ops; type = script_get_item(wifi_para, "wifi_used", &ops->wifi_used); if (SCIRPT_ITEM_VALUE_TYPE_INT != type) { wifi_pm_msg("failed to fetch wifi configuration!\n"); return -1; } if (!ops->wifi_used.val) { wifi_pm_msg("no wifi used in configuration\n"); return -1; } type = script_get_item(wifi_para, "wifi_sdc_id", &ops->sdio_id); if (SCIRPT_ITEM_VALUE_TYPE_INT != type) { wifi_pm_msg("failed to fetch sdio card's sdcid\n"); return -1; } type = script_get_item(wifi_para, "wifi_usbc_id", &ops->usb_id); if (SCIRPT_ITEM_VALUE_TYPE_INT != type) { wifi_pm_msg("failed to fetch usb's id\n"); return -1; } type = script_get_item(wifi_para, "wifi_mod_sel", &ops->module_sel); if (SCIRPT_ITEM_VALUE_TYPE_INT != type) { wifi_pm_msg("failed to fetch sdio module select\n"); return -1; } ops->mod_name = wifi_mod[ops->module_sel.val]; printk("[wifi]: select wifi: %s !!\n", wifi_mod[ops->module_sel.val]); return 0; } static int __devinit wifi_pm_probe(struct platform_device *pdev) { struct wifi_pm_ops *ops = &wifi_select_pm_ops; switch (ops->module_sel.val) { case 1: /* BCM40181 */ bcm40181_gpio_init(); break; case 2: /* BCM40183 */ bcm40183_gpio_init(); break; case 3: /* RTL8723AS */ rtl8723as_gpio_init(); break; case 4: /* RTL8189ES */ rtl8189es_gpio_init(); break; case 5: /* RTL8192CU */ rtl8192cu_gpio_init(); break; case 6: /* RTL8188EU */ rtl8188eu_gpio_init(); break; case 7: /* AP6210 */ case 8: /* AP6330 */ case 9: /* AP6181 */ ap6xxx_gpio_init(); break; case 10: /* RTL8723AU */ rtl8723au_gpio_init(); break; default: wifi_pm_msg("wrong sdio module select %d !\n", ops->module_sel.val); } awwifi_procfs_attach(); wifi_pm_msg("wifi gpio init is OK !!\n"); return 0; } static int __devexit wifi_pm_remove(struct platform_device *pdev) { awwifi_procfs_remove(); wifi_pm_msg("wifi gpio is released !!\n"); return 0; } #ifdef CONFIG_PM static int wifi_pm_suspend(struct device *dev) { struct wifi_pm_ops *ops = &wifi_select_pm_ops; if (ops->standby) ops->standby(1); return 0; } static int wifi_pm_resume(struct device *dev) { struct wifi_pm_ops *ops = &wifi_select_pm_ops; if (ops->standby) ops->standby(0); return 0; } static struct dev_pm_ops wifi_dev_pm_ops = { .suspend = wifi_pm_suspend, .resume = wifi_pm_resume, }; #endif static struct platform_device wifi_pm_dev = { .name = "wifi_pm", }; static struct platform_driver wifi_pm_driver = { .driver.name = "wifi_pm", .driver.owner = THIS_MODULE, #ifdef CONFIG_PM .driver.pm = &wifi_dev_pm_ops, #endif .probe = wifi_pm_probe, .remove = __devexit_p(wifi_pm_remove), }; static int __init wifi_pm_init(void) { struct wifi_pm_ops *ops = &wifi_select_pm_ops; memset(ops, 0, sizeof(struct wifi_pm_ops)); wifi_pm_get_res(); if (!ops->wifi_used.val) return 0; platform_device_register(&wifi_pm_dev); return platform_driver_register(&wifi_pm_driver); } static void __exit wifi_pm_exit(void) { struct wifi_pm_ops *ops = &wifi_select_pm_ops; if (!ops->wifi_used.val) return; memset(ops, 0, sizeof(struct wifi_pm_ops)); platform_driver_unregister(&wifi_pm_driver); } module_init(wifi_pm_init); module_exit(wifi_pm_exit);
indashnet/InDashNet.Open.UN2000
lichee/linux-3.4/arch/arm/mach-sun7i/rf/wifi_pm.c
C
apache-2.0
6,683
package org.wso2.developerstudio.datamapper.diagram.custom.util; import java.util.ArrayList; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.edit.command.AddCommand; import org.eclipse.emf.edit.command.DeleteCommand; import org.eclipse.emf.transaction.TransactionalEditingDomain; import org.eclipse.gef.EditPart; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.wso2.developerstudio.datamapper.DataMapperFactory; import org.wso2.developerstudio.datamapper.DataMapperPackage; import org.wso2.developerstudio.datamapper.OperatorRightConnector; import org.wso2.developerstudio.datamapper.Split; public class ConfigureSplitOperatorDialog extends Dialog { private Split splitOperator; private Label caseCount; private Text count; private EditPart editpart; private TransactionalEditingDomain editingDomain; // private ArrayList<OperatorLeftContainer> caseBranches=new ArrayList<OperatorLeftContainer>(); private ArrayList<OperatorRightConnector> caseOutputConnectors=new ArrayList<OperatorRightConnector>(); public ConfigureSplitOperatorDialog(Shell parentShell, Split splitOperator, TransactionalEditingDomain editingDomain, EditPart editpart) { super(parentShell); this.splitOperator=splitOperator; this.editpart=editpart; this.editingDomain=editingDomain; } protected void configureShell(Shell newShell) { super.configureShell(newShell); // Set title. newShell.setText("Add Split Branches."); } protected Control createDialogArea(Composite parent) { Composite container = (Composite) super.createDialogArea(parent); FormLayout mainLayout = new FormLayout(); mainLayout.marginHeight = 5; mainLayout.marginWidth = 5; container.setLayout(mainLayout); caseCount = new Label(container, SWT.NONE); { caseCount.setText("Number of branches: "); FormData caseCountLabelLayoutData = new FormData(); caseCountLabelLayoutData.top = new FormAttachment(0, 5); caseCountLabelLayoutData.left = new FormAttachment(0); caseCount.setLayoutData(caseCountLabelLayoutData); } count = new Text(container, SWT.NONE); { count.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent arg0) { if(getOKButton()!=null){ if(count.getText().equals("0")){ getOKButton().setEnabled(false); }else{ getOKButton().setEnabled(true); } } } }); FormData countLayoutData = new FormData(); countLayoutData.width = 50; countLayoutData.top = new FormAttachment(caseCount, 0, SWT.CENTER); countLayoutData.left = new FormAttachment(caseCount, 5); count.setLayoutData(countLayoutData); int i =splitOperator.getBasicContainer().getRightContainer().getRightConnectors().size(); count.setText(Integer.toString(i)); } return container; } protected void okPressed() { int number = Integer.parseInt(count.getText()) - splitOperator.getBasicContainer().getRightContainer() .getRightConnectors().size(); if (number > 0) { for (int i = 0; i < number; ++i) { OperatorRightConnector concatOperatorContainers = DataMapperFactory.eINSTANCE .createOperatorRightConnector(); AddCommand addCmd = new AddCommand( editingDomain, splitOperator.getBasicContainer().getRightContainer(), DataMapperPackage.Literals.OPERATOR_RIGHT_CONTAINER__RIGHT_CONNECTORS, concatOperatorContainers); if (addCmd.canExecute()) { editingDomain.getCommandStack().execute(addCmd); } } } else if (number < 0) { for (int i = 0; i < Math.abs(number); i++) { EList<OperatorRightConnector> listOfRightConnectors = splitOperator .getBasicContainer().getRightContainer() .getRightConnectors(); OperatorRightConnector splitOperatorConnector = listOfRightConnectors .get(listOfRightConnectors.size() - 1); caseOutputConnectors.add(splitOperatorConnector); DeleteCommand deleteCmd = new DeleteCommand(editingDomain, caseOutputConnectors); if (deleteCmd.canExecute()) { editingDomain.getCommandStack().execute(deleteCmd); } caseOutputConnectors.remove(splitOperatorConnector); } } super.okPressed(); } }
nwnpallewela/developer-studio
datamapper-tool/org.wso2.developerstudio.visualdatamapper.diagram/src/org/wso2/developerstudio/datamapper/diagram/custom/util/ConfigureSplitOperatorDialog.java
Java
apache-2.0
4,626
/*------------------------------------------------------------------------- * * discard.h * prototypes for discard.c. * * * Copyright (c) 1996-2019, PostgreSQL Global Development Group * * src/include/commands/discard.h * *------------------------------------------------------------------------- */ #ifndef DISCARD_H #define DISCARD_H #include "nodes/parsenodes.h" extern void DiscardCommand(DiscardStmt *stmt, bool isTopLevel); #endif /* DISCARD_H */
50wu/gpdb
src/include/commands/discard.h
C
apache-2.0
475
@REM SBT launcher script @REM @REM Envioronment: @REM JAVA_HOME - location of a JDK home dir (mandatory) @REM SBT_OPTS - JVM options (optional) @REM Configuration: @REM sbtconfig.txt found in the SBT_HOME. @REM ZOMG! We need delayed expansion to build up CFG_OPTS later @setlocal enabledelayedexpansion @echo off set SBT_HOME=%~dp0 set ERROR_CODE=0 rem FIRST we load the config file of extra options. set FN=%SBT_HOME%sbtconfig.txt set CFG_OPTS= FOR /F "tokens=* eol=# usebackq delims=" %%i IN ("%FN%") DO ( set DO_NOT_REUSE_ME=%%i rem ZOMG (Part #2) WE use !! here to delay the expansion of rem CFG_OPTS, otherwise it remains "" for this loop. set CFG_OPTS=!CFG_OPTS! !DO_NOT_REUSE_ME! ) rem We use the value of the JAVACMD environment variable if defined set _JAVACMD=%JAVACMD% if "%_JAVACMD%"=="" ( if not "%JAVA_HOME%"=="" ( if exist "%JAVA_HOME%\bin\java.exe" set "_JAVACMD=%JAVA_HOME%\bin\java.exe" ) ) if "%_JAVACMD%"=="" set _JAVACMD=java rem We use the value of the JAVA_OPTS environment variable if defined, rather than the config. set _JAVA_OPTS=%JAVA_OPTS% if "%_JAVA_OPTS%"=="" set _JAVA_OPTS=%CFG_OPTS% :run "%_JAVACMD%" %_JAVA_OPTS% %SBT_OPTS% -cp "%SBT_HOME%jansi.jar;%SBT_HOME%sbt-launch.jar;%SBT_HOME%classes" SbtJansiLaunch %* if ERRORLEVEL 1 goto error goto end :error set ERROR_CODE=1 :end @endlocal exit /B %ERROR_CODE%
sameeragarwal/blinkdb_dev
sbt/sbt.bat
Batchfile
apache-2.0
1,376
/* * 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.cassandra.db.commitlog; import java.io.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.function.BiConsumer; import java.util.stream.Collectors; import java.util.zip.CRC32; import java.util.zip.Checksum; import com.google.common.collect.Iterables; import org.junit.*; import com.google.common.io.Files; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.apache.cassandra.SchemaLoader; import org.apache.cassandra.Util; import org.apache.cassandra.io.compress.ZstdCompressor; import org.apache.cassandra.io.util.FileUtils; import org.apache.cassandra.schema.TableId; import org.apache.cassandra.schema.TableMetadata; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.config.ParameterizedClass; import org.apache.cassandra.config.Config.DiskFailurePolicy; import org.apache.cassandra.db.*; import org.apache.cassandra.db.commitlog.CommitLogReplayer.CommitLogReplayException; import org.apache.cassandra.db.compaction.CompactionManager; import org.apache.cassandra.db.marshal.AsciiType; import org.apache.cassandra.db.marshal.BytesType; import org.apache.cassandra.db.partitions.PartitionUpdate; import org.apache.cassandra.db.rows.Row; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.io.FSWriteError; import org.apache.cassandra.io.compress.DeflateCompressor; import org.apache.cassandra.io.compress.LZ4Compressor; import org.apache.cassandra.io.compress.SnappyCompressor; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.cassandra.net.MessagingService; import org.apache.cassandra.schema.KeyspaceParams; import org.apache.cassandra.security.EncryptionContext; import org.apache.cassandra.security.EncryptionContextGenerator; import org.apache.cassandra.utils.Hex; import org.apache.cassandra.utils.JVMStabilityInspector; import org.apache.cassandra.utils.KillerForTests; import org.apache.cassandra.utils.Pair; import org.apache.cassandra.utils.vint.VIntCoding; import org.junit.After; import static org.apache.cassandra.utils.ByteBufferUtil.bytes; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @Ignore @RunWith(Parameterized.class) public abstract class CommitLogTest { protected static final String KEYSPACE1 = "CommitLogTest"; private static final String KEYSPACE2 = "CommitLogTestNonDurable"; protected static final String STANDARD1 = "Standard1"; private static final String STANDARD2 = "Standard2"; private static JVMStabilityInspector.Killer oldKiller; private static KillerForTests testKiller; public CommitLogTest(ParameterizedClass commitLogCompression, EncryptionContext encryptionContext) { DatabaseDescriptor.setCommitLogCompression(commitLogCompression); DatabaseDescriptor.setEncryptionContext(encryptionContext); } @Parameters() public static Collection<Object[]> generateData() { return Arrays.asList(new Object[][]{ {null, EncryptionContextGenerator.createDisabledContext()}, // No compression, no encryption {null, EncryptionContextGenerator.createContext(true)}, // Encryption {new ParameterizedClass(LZ4Compressor.class.getName(), Collections.emptyMap()), EncryptionContextGenerator.createDisabledContext()}, {new ParameterizedClass(SnappyCompressor.class.getName(), Collections.emptyMap()), EncryptionContextGenerator.createDisabledContext()}, {new ParameterizedClass(DeflateCompressor.class.getName(), Collections.emptyMap()), EncryptionContextGenerator.createDisabledContext()}, {new ParameterizedClass(ZstdCompressor.class.getName(), Collections.emptyMap()), EncryptionContextGenerator.createDisabledContext()}}); } public static void beforeClass() throws ConfigurationException { // Disable durable writes for system keyspaces to prevent system mutations, e.g. sstable_activity, // to end up in CL segments and cause unexpected results in this test wrt counting CL segments, // see CASSANDRA-12854 KeyspaceParams.DEFAULT_LOCAL_DURABLE_WRITES = false; SchemaLoader.prepareServer(); SchemaLoader.createKeyspace(KEYSPACE1, KeyspaceParams.simple(1), SchemaLoader.standardCFMD(KEYSPACE1, STANDARD1, 0, AsciiType.instance, BytesType.instance), SchemaLoader.standardCFMD(KEYSPACE1, STANDARD2, 0, AsciiType.instance, BytesType.instance)); SchemaLoader.createKeyspace(KEYSPACE2, KeyspaceParams.simpleTransient(1), SchemaLoader.standardCFMD(KEYSPACE1, STANDARD1, 0, AsciiType.instance, BytesType.instance), SchemaLoader.standardCFMD(KEYSPACE1, STANDARD2, 0, AsciiType.instance, BytesType.instance)); CompactionManager.instance.disableAutoCompaction(); testKiller = new KillerForTests(); // While we don't want the JVM to be nuked from under us on a test failure, we DO want some indication of // an error. If we hit a "Kill the JVM" condition while working with the CL when we don't expect it, an aggressive // KillerForTests will assertion out on us. oldKiller = JVMStabilityInspector.replaceKiller(testKiller); } @AfterClass public static void afterClass() { JVMStabilityInspector.replaceKiller(oldKiller); } @Before public void beforeTest() throws IOException { CommitLog.instance.resetUnsafe(true); } @After public void afterTest() { testKiller.reset(); } @Test public void testRecoveryWithEmptyLog() throws Exception { runExpecting(() -> { CommitLog.instance.recoverFiles(new File[]{ tmpFile(CommitLogDescriptor.current_version), tmpFile(CommitLogDescriptor.current_version) }); return null; }, CommitLogReplayException.class); } @Test public void testRecoveryWithEmptyFinalLog() throws Exception { CommitLog.instance.recoverFiles(tmpFile(CommitLogDescriptor.current_version)); } /** * Since commit log segments can be allocated before they're needed, the commit log file with the highest * id isn't neccesarily the last log that we wrote to. We should remove header only logs on recover so we * can tolerate truncated logs */ @Test public void testHeaderOnlyFileFiltering() throws Exception { File directory = Files.createTempDir(); CommitLogDescriptor desc1 = new CommitLogDescriptor(CommitLogDescriptor.current_version, 1, null, DatabaseDescriptor.getEncryptionContext()); CommitLogDescriptor desc2 = new CommitLogDescriptor(CommitLogDescriptor.current_version, 2, null, DatabaseDescriptor.getEncryptionContext()); ByteBuffer buffer; // this has a header and malformed data File file1 = new File(directory, desc1.fileName()); buffer = ByteBuffer.allocate(1024); CommitLogDescriptor.writeHeader(buffer, desc1); int pos = buffer.position(); CommitLogSegment.writeSyncMarker(desc1.id, buffer, buffer.position(), buffer.position(), buffer.position() + 128); buffer.position(pos + 8); buffer.putInt(5); buffer.putInt(6); try (OutputStream lout = new FileOutputStream(file1)) { lout.write(buffer.array()); } // this has only a header File file2 = new File(directory, desc2.fileName()); buffer = ByteBuffer.allocate(1024); CommitLogDescriptor.writeHeader(buffer, desc2); try (OutputStream lout = new FileOutputStream(file2)) { lout.write(buffer.array()); } // one corrupt file and one header only file should be ok runExpecting(() -> { CommitLog.instance.recoverFiles(file1, file2); return null; }, null); // 2 corrupt files and one header only file should fail runExpecting(() -> { CommitLog.instance.recoverFiles(file1, file1, file2); return null; }, CommitLogReplayException.class); } @Test public void testRecoveryWithZeroLog() throws Exception { testRecovery(new byte[10], CommitLogReplayException.class); } @Test public void testRecoveryWithShortLog() throws Exception { // force EOF while reading log testRecoveryWithBadSizeArgument(100, 10); } @Test public void testRecoveryWithShortSize() throws Exception { runExpecting(() -> { testRecovery(new byte[2], CommitLogDescriptor.current_version); return null; }, CommitLogReplayException.class); } @Test public void testRecoveryWithShortMutationSize() throws Exception { testRecoveryWithBadSizeArgument(9, 10); } private void testRecoveryWithGarbageLog() throws Exception { byte[] garbage = new byte[100]; (new java.util.Random()).nextBytes(garbage); testRecovery(garbage, CommitLogDescriptor.current_version); } @Test public void testRecoveryWithGarbageLog_fail() throws Exception { runExpecting(() -> { testRecoveryWithGarbageLog(); return null; }, CommitLogReplayException.class); } @Test public void testRecoveryWithGarbageLog_ignoredByProperty() throws Exception { try { System.setProperty(CommitLogReplayer.IGNORE_REPLAY_ERRORS_PROPERTY, "true"); testRecoveryWithGarbageLog(); } finally { System.clearProperty(CommitLogReplayer.IGNORE_REPLAY_ERRORS_PROPERTY); } } @Test public void testRecoveryWithBadSizeChecksum() throws Exception { Checksum checksum = new CRC32(); checksum.update(100); testRecoveryWithBadSizeArgument(100, 100, ~checksum.getValue()); } @Test public void testRecoveryWithNegativeSizeArgument() throws Exception { // garbage from a partial/bad flush could be read as a negative size even if there is no EOF testRecoveryWithBadSizeArgument(-10, 10); // negative size, but no EOF } @Test public void testDontDeleteIfDirty() throws Exception { Keyspace ks = Keyspace.open(KEYSPACE1); ColumnFamilyStore cfs1 = ks.getColumnFamilyStore(STANDARD1); ColumnFamilyStore cfs2 = ks.getColumnFamilyStore(STANDARD2); // Roughly 32 MB mutation Mutation m = new RowUpdateBuilder(cfs1.metadata(), 0, "k") .clustering("bytes") .add("val", ByteBuffer.allocate(DatabaseDescriptor.getCommitLogSegmentSize() / 4)) .build(); // Adding it 5 times CommitLog.instance.add(m); CommitLog.instance.add(m); CommitLog.instance.add(m); CommitLog.instance.add(m); CommitLog.instance.add(m); // Adding new mutation on another CF Mutation m2 = new RowUpdateBuilder(cfs2.metadata(), 0, "k") .clustering("bytes") .add("val", ByteBuffer.allocate(4)) .build(); CommitLog.instance.add(m2); assertEquals(2, CommitLog.instance.segmentManager.getActiveSegments().size()); TableId id2 = m2.getTableIds().iterator().next(); CommitLog.instance.discardCompletedSegments(id2, CommitLogPosition.NONE, CommitLog.instance.getCurrentPosition()); // Assert we still have both our segments assertEquals(2, CommitLog.instance.segmentManager.getActiveSegments().size()); } @Test public void testDeleteIfNotDirty() throws Exception { Keyspace ks = Keyspace.open(KEYSPACE1); ColumnFamilyStore cfs1 = ks.getColumnFamilyStore(STANDARD1); ColumnFamilyStore cfs2 = ks.getColumnFamilyStore(STANDARD2); // Roughly 32 MB mutation Mutation rm = new RowUpdateBuilder(cfs1.metadata(), 0, "k") .clustering("bytes") .add("val", ByteBuffer.allocate((DatabaseDescriptor.getCommitLogSegmentSize()/4) - 1)) .build(); // Adding it twice (won't change segment) CommitLog.instance.add(rm); CommitLog.instance.add(rm); assertEquals(1, CommitLog.instance.segmentManager.getActiveSegments().size()); // "Flush": this won't delete anything TableId id1 = rm.getTableIds().iterator().next(); CommitLog.instance.sync(true); CommitLog.instance.discardCompletedSegments(id1, CommitLogPosition.NONE, CommitLog.instance.getCurrentPosition()); assertEquals(1, CommitLog.instance.segmentManager.getActiveSegments().size()); // Adding new mutation on another CF, large enough (including CL entry overhead) that a new segment is created Mutation rm2 = new RowUpdateBuilder(cfs2.metadata(), 0, "k") .clustering("bytes") .add("val", ByteBuffer.allocate(DatabaseDescriptor.getMaxMutationSize() - 200)) .build(); CommitLog.instance.add(rm2); // also forces a new segment, since each entry-with-overhead is just under half the CL size CommitLog.instance.add(rm2); CommitLog.instance.add(rm2); Collection<CommitLogSegment> segments = CommitLog.instance.segmentManager.getActiveSegments(); assertEquals(String.format("Expected 3 segments but got %d (%s)", segments.size(), getDirtyCFIds(segments)), 3, segments.size()); // "Flush" second cf: The first segment should be deleted since we // didn't write anything on cf1 since last flush (and we flush cf2) TableId id2 = rm2.getTableIds().iterator().next(); CommitLog.instance.discardCompletedSegments(id2, CommitLogPosition.NONE, CommitLog.instance.getCurrentPosition()); segments = CommitLog.instance.segmentManager.getActiveSegments(); // Assert we still have both our segment assertEquals(String.format("Expected 1 segment but got %d (%s)", segments.size(), getDirtyCFIds(segments)), 1, segments.size()); } private String getDirtyCFIds(Collection<CommitLogSegment> segments) { return "Dirty tableIds: <" + String.join(", ", segments.stream() .map(CommitLogSegment::getDirtyTableIds) .flatMap(uuids -> uuids.stream()) .distinct() .map(uuid -> uuid.toString()).collect(Collectors.toList())) + ">"; } private static int getMaxRecordDataSize(String keyspace, ByteBuffer key, String cfName, String colName) { ColumnFamilyStore cfs = Keyspace.open(keyspace).getColumnFamilyStore(cfName); // We don't want to allocate a size of 0 as this is optimized under the hood and our computation would // break testEqualRecordLimit int allocSize = 1; Mutation rm = new RowUpdateBuilder(cfs.metadata(), 0, key) .clustering(colName) .add("val", ByteBuffer.allocate(allocSize)).build(); int max = DatabaseDescriptor.getMaxMutationSize(); max -= CommitLogSegment.ENTRY_OVERHEAD_SIZE; // log entry overhead // Note that the size of the value if vint encoded. So we first compute the ovehead of the mutation without the value and it's size int mutationOverhead = (int)Mutation.serializer.serializedSize(rm, MessagingService.current_version) - (VIntCoding.computeVIntSize(allocSize) + allocSize); max -= mutationOverhead; // Now, max is the max for both the value and it's size. But we want to know how much we can allocate, i.e. the size of the value. int sizeOfMax = VIntCoding.computeVIntSize(max); max -= sizeOfMax; assert VIntCoding.computeVIntSize(max) == sizeOfMax; // sanity check that we're still encoded with the size we though we would return max; } private static int getMaxRecordDataSize() { return getMaxRecordDataSize(KEYSPACE1, bytes("k"), STANDARD1, "bytes"); } // CASSANDRA-3615 @Test public void testEqualRecordLimit() throws Exception { ColumnFamilyStore cfs = Keyspace.open(KEYSPACE1).getColumnFamilyStore(STANDARD1); Mutation rm = new RowUpdateBuilder(cfs.metadata(), 0, "k") .clustering("bytes") .add("val", ByteBuffer.allocate(getMaxRecordDataSize())) .build(); CommitLog.instance.add(rm); } @Test(expected = IllegalArgumentException.class) public void testExceedRecordLimit() throws Exception { Keyspace ks = Keyspace.open(KEYSPACE1); ColumnFamilyStore cfs = ks.getColumnFamilyStore(STANDARD1); Mutation rm = new RowUpdateBuilder(cfs.metadata(), 0, "k") .clustering("bytes") .add("val", ByteBuffer.allocate(1 + getMaxRecordDataSize())) .build(); CommitLog.instance.add(rm); throw new AssertionError("mutation larger than limit was accepted"); } protected void testRecoveryWithBadSizeArgument(int size, int dataSize) throws Exception { Checksum checksum = new CRC32(); checksum.update(size); testRecoveryWithBadSizeArgument(size, dataSize, checksum.getValue()); } protected void testRecoveryWithBadSizeArgument(int size, int dataSize, long checksum) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(out); dout.writeInt(size); dout.writeLong(checksum); dout.write(new byte[dataSize]); dout.close(); testRecovery(out.toByteArray(), CommitLogReplayException.class); } /** * Create a temporary commit log file with an appropriate descriptor at the head. * * @return the commit log file reference and the first position after the descriptor in the file * (so that subsequent writes happen at the correct file location). */ protected Pair<File, Integer> tmpFile() throws IOException { EncryptionContext encryptionContext = DatabaseDescriptor.getEncryptionContext(); CommitLogDescriptor desc = new CommitLogDescriptor(CommitLogDescriptor.current_version, CommitLogSegment.getNextId(), DatabaseDescriptor.getCommitLogCompression(), encryptionContext); ByteBuffer buf = ByteBuffer.allocate(1024); CommitLogDescriptor.writeHeader(buf, desc, getAdditionalHeaders(encryptionContext)); buf.flip(); int positionAfterHeader = buf.limit() + 1; File logFile = new File(DatabaseDescriptor.getCommitLogLocation(), desc.fileName()); try (OutputStream lout = new FileOutputStream(logFile)) { lout.write(buf.array(), 0, buf.limit()); } return Pair.create(logFile, positionAfterHeader); } private Map<String, String> getAdditionalHeaders(EncryptionContext encryptionContext) { if (!encryptionContext.isEnabled()) return Collections.emptyMap(); // if we're testing encryption, we need to write out a cipher IV to the descriptor headers byte[] buf = new byte[16]; new Random().nextBytes(buf); return Collections.singletonMap(EncryptionContext.ENCRYPTION_IV, Hex.bytesToHex(buf)); } protected File tmpFile(int version) { File logFile = FileUtils.createTempFile("CommitLog-" + version + "-", ".log"); assert logFile.length() == 0; return logFile; } protected Void testRecovery(byte[] logData, int version) throws Exception { File logFile = tmpFile(version); try (OutputStream lout = new FileOutputStream(logFile)) { lout.write(logData); //statics make it annoying to test things correctly CommitLog.instance.recover(logFile.getPath()); //CASSANDRA-1119 / CASSANDRA-1179 throw on failure*/ } return null; } protected Void testRecovery(CommitLogDescriptor desc, byte[] logData) throws Exception { File logFile = tmpFile(desc.version); CommitLogDescriptor fromFile = CommitLogDescriptor.fromFileName(logFile.getName()); // Change id to match file. desc = new CommitLogDescriptor(desc.version, fromFile.id, desc.compression, desc.getEncryptionContext()); ByteBuffer buf = ByteBuffer.allocate(1024); CommitLogDescriptor.writeHeader(buf, desc, getAdditionalHeaders(desc.getEncryptionContext())); try (OutputStream lout = new FileOutputStream(logFile)) { lout.write(buf.array(), 0, buf.position()); lout.write(logData); //statics make it annoying to test things correctly CommitLog.instance.recover(logFile.getPath()); //CASSANDRA-1119 / CASSANDRA-1179 throw on failure*/ } return null; } @Test public void testRecoveryWithIdMismatch() throws Exception { CommitLogDescriptor desc = new CommitLogDescriptor(4, null, EncryptionContextGenerator.createDisabledContext()); File logFile = tmpFile(desc.version); ByteBuffer buf = ByteBuffer.allocate(1024); CommitLogDescriptor.writeHeader(buf, desc); try (OutputStream lout = new FileOutputStream(logFile)) { lout.write(buf.array(), 0, buf.position()); runExpecting(() -> { CommitLog.instance.recover(logFile.getPath()); //CASSANDRA-1119 / CASSANDRA-1179 throw on failure*/ return null; }, CommitLogReplayException.class); } } @Test public void testRecoveryWithBadCompressor() throws Exception { CommitLogDescriptor desc = new CommitLogDescriptor(4, new ParameterizedClass("UnknownCompressor", null), EncryptionContextGenerator.createDisabledContext()); runExpecting(() -> { testRecovery(desc, new byte[0]); return null; }, CommitLogReplayException.class); } protected void runExpecting(Callable<Void> r, Class<?> expected) { Throwable caught = null; try { r.call(); } catch (Throwable t) { if (expected != t.getClass()) throw new AssertionError("Expected exception " + expected + ", got " + t, t); caught = t; } if (expected != null && caught == null) Assert.fail("Expected exception " + expected + " but call completed successfully."); assertEquals("JVM kill state doesn't match expectation.", expected != null, testKiller.wasKilled()); } protected void testRecovery(final byte[] logData, Class<?> expected) throws Exception { ParameterizedClass commitLogCompression = DatabaseDescriptor.getCommitLogCompression(); EncryptionContext encryptionContext = DatabaseDescriptor.getEncryptionContext(); runExpecting(() -> testRecovery(logData, CommitLogDescriptor.current_version), expected); } @Test public void testTruncateWithoutSnapshot() throws ExecutionException, InterruptedException, IOException { boolean originalState = DatabaseDescriptor.isAutoSnapshot(); try { boolean prev = DatabaseDescriptor.isAutoSnapshot(); DatabaseDescriptor.setAutoSnapshot(false); Keyspace ks = Keyspace.open(KEYSPACE1); ColumnFamilyStore cfs1 = ks.getColumnFamilyStore(STANDARD1); ColumnFamilyStore cfs2 = ks.getColumnFamilyStore(STANDARD2); new RowUpdateBuilder(cfs1.metadata(), 0, "k").clustering("bytes").add("val", ByteBuffer.allocate(100)).build().applyUnsafe(); cfs1.truncateBlocking(); DatabaseDescriptor.setAutoSnapshot(prev); Mutation m2 = new RowUpdateBuilder(cfs2.metadata(), 0, "k") .clustering("bytes") .add("val", ByteBuffer.allocate(DatabaseDescriptor.getCommitLogSegmentSize() / 4)) .build(); for (int i = 0 ; i < 5 ; i++) CommitLog.instance.add(m2); assertEquals(2, CommitLog.instance.segmentManager.getActiveSegments().size()); CommitLogPosition position = CommitLog.instance.getCurrentPosition(); for (Keyspace keyspace : Keyspace.system()) for (ColumnFamilyStore syscfs : keyspace.getColumnFamilyStores()) CommitLog.instance.discardCompletedSegments(syscfs.metadata().id, CommitLogPosition.NONE, position); CommitLog.instance.discardCompletedSegments(cfs2.metadata().id, CommitLogPosition.NONE, position); assertEquals(1, CommitLog.instance.segmentManager.getActiveSegments().size()); } finally { DatabaseDescriptor.setAutoSnapshot(originalState); } } @Test public void testTruncateWithoutSnapshotNonDurable() throws IOException { boolean originalState = DatabaseDescriptor.getAutoSnapshot(); try { DatabaseDescriptor.setAutoSnapshot(false); Keyspace notDurableKs = Keyspace.open(KEYSPACE2); Assert.assertFalse(notDurableKs.getMetadata().params.durableWrites); ColumnFamilyStore cfs = notDurableKs.getColumnFamilyStore("Standard1"); new RowUpdateBuilder(cfs.metadata(), 0, "key1") .clustering("bytes").add("val", bytes("abcd")) .build() .applyUnsafe(); assertTrue(Util.getOnlyRow(Util.cmd(cfs).columns("val").build()) .cells().iterator().next().value().equals(bytes("abcd"))); cfs.truncateBlocking(); Util.assertEmpty(Util.cmd(cfs).columns("val").build()); } finally { DatabaseDescriptor.setAutoSnapshot(originalState); } } @Test public void replaySimple() throws IOException { int cellCount = 0; ColumnFamilyStore cfs = Keyspace.open(KEYSPACE1).getColumnFamilyStore(STANDARD1); final Mutation rm1 = new RowUpdateBuilder(cfs.metadata(), 0, "k1") .clustering("bytes") .add("val", bytes("this is a string")) .build(); cellCount += 1; CommitLog.instance.add(rm1); final Mutation rm2 = new RowUpdateBuilder(cfs.metadata(), 0, "k2") .clustering("bytes") .add("val", bytes("this is a string")) .build(); cellCount += 1; CommitLog.instance.add(rm2); CommitLog.instance.sync(true); SimpleCountingReplayer replayer = new SimpleCountingReplayer(CommitLog.instance, CommitLogPosition.NONE, cfs.metadata()); List<String> activeSegments = CommitLog.instance.getActiveSegmentNames(); Assert.assertFalse(activeSegments.isEmpty()); File[] files = new File(CommitLog.instance.segmentManager.storageDirectory).listFiles((file, name) -> activeSegments.contains(name)); replayer.replayFiles(files); assertEquals(cellCount, replayer.cells); } @Test public void replayWithDiscard() throws IOException { int cellCount = 0; int max = 1024; int discardPosition = (int)(max * .8); // an arbitrary number of entries that we'll skip on the replay CommitLogPosition commitLogPosition = null; ColumnFamilyStore cfs = Keyspace.open(KEYSPACE1).getColumnFamilyStore(STANDARD1); for (int i = 0; i < max; i++) { final Mutation rm1 = new RowUpdateBuilder(cfs.metadata(), 0, "k" + 1) .clustering("bytes") .add("val", bytes("this is a string")) .build(); CommitLogPosition position = CommitLog.instance.add(rm1); if (i == discardPosition) commitLogPosition = position; if (i > discardPosition) { cellCount += 1; } } CommitLog.instance.sync(true); SimpleCountingReplayer replayer = new SimpleCountingReplayer(CommitLog.instance, commitLogPosition, cfs.metadata()); List<String> activeSegments = CommitLog.instance.getActiveSegmentNames(); Assert.assertFalse(activeSegments.isEmpty()); File[] files = new File(CommitLog.instance.segmentManager.storageDirectory).listFiles((file, name) -> activeSegments.contains(name)); replayer.replayFiles(files); assertEquals(cellCount, replayer.cells); } class SimpleCountingReplayer extends CommitLogReplayer { private final CommitLogPosition filterPosition; private final TableMetadata metadata; int cells; int skipped; SimpleCountingReplayer(CommitLog commitLog, CommitLogPosition filterPosition, TableMetadata metadata) { super(commitLog, filterPosition, Collections.emptyMap(), ReplayFilter.create()); this.filterPosition = filterPosition; this.metadata = metadata; } @SuppressWarnings("resource") @Override public void handleMutation(Mutation m, int size, int entryLocation, CommitLogDescriptor desc) { // Filter out system writes that could flake the test. if (!KEYSPACE1.equals(m.getKeyspaceName())) return; if (entryLocation <= filterPosition.position) { // Skip over this mutation. skipped++; return; } for (PartitionUpdate partitionUpdate : m.getPartitionUpdates()) { // Only process mutations for the CF's we're testing against, since we can't deterministically predict // whether or not system keyspaces will be mutated during a test. if (partitionUpdate.metadata().name.equals(metadata.name)) { for (Row row : partitionUpdate) cells += Iterables.size(row.cells()); } } } } public void testUnwriteableFlushRecovery() throws ExecutionException, InterruptedException, IOException { CommitLog.instance.resetUnsafe(true); ColumnFamilyStore cfs = Keyspace.open(KEYSPACE1).getColumnFamilyStore(STANDARD1); DiskFailurePolicy oldPolicy = DatabaseDescriptor.getDiskFailurePolicy(); try { DatabaseDescriptor.setDiskFailurePolicy(DiskFailurePolicy.ignore); for (int i = 0 ; i < 5 ; i++) { new RowUpdateBuilder(cfs.metadata(), 0, "k") .clustering("c" + i).add("val", ByteBuffer.allocate(100)) .build() .apply(); if (i == 2) { try (Closeable c = Util.markDirectoriesUnwriteable(cfs)) { cfs.forceBlockingFlush(); } catch (Throwable t) { // expected. Cause (after some wrappings) should be a write error while (!(t instanceof FSWriteError)) t = t.getCause(); } } else cfs.forceBlockingFlush(); } } finally { DatabaseDescriptor.setDiskFailurePolicy(oldPolicy); } CommitLog.instance.sync(true); System.setProperty("cassandra.replayList", KEYSPACE1 + "." + STANDARD1); // Currently we don't attempt to re-flush a memtable that failed, thus make sure data is replayed by commitlog. // If retries work subsequent flushes should clear up error and this should change to expect 0. Assert.assertEquals(1, CommitLog.instance.resetUnsafe(false)); } public void testOutOfOrderFlushRecovery(BiConsumer<ColumnFamilyStore, Memtable> flushAction, boolean performCompaction) throws ExecutionException, InterruptedException, IOException { CommitLog.instance.resetUnsafe(true); ColumnFamilyStore cfs = Keyspace.open(KEYSPACE1).getColumnFamilyStore(STANDARD1); for (int i = 0 ; i < 5 ; i++) { new RowUpdateBuilder(cfs.metadata(), 0, "k") .clustering("c" + i).add("val", ByteBuffer.allocate(100)) .build() .apply(); Memtable current = cfs.getTracker().getView().getCurrentMemtable(); if (i == 2) current.makeUnflushable(); flushAction.accept(cfs, current); } if (performCompaction) cfs.forceMajorCompaction(); // Make sure metadata saves and reads fine for (SSTableReader reader : cfs.getLiveSSTables()) reader.reloadSSTableMetadata(); CommitLog.instance.sync(true); System.setProperty("cassandra.replayList", KEYSPACE1 + "." + STANDARD1); // In the absence of error, this should be 0 because forceBlockingFlush/forceRecycleAllSegments would have // persisted all data in the commit log. Because we know there was an error, there must be something left to // replay. Assert.assertEquals(1, CommitLog.instance.resetUnsafe(false)); } BiConsumer<ColumnFamilyStore, Memtable> flush = (cfs, current) -> { try { cfs.forceBlockingFlush(); } catch (Throwable t) { // expected after makeUnflushable. Cause (after some wrappings) should be a write error while (!(t instanceof FSWriteError)) t = t.getCause(); // Wait for started flushes to complete. cfs.switchMemtableIfCurrent(current); } }; BiConsumer<ColumnFamilyStore, Memtable> recycleSegments = (cfs, current) -> { // Move to new commit log segment and try to flush all data. Also delete segments that no longer contain // flushed data. // This does not stop on errors and should retain segments for which flushing failed. CommitLog.instance.forceRecycleAllSegments(); // Wait for started flushes to complete. cfs.switchMemtableIfCurrent(current); }; @Test public void testOutOfOrderFlushRecovery() throws ExecutionException, InterruptedException, IOException { testOutOfOrderFlushRecovery(flush, false); } @Test public void testOutOfOrderLogDiscard() throws ExecutionException, InterruptedException, IOException { testOutOfOrderFlushRecovery(recycleSegments, false); } @Test public void testOutOfOrderFlushRecoveryWithCompaction() throws ExecutionException, InterruptedException, IOException { testOutOfOrderFlushRecovery(flush, true); } @Test public void testOutOfOrderLogDiscardWithCompaction() throws ExecutionException, InterruptedException, IOException { testOutOfOrderFlushRecovery(recycleSegments, true); } }
cooldoger/cassandra
test/unit/org/apache/cassandra/db/commitlog/CommitLogTest.java
Java
apache-2.0
36,918
/* * Copyright (c) 2018, Adam <Adam@sigterm.info> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.script; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import static java.lang.Integer.parseInt; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; @Mojo( name = "build-index", defaultPhase = LifecyclePhase.GENERATE_RESOURCES ) public class IndexMojo extends AbstractMojo { @Parameter(required = true) private File archiveOverlayDirectory; @Parameter(required = true) private File indexFile; @Override public void execute() throws MojoExecutionException, MojoFailureException { try (DataOutputStream fout = new DataOutputStream(new FileOutputStream(indexFile))) { for (File indexFolder : archiveOverlayDirectory.listFiles()) { if (indexFolder.isDirectory()) { int indexId = parseInt(indexFolder.getName()); for (File archiveFile : indexFolder.listFiles()) { int archiveId; try { archiveId = parseInt(archiveFile.getName()); } catch (NumberFormatException ex) { continue; } fout.writeInt(indexId << 16 | archiveId); } } } fout.writeInt(-1); } catch (IOException ex) { throw new MojoExecutionException("error build index file", ex); } } }
Sethtroll/runelite
runelite-script-assembler-plugin/src/main/java/net/runelite/script/IndexMojo.java
Java
bsd-2-clause
2,911
cask 'busycontacts' do version :latest sha256 :no_check url 'http://www.busymac.com/download/BusyContacts.zip' name 'BusyContacts' homepage 'http://www.busymac.com/busycontacts/index.html' license :commercial pkg 'BusyContacts Installer.pkg' uninstall :pkgutil => 'com.busymac.busycontacts.pkg' end
mgryszko/homebrew-cask
Casks/busycontacts.rb
Ruby
bsd-2-clause
318
// Copyright (c) 2016 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #include "common/file_util.h" #include <sys/stat.h> #ifndef _MSC_VER #include <unistd.h> // close() #endif #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <ios> #include <string> namespace libwebm { std::string GetTempFileName() { #if !defined _MSC_VER && !defined __MINGW32__ std::string temp_file_name_template_str = std::string(std::getenv("TEST_TMPDIR") ? std::getenv("TEST_TMPDIR") : ".") + "/libwebm_temp.XXXXXX"; char* temp_file_name_template = new char[temp_file_name_template_str.length() + 1]; memset(temp_file_name_template, 0, temp_file_name_template_str.length() + 1); temp_file_name_template_str.copy(temp_file_name_template, temp_file_name_template_str.length(), 0); int fd = mkstemp(temp_file_name_template); std::string temp_file_name = (fd != -1) ? std::string(temp_file_name_template) : std::string(); delete[] temp_file_name_template; if (fd != -1) { close(fd); } return temp_file_name; #else char tmp_file_name[_MAX_PATH]; #if defined _MSC_VER || defined MINGW_HAS_SECURE_API errno_t err = tmpnam_s(tmp_file_name); #else char* fname_pointer = tmpnam(tmp_file_name); errno_t err = (fname_pointer == &tmp_file_name[0]) ? 0 : -1; #endif if (err == 0) { return std::string(tmp_file_name); } return std::string(); #endif } uint64_t GetFileSize(const std::string& file_name) { uint64_t file_size = 0; #ifndef _MSC_VER struct stat st; st.st_size = 0; if (stat(file_name.c_str(), &st) == 0) { #else struct _stat st; st.st_size = 0; if (_stat(file_name.c_str(), &st) == 0) { #endif file_size = st.st_size; } return file_size; } bool GetFileContents(const std::string& file_name, std::string* contents) { std::ifstream file(file_name.c_str()); *contents = std::string(static_cast<size_t>(GetFileSize(file_name)), 0); if (file.good() && contents->size()) { file.read(&(*contents)[0], contents->size()); } return !file.fail(); } TempFileDeleter::TempFileDeleter() { file_name_ = GetTempFileName(); } TempFileDeleter::~TempFileDeleter() { std::ifstream file(file_name_.c_str()); if (file.good()) { file.close(); std::remove(file_name_.c_str()); } } } // namespace libwebm
GrokImageCompression/aom
third_party/libwebm/common/file_util.cc
C++
bsd-2-clause
2,723
<?php /** * @group Kwc_Basic_LinkTag **/ class Kwc_Basic_LinkTag_Test extends Kwc_TestAbstract { public function setUp() { parent::setUp('Kwc_Basic_LinkTag_Root'); } public function testTemplateVars() { $c = $this->_root->getComponentById(1100)->getComponent(); $vars = $c->getTemplateVars(); $this->assertEquals('1100-child', $vars['linkTag']->componentId); } public function testUrlAndRel() { $c = $this->_root->getComponentById(1100); $c2 = $c->getChildComponent('-child'); $this->assertEquals('http://example.com', $c2->url); $this->assertEquals('foo', $c2->rel); $this->assertEquals('http://example.com', $c->url); $this->assertEquals('foo', $c->rel); } public function testHtml() { $c = $this->_root->getComponentById(1100); $c2 = $c->getChildComponent('-child'); $html = $c2->render(); $this->assertRegExp('<a .*?href="http://example.com" rel="foo">', $html); $html = $c->render(); $this->assertRegExp('<a .*?href="http://example.com" rel="foo">', $html); } public function testCacheChangeType() { $c = $this->_root->getComponentById('1101'); $this->assertRegExp('<a .*?href="http://example2.com" rel="foo">', $c->render()); $row = $c->getComponent()->getRow(); $row->component = 'test'; $row->save(); $this->_process(); $c = $this->_root->getComponentById('1101'); $c = $c->getChildComponent('-child'); $this->assertRegExp('<a .*?href="http://example.com" rel="foo">', $c->render()); $c = $this->_root->getComponentById('1101'); $this->assertRegExp('<a .*?href="http://example.com" rel="foo">', $c->render()); } }
yacon/koala-framework
tests/Kwc/Basic/LinkTag/Test.php
PHP
bsd-2-clause
1,811
; ; Copyright (c) 2016, Alliance for Open Media. All rights reserved ; ; This source code is subject to the terms of the BSD 2 Clause License and ; the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License ; was not distributed with this source code in the LICENSE file, you can ; obtain it at www.aomedia.org/license/software. If the Alliance for Open ; Media Patent License 1.0 was not distributed with this source code in the ; PATENTS file, you can obtain it at www.aomedia.org/license/patent. ; ; %define private_prefix av1 %include "third_party/x86inc/x86inc.asm" SECTION .text ; int64_t av1_block_error(int16_t *coeff, int16_t *dqcoeff, intptr_t block_size, ; int64_t *ssz) INIT_XMM sse2 cglobal block_error, 3, 3, 8, uqc, dqc, size, ssz pxor m4, m4 ; sse accumulator pxor m6, m6 ; ssz accumulator pxor m5, m5 ; dedicated zero register lea uqcq, [uqcq+sizeq*2] lea dqcq, [dqcq+sizeq*2] neg sizeq .loop: mova m2, [uqcq+sizeq*2] mova m0, [dqcq+sizeq*2] mova m3, [uqcq+sizeq*2+mmsize] mova m1, [dqcq+sizeq*2+mmsize] psubw m0, m2 psubw m1, m3 ; individual errors are max. 15bit+sign, so squares are 30bit, and ; thus the sum of 2 should fit in a 31bit integer (+ unused sign bit) pmaddwd m0, m0 pmaddwd m1, m1 pmaddwd m2, m2 pmaddwd m3, m3 ; accumulate in 64bit punpckldq m7, m0, m5 punpckhdq m0, m5 paddq m4, m7 punpckldq m7, m1, m5 paddq m4, m0 punpckhdq m1, m5 paddq m4, m7 punpckldq m7, m2, m5 paddq m4, m1 punpckhdq m2, m5 paddq m6, m7 punpckldq m7, m3, m5 paddq m6, m2 punpckhdq m3, m5 paddq m6, m7 paddq m6, m3 add sizeq, mmsize jl .loop ; accumulate horizontally and store in return value movhlps m5, m4 movhlps m7, m6 paddq m4, m5 paddq m6, m7 %if ARCH_X86_64 movq rax, m4 movq [sszq], m6 %else mov eax, sszm pshufd m5, m4, 0x1 movq [eax], m6 movd eax, m4 movd edx, m5 %endif RET ; Compute the sum of squared difference between two int16_t vectors. ; int64_t av1_block_error_fp(int16_t *coeff, int16_t *dqcoeff, ; intptr_t block_size) INIT_XMM sse2 cglobal block_error_fp, 3, 3, 6, uqc, dqc, size pxor m4, m4 ; sse accumulator pxor m5, m5 ; dedicated zero register lea uqcq, [uqcq+sizeq*2] lea dqcq, [dqcq+sizeq*2] neg sizeq .loop: mova m2, [uqcq+sizeq*2] mova m0, [dqcq+sizeq*2] mova m3, [uqcq+sizeq*2+mmsize] mova m1, [dqcq+sizeq*2+mmsize] psubw m0, m2 psubw m1, m3 ; individual errors are max. 15bit+sign, so squares are 30bit, and ; thus the sum of 2 should fit in a 31bit integer (+ unused sign bit) pmaddwd m0, m0 pmaddwd m1, m1 ; accumulate in 64bit punpckldq m3, m0, m5 punpckhdq m0, m5 paddq m4, m3 punpckldq m3, m1, m5 paddq m4, m0 punpckhdq m1, m5 paddq m4, m3 paddq m4, m1 add sizeq, mmsize jl .loop ; accumulate horizontally and store in return value movhlps m5, m4 paddq m4, m5 %if ARCH_X86_64 movq rax, m4 %else pshufd m5, m4, 0x1 movd eax, m4 movd edx, m5 %endif RET
luctrudeau/aom
av1/encoder/x86/error_sse2.asm
Assembly
bsd-2-clause
3,336
Sequel.migration do def up end def down end end
future-analytics/cartodb
db/migrate/20150729102936_create_ldap_configuration.rb
Ruby
bsd-3-clause
55
/* * Copyright (C) 2010, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ #include "third_party/blink/renderer/modules/webaudio/audio_processing_event.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_audio_processing_event_init.h" #include "third_party/blink/renderer/core/event_type_names.h" namespace blink { AudioProcessingEvent* AudioProcessingEvent::Create() { return MakeGarbageCollected<AudioProcessingEvent>(); } AudioProcessingEvent* AudioProcessingEvent::Create(AudioBuffer* input_buffer, AudioBuffer* output_buffer, double playback_time) { return MakeGarbageCollected<AudioProcessingEvent>(input_buffer, output_buffer, playback_time); } AudioProcessingEvent* AudioProcessingEvent::Create( const AtomicString& type, const AudioProcessingEventInit* initializer) { return MakeGarbageCollected<AudioProcessingEvent>(type, initializer); } AudioProcessingEvent::AudioProcessingEvent() = default; AudioProcessingEvent::AudioProcessingEvent(AudioBuffer* input_buffer, AudioBuffer* output_buffer, double playback_time) : Event(event_type_names::kAudioprocess, Bubbles::kYes, Cancelable::kNo), input_buffer_(input_buffer), output_buffer_(output_buffer), playback_time_(playback_time) {} AudioProcessingEvent::AudioProcessingEvent( const AtomicString& type, const AudioProcessingEventInit* initializer) : Event(type, initializer) { input_buffer_ = initializer->inputBuffer(); output_buffer_ = initializer->outputBuffer(); playback_time_ = initializer->playbackTime(); } AudioProcessingEvent::~AudioProcessingEvent() = default; const AtomicString& AudioProcessingEvent::InterfaceName() const { return event_interface_names::kAudioProcessingEvent; } void AudioProcessingEvent::Trace(Visitor* visitor) const { visitor->Trace(input_buffer_); visitor->Trace(output_buffer_); Event::Trace(visitor); } } // namespace blink
scheib/chromium
third_party/blink/renderer/modules/webaudio/audio_processing_event.cc
C++
bsd-3-clause
3,431
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NetworkInformation_h #define NetworkInformation_h #include "core/dom/ActiveDOMObject.h" #include "core/events/EventTarget.h" #include "core/page/NetworkStateNotifier.h" #include "public/platform/WebConnectionType.h" namespace blink { class ExecutionContext; class NetworkInformation FINAL : public RefCountedGarbageCollectedWillBeGarbageCollectedFinalized<NetworkInformation> , public ActiveDOMObject , public EventTargetWithInlineData , public NetworkStateNotifier::NetworkStateObserver { DEFINE_EVENT_TARGET_REFCOUNTING_WILL_BE_REMOVED(RefCountedGarbageCollected<NetworkInformation>); DEFINE_WRAPPERTYPEINFO(); WILL_BE_USING_GARBAGE_COLLECTED_MIXIN(NetworkInformation); public: static NetworkInformation* create(ExecutionContext*); virtual ~NetworkInformation(); String type() const; virtual void connectionTypeChange(WebConnectionType) OVERRIDE; // EventTarget overrides. virtual const AtomicString& interfaceName() const OVERRIDE; virtual ExecutionContext* executionContext() const OVERRIDE; virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture = false) OVERRIDE; virtual bool removeEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture = false) OVERRIDE; virtual void removeAllEventListeners() OVERRIDE; // ActiveDOMObject overrides. virtual bool hasPendingActivity() const OVERRIDE; virtual void stop() OVERRIDE; DEFINE_ATTRIBUTE_EVENT_LISTENER(typechange); private: explicit NetworkInformation(ExecutionContext*); void startObserving(); void stopObserving(); // Touched only on context thread. WebConnectionType m_type; // Whether this object is listening for events from NetworkStateNotifier. bool m_observing; // Whether ActiveDOMObject::stop has been called. bool m_contextStopped; }; } // namespace blink #endif // NetworkInformation_h
hgl888/blink-crosswalk-efl
Source/modules/netinfo/NetworkInformation.h
C
bsd-3-clause
2,141
package edu.gemini.spModel.core /** * A type class that combines conversion and construction for convenience. */ trait IsoAngle[A] extends ToDegrees[A] with FromDegrees[A] { def add(a0: A, a1: A): A = fromDegrees(toDegrees(a0) + toDegrees(a1)) def subtract(a0: A, a1: A): A = fromDegrees(toDegrees(a0) - toDegrees(a1)) def multiply(a0: A, factor: Double): A = fromDegrees(toDegrees(a0) * factor) def flip(a: A): A = fromDegrees(toDegrees(a) + 180.0) }
arturog8m/ocs
bundle/edu.gemini.spModel.core/src/main/scala/edu/gemini/spModel/core/IsoAngle.scala
Scala
bsd-3-clause
482
package edu.gemini.model.p1.targetio.impl import edu.gemini.model.p1.immutable.NonSiderealTarget import edu.gemini.model.p1.targetio.api.{DataSourceError, FileType, TargetWriter} import java.io.{OutputStream, File} import edu.gemini.model.p1.targetio.table.{Column, TableWriter} object NonSiderealWriter extends TargetWriter[NonSiderealTarget] { private val all = NonSiderealColumns.REQUIRED ++ List(NonSiderealColumns.MAG) private def cols(targets: Traversable[NonSiderealTarget]): List[Column[NamedEphemeris,_]] = if (targets.exists(_.ephemeris.exists(_.magnitude.isDefined))) all else NonSiderealColumns.REQUIRED def write(targets: Iterable[NonSiderealTarget], file: File, ftype: FileType): Either[DataSourceError, Unit] = TableWriter.write(toElements(targets), cols(targets), file, ftype) def write(targets: Iterable[NonSiderealTarget], os: OutputStream, ftype: FileType): Either[DataSourceError, Unit] = TableWriter.write(toElements(targets), cols(targets), os, ftype) private def toElements(targets: Iterable[NonSiderealTarget]): Iterable[NamedEphemeris] = targets.zipWithIndex flatMap { case (target, index) => target.ephemeris map { ep => NamedEphemeris(index, target.name, ep) } } }
arturog8m/ocs
bundle/edu.gemini.model.p1.targetio/src/main/scala/edu/gemini/model/p1/targetio/impl/NonSiderealWriter.scala
Scala
bsd-3-clause
1,233
/* * Copyright (c) 2013 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2004-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Ali Saidi * Andrew Schultz * Miguel Serrano */ /* @file * A single PCI device configuration space entry. */ #include <list> #include <string> #include <vector> #include "base/inifile.hh" #include "base/intmath.hh" #include "base/misc.hh" #include "base/str.hh" #include "base/trace.hh" #include "debug/PCIDEV.hh" #include "dev/alpha/tsunamireg.h" #include "dev/pciconfigall.hh" #include "dev/pcidev.hh" #include "mem/packet.hh" #include "mem/packet_access.hh" #include "sim/byteswap.hh" #include "sim/core.hh" PciDevice::PciConfigPort::PciConfigPort(PciDevice *dev, int busid, int devid, int funcid, Platform *p) : SimpleTimingPort(dev->name() + "-pciconf", dev), device(dev), platform(p), busId(busid), deviceId(devid), functionId(funcid) { configAddr = platform->calcPciConfigAddr(busId, deviceId, functionId); } Tick PciDevice::PciConfigPort::recvAtomic(PacketPtr pkt) { assert(pkt->getAddr() >= configAddr && pkt->getAddr() < configAddr + PCI_CONFIG_SIZE); // @todo someone should pay for this pkt->busFirstWordDelay = pkt->busLastWordDelay = 0; return pkt->isRead() ? device->readConfig(pkt) : device->writeConfig(pkt); } AddrRangeList PciDevice::PciConfigPort::getAddrRanges() const { AddrRangeList ranges; if (configAddr != ULL(-1)) ranges.push_back(RangeSize(configAddr, PCI_CONFIG_SIZE+1)); return ranges; } PciDevice::PciDevice(const Params *p) : DmaDevice(p), PMCAP_BASE(p->PMCAPBaseOffset), MSICAP_BASE(p->MSICAPBaseOffset), MSIXCAP_BASE(p->MSIXCAPBaseOffset), PXCAP_BASE(p->PXCAPBaseOffset), platform(p->platform), pioDelay(p->pio_latency), configDelay(p->config_latency), configPort(this, params()->pci_bus, params()->pci_dev, params()->pci_func, params()->platform) { config.vendor = htole(p->VendorID); config.device = htole(p->DeviceID); config.command = htole(p->Command); config.status = htole(p->Status); config.revision = htole(p->Revision); config.progIF = htole(p->ProgIF); config.subClassCode = htole(p->SubClassCode); config.classCode = htole(p->ClassCode); config.cacheLineSize = htole(p->CacheLineSize); config.latencyTimer = htole(p->LatencyTimer); config.headerType = htole(p->HeaderType); config.bist = htole(p->BIST); config.baseAddr[0] = htole(p->BAR0); config.baseAddr[1] = htole(p->BAR1); config.baseAddr[2] = htole(p->BAR2); config.baseAddr[3] = htole(p->BAR3); config.baseAddr[4] = htole(p->BAR4); config.baseAddr[5] = htole(p->BAR5); config.cardbusCIS = htole(p->CardbusCIS); config.subsystemVendorID = htole(p->SubsystemVendorID); config.subsystemID = htole(p->SubsystemID); config.expansionROM = htole(p->ExpansionROM); config.capabilityPtr = htole(p->CapabilityPtr); // Zero out the 7 bytes of reserved space in the PCI Config space register. bzero(config.reserved, 7*sizeof(uint8_t)); config.interruptLine = htole(p->InterruptLine); config.interruptPin = htole(p->InterruptPin); config.minimumGrant = htole(p->MinimumGrant); config.maximumLatency = htole(p->MaximumLatency); // Initialize the capability lists // These structs are bitunions, meaning the data is stored in host // endianess and must be converted to Little Endian when accessed // by the guest // PMCAP pmcap.pid.cid = p->PMCAPCapId; pmcap.pid.next = p->PMCAPNextCapability; pmcap.pc = p->PMCAPCapabilities; pmcap.pmcs = p->PMCAPCtrlStatus; // MSICAP msicap.mid.cid = p->MSICAPCapId; msicap.mid.next = p->MSICAPNextCapability; msicap.mc = p->MSICAPMsgCtrl; msicap.ma = p->MSICAPMsgAddr; msicap.mua = p->MSICAPMsgUpperAddr; msicap.md = p->MSICAPMsgData; msicap.mmask = p->MSICAPMaskBits; msicap.mpend = p->MSICAPPendingBits; // MSIXCAP msixcap.mxid.cid = p->MSIXCAPCapId; msixcap.mxid.next = p->MSIXCAPNextCapability; msixcap.mxc = p->MSIXMsgCtrl; msixcap.mtab = p->MSIXTableOffset; msixcap.mpba = p->MSIXPbaOffset; // allocate MSIX structures if MSIXCAP_BASE // indicates the MSIXCAP is being used by having a // non-zero base address. // The MSIX tables are stored by the guest in // little endian byte-order as according the // PCIe specification. Make sure to take the proper // actions when manipulating these tables on the host if (MSIXCAP_BASE != 0x0) { int msix_vecs = msixcap.mxc.ts + 1; MSIXTable tmp1 = {{0UL,0UL,0UL,0UL}}; msix_table.resize(msix_vecs, tmp1); MSIXPbaEntry tmp2 = {0}; int pba_size = msix_vecs / MSIXVECS_PER_PBA; if ((msix_vecs % MSIXVECS_PER_PBA) > 0) { pba_size++; } msix_pba.resize(pba_size, tmp2); } // PXCAP pxcap.pxid.cid = p->PXCAPCapId; pxcap.pxid.next = p->PXCAPNextCapability; pxcap.pxcap = p->PXCAPCapabilities; pxcap.pxdcap = p->PXCAPDevCapabilities; pxcap.pxdc = p->PXCAPDevCtrl; pxcap.pxds = p->PXCAPDevStatus; pxcap.pxlcap = p->PXCAPLinkCap; pxcap.pxlc = p->PXCAPLinkCtrl; pxcap.pxls = p->PXCAPLinkStatus; pxcap.pxdcap2 = p->PXCAPDevCap2; pxcap.pxdc2 = p->PXCAPDevCtrl2; BARSize[0] = p->BAR0Size; BARSize[1] = p->BAR1Size; BARSize[2] = p->BAR2Size; BARSize[3] = p->BAR3Size; BARSize[4] = p->BAR4Size; BARSize[5] = p->BAR5Size; legacyIO[0] = p->BAR0LegacyIO; legacyIO[1] = p->BAR1LegacyIO; legacyIO[2] = p->BAR2LegacyIO; legacyIO[3] = p->BAR3LegacyIO; legacyIO[4] = p->BAR4LegacyIO; legacyIO[5] = p->BAR5LegacyIO; for (int i = 0; i < 6; ++i) { if (legacyIO[i]) { BARAddrs[i] = platform->calcPciIOAddr(letoh(config.baseAddr[i])); config.baseAddr[i] = 0; } else { BARAddrs[i] = 0; uint32_t barsize = BARSize[i]; if (barsize != 0 && !isPowerOf2(barsize)) { fatal("BAR %d size %d is not a power of 2\n", i, BARSize[i]); } } } platform->registerPciDevice(p->pci_bus, p->pci_dev, p->pci_func, letoh(config.interruptLine)); } void PciDevice::init() { if (!configPort.isConnected()) panic("PCI config port on %s not connected to anything!\n", name()); configPort.sendRangeChange(); DmaDevice::init(); } unsigned int PciDevice::drain(DrainManager *dm) { unsigned int count; count = pioPort.drain(dm) + dmaPort.drain(dm) + configPort.drain(dm); if (count) setDrainState(Drainable::Draining); else setDrainState(Drainable::Drained); return count; } Tick PciDevice::readConfig(PacketPtr pkt) { int offset = pkt->getAddr() & PCI_CONFIG_SIZE; if (offset >= PCI_DEVICE_SPECIFIC) panic("Device specific PCI config space not implemented!\n"); pkt->allocate(); switch (pkt->getSize()) { case sizeof(uint8_t): pkt->set<uint8_t>(config.data[offset]); DPRINTF(PCIDEV, "readConfig: dev %#x func %#x reg %#x 1 bytes: data = %#x\n", params()->pci_dev, params()->pci_func, offset, (uint32_t)pkt->get<uint8_t>()); break; case sizeof(uint16_t): pkt->set<uint16_t>(*(uint16_t*)&config.data[offset]); DPRINTF(PCIDEV, "readConfig: dev %#x func %#x reg %#x 2 bytes: data = %#x\n", params()->pci_dev, params()->pci_func, offset, (uint32_t)pkt->get<uint16_t>()); break; case sizeof(uint32_t): pkt->set<uint32_t>(*(uint32_t*)&config.data[offset]); DPRINTF(PCIDEV, "readConfig: dev %#x func %#x reg %#x 4 bytes: data = %#x\n", params()->pci_dev, params()->pci_func, offset, (uint32_t)pkt->get<uint32_t>()); break; default: panic("invalid access size(?) for PCI configspace!\n"); } pkt->makeAtomicResponse(); return configDelay; } AddrRangeList PciDevice::getAddrRanges() const { AddrRangeList ranges; int x = 0; for (x = 0; x < 6; x++) if (BARAddrs[x] != 0) ranges.push_back(RangeSize(BARAddrs[x],BARSize[x])); return ranges; } Tick PciDevice::writeConfig(PacketPtr pkt) { int offset = pkt->getAddr() & PCI_CONFIG_SIZE; if (offset >= PCI_DEVICE_SPECIFIC) panic("Device specific PCI config space not implemented!\n"); switch (pkt->getSize()) { case sizeof(uint8_t): switch (offset) { case PCI0_INTERRUPT_LINE: config.interruptLine = pkt->get<uint8_t>(); break; case PCI_CACHE_LINE_SIZE: config.cacheLineSize = pkt->get<uint8_t>(); break; case PCI_LATENCY_TIMER: config.latencyTimer = pkt->get<uint8_t>(); break; /* Do nothing for these read-only registers */ case PCI0_INTERRUPT_PIN: case PCI0_MINIMUM_GRANT: case PCI0_MAXIMUM_LATENCY: case PCI_CLASS_CODE: case PCI_REVISION_ID: break; default: panic("writing to a read only register"); } DPRINTF(PCIDEV, "writeConfig: dev %#x func %#x reg %#x 1 bytes: data = %#x\n", params()->pci_dev, params()->pci_func, offset, (uint32_t)pkt->get<uint8_t>()); break; case sizeof(uint16_t): switch (offset) { case PCI_COMMAND: config.command = pkt->get<uint8_t>(); break; case PCI_STATUS: config.status = pkt->get<uint8_t>(); break; case PCI_CACHE_LINE_SIZE: config.cacheLineSize = pkt->get<uint8_t>(); break; default: panic("writing to a read only register"); } DPRINTF(PCIDEV, "writeConfig: dev %#x func %#x reg %#x 2 bytes: data = %#x\n", params()->pci_dev, params()->pci_func, offset, (uint32_t)pkt->get<uint16_t>()); break; case sizeof(uint32_t): switch (offset) { case PCI0_BASE_ADDR0: case PCI0_BASE_ADDR1: case PCI0_BASE_ADDR2: case PCI0_BASE_ADDR3: case PCI0_BASE_ADDR4: case PCI0_BASE_ADDR5: { int barnum = BAR_NUMBER(offset); if (!legacyIO[barnum]) { // convert BAR values to host endianness uint32_t he_old_bar = letoh(config.baseAddr[barnum]); uint32_t he_new_bar = letoh(pkt->get<uint32_t>()); uint32_t bar_mask = BAR_IO_SPACE(he_old_bar) ? BAR_IO_MASK : BAR_MEM_MASK; // Writing 0xffffffff to a BAR tells the card to set the // value of the bar to a bitmask indicating the size of // memory it needs if (he_new_bar == 0xffffffff) { he_new_bar = ~(BARSize[barnum] - 1); } else { // does it mean something special to write 0 to a BAR? he_new_bar &= ~bar_mask; if (he_new_bar) { BARAddrs[barnum] = BAR_IO_SPACE(he_old_bar) ? platform->calcPciIOAddr(he_new_bar) : platform->calcPciMemAddr(he_new_bar); pioPort.sendRangeChange(); } } config.baseAddr[barnum] = htole((he_new_bar & ~bar_mask) | (he_old_bar & bar_mask)); } } break; case PCI0_ROM_BASE_ADDR: if (letoh(pkt->get<uint32_t>()) == 0xfffffffe) config.expansionROM = htole((uint32_t)0xffffffff); else config.expansionROM = pkt->get<uint32_t>(); break; case PCI_COMMAND: // This could also clear some of the error bits in the Status // register. However they should never get set, so lets ignore // it for now config.command = pkt->get<uint32_t>(); break; default: DPRINTF(PCIDEV, "Writing to a read only register"); } DPRINTF(PCIDEV, "writeConfig: dev %#x func %#x reg %#x 4 bytes: data = %#x\n", params()->pci_dev, params()->pci_func, offset, (uint32_t)pkt->get<uint32_t>()); break; default: panic("invalid access size(?) for PCI configspace!\n"); } pkt->makeAtomicResponse(); return configDelay; } void PciDevice::serialize(std::ostream &os) { SERIALIZE_ARRAY(BARSize, sizeof(BARSize) / sizeof(BARSize[0])); SERIALIZE_ARRAY(BARAddrs, sizeof(BARAddrs) / sizeof(BARAddrs[0])); SERIALIZE_ARRAY(config.data, sizeof(config.data) / sizeof(config.data[0])); // serialize the capability list registers paramOut(os, csprintf("pmcap.pid"), uint16_t(pmcap.pid)); paramOut(os, csprintf("pmcap.pc"), uint16_t(pmcap.pc)); paramOut(os, csprintf("pmcap.pmcs"), uint16_t(pmcap.pmcs)); paramOut(os, csprintf("msicap.mid"), uint16_t(msicap.mid)); paramOut(os, csprintf("msicap.mc"), uint16_t(msicap.mc)); paramOut(os, csprintf("msicap.ma"), uint32_t(msicap.ma)); SERIALIZE_SCALAR(msicap.mua); paramOut(os, csprintf("msicap.md"), uint16_t(msicap.md)); SERIALIZE_SCALAR(msicap.mmask); SERIALIZE_SCALAR(msicap.mpend); paramOut(os, csprintf("msixcap.mxid"), uint16_t(msixcap.mxid)); paramOut(os, csprintf("msixcap.mxc"), uint16_t(msixcap.mxc)); paramOut(os, csprintf("msixcap.mtab"), uint32_t(msixcap.mtab)); paramOut(os, csprintf("msixcap.mpba"), uint32_t(msixcap.mpba)); // Only serialize if we have a non-zero base address if (MSIXCAP_BASE != 0x0) { int msix_array_size = msixcap.mxc.ts + 1; int pba_array_size = msix_array_size/MSIXVECS_PER_PBA; if ((msix_array_size % MSIXVECS_PER_PBA) > 0) { pba_array_size++; } SERIALIZE_SCALAR(msix_array_size); SERIALIZE_SCALAR(pba_array_size); for (int i = 0; i < msix_array_size; i++) { paramOut(os, csprintf("msix_table[%d].addr_lo", i), msix_table[i].fields.addr_lo); paramOut(os, csprintf("msix_table[%d].addr_hi", i), msix_table[i].fields.addr_hi); paramOut(os, csprintf("msix_table[%d].msg_data", i), msix_table[i].fields.msg_data); paramOut(os, csprintf("msix_table[%d].vec_ctrl", i), msix_table[i].fields.vec_ctrl); } for (int i = 0; i < pba_array_size; i++) { paramOut(os, csprintf("msix_pba[%d].bits", i), msix_pba[i].bits); } } paramOut(os, csprintf("pxcap.pxid"), uint16_t(pxcap.pxid)); paramOut(os, csprintf("pxcap.pxcap"), uint16_t(pxcap.pxcap)); paramOut(os, csprintf("pxcap.pxdcap"), uint32_t(pxcap.pxdcap)); paramOut(os, csprintf("pxcap.pxdc"), uint16_t(pxcap.pxdc)); paramOut(os, csprintf("pxcap.pxds"), uint16_t(pxcap.pxds)); paramOut(os, csprintf("pxcap.pxlcap"), uint32_t(pxcap.pxlcap)); paramOut(os, csprintf("pxcap.pxlc"), uint16_t(pxcap.pxlc)); paramOut(os, csprintf("pxcap.pxls"), uint16_t(pxcap.pxls)); paramOut(os, csprintf("pxcap.pxdcap2"), uint32_t(pxcap.pxdcap2)); paramOut(os, csprintf("pxcap.pxdc2"), uint32_t(pxcap.pxdc2)); } void PciDevice::unserialize(Checkpoint *cp, const std::string &section) { UNSERIALIZE_ARRAY(BARSize, sizeof(BARSize) / sizeof(BARSize[0])); UNSERIALIZE_ARRAY(BARAddrs, sizeof(BARAddrs) / sizeof(BARAddrs[0])); UNSERIALIZE_ARRAY(config.data, sizeof(config.data) / sizeof(config.data[0])); // unserialize the capability list registers uint16_t tmp16; uint32_t tmp32; paramIn(cp, section, csprintf("pmcap.pid"), tmp16); pmcap.pid = tmp16; paramIn(cp, section, csprintf("pmcap.pc"), tmp16); pmcap.pc = tmp16; paramIn(cp, section, csprintf("pmcap.pmcs"), tmp16); pmcap.pmcs = tmp16; paramIn(cp, section, csprintf("msicap.mid"), tmp16); msicap.mid = tmp16; paramIn(cp, section, csprintf("msicap.mc"), tmp16); msicap.mc = tmp16; paramIn(cp, section, csprintf("msicap.ma"), tmp32); msicap.ma = tmp32; UNSERIALIZE_SCALAR(msicap.mua); paramIn(cp, section, csprintf("msicap.md"), tmp16);; msicap.md = tmp16; UNSERIALIZE_SCALAR(msicap.mmask); UNSERIALIZE_SCALAR(msicap.mpend); paramIn(cp, section, csprintf("msixcap.mxid"), tmp16); msixcap.mxid = tmp16; paramIn(cp, section, csprintf("msixcap.mxc"), tmp16); msixcap.mxc = tmp16; paramIn(cp, section, csprintf("msixcap.mtab"), tmp32); msixcap.mtab = tmp32; paramIn(cp, section, csprintf("msixcap.mpba"), tmp32); msixcap.mpba = tmp32; // Only allocate if MSIXCAP_BASE is not 0x0 if (MSIXCAP_BASE != 0x0) { int msix_array_size; int pba_array_size; UNSERIALIZE_SCALAR(msix_array_size); UNSERIALIZE_SCALAR(pba_array_size); MSIXTable tmp1 = {{0UL, 0UL, 0UL, 0UL}}; msix_table.resize(msix_array_size, tmp1); MSIXPbaEntry tmp2 = {0}; msix_pba.resize(pba_array_size, tmp2); for (int i = 0; i < msix_array_size; i++) { paramIn(cp, section, csprintf("msix_table[%d].addr_lo", i), msix_table[i].fields.addr_lo); paramIn(cp, section, csprintf("msix_table[%d].addr_hi", i), msix_table[i].fields.addr_hi); paramIn(cp, section, csprintf("msix_table[%d].msg_data", i), msix_table[i].fields.msg_data); paramIn(cp, section, csprintf("msix_table[%d].vec_ctrl", i), msix_table[i].fields.vec_ctrl); } for (int i = 0; i < pba_array_size; i++) { paramIn(cp, section, csprintf("msix_pba[%d].bits", i), msix_pba[i].bits); } } paramIn(cp, section, csprintf("pxcap.pxid"), tmp16); pxcap.pxid = tmp16; paramIn(cp, section, csprintf("pxcap.pxcap"), tmp16); pxcap.pxcap = tmp16; paramIn(cp, section, csprintf("pxcap.pxdcap"), tmp32); pxcap.pxdcap = tmp32; paramIn(cp, section, csprintf("pxcap.pxdc"), tmp16); pxcap.pxdc = tmp16; paramIn(cp, section, csprintf("pxcap.pxds"), tmp16); pxcap.pxds = tmp16; paramIn(cp, section, csprintf("pxcap.pxlcap"), tmp32); pxcap.pxlcap = tmp32; paramIn(cp, section, csprintf("pxcap.pxlc"), tmp16); pxcap.pxlc = tmp16; paramIn(cp, section, csprintf("pxcap.pxls"), tmp16); pxcap.pxls = tmp16; paramIn(cp, section, csprintf("pxcap.pxdcap2"), tmp32); pxcap.pxdcap2 = tmp32; paramIn(cp, section, csprintf("pxcap.pxdc2"), tmp32); pxcap.pxdc2 = tmp32; pioPort.sendRangeChange(); }
BIT-SYS/gem5-spm-module
src/dev/pcidev.cc
C++
bsd-3-clause
21,256
ms.dispatch = function(that) { var types = {}; that.on = function(type, handler) { var listeners = types[type] || (types[type] = []); for (var i = 0; i < listeners.length; i++) { if (listeners[i].handler == handler) return that; // already registered } listeners.push({handler: handler, on: true}); return that; }; that.off = function(type, handler) { var listeners = types[type]; if (listeners) for (var i = 0; i < listeners.length; i++) { var l = listeners[i]; if (l.handler == handler) { l.on = false; listeners.splice(i, 1); break; } } return that; }; return function(event) { var listeners = types[event.type]; if (!listeners) return; listeners = listeners.slice(); // defensive copy for (var i = 0; i < listeners.length; i++) { var l = listeners[i]; if (l.on) l.handler.call(that, event); } }; };
mapsense/mapsense.js
src/Dispatch.js
JavaScript
bsd-3-clause
936
<!DOCTYPE html> <!-- Copyright (c) 2013 Samsung Electronics Co., Ltd. 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. Authors: Beata Koziarek <b.koziarek@samsung.com> Mariusz Polasinski <m.polasinski@samsung.com> --> <html> <head> <title>File_readAsText</title> <meta charset="utf-8"/> <script src="support/unitcommon.js"></script> <script src="support/filesystem_common.js"></script> </head> <body> <div id="log"></div> <script type="text/javascript"> //==== TEST: File_readAsText //==== LABEL Check if File::readAsText() method works properly without errorCallback //==== SPEC: Tizen Web API:IO:Filesystem:File:readAsText M //==== SPEC_URL https://developer.tizen.org/help/topic/org.tizen.web.device.apireference/tizen/filesystem.html //==== TEST_CRITERIA MMINA MR var t = async_test(document.title), resolveSuccess, resolveError, stringInFile = "HelloWorld", readAsTextSuccess, file, fsTestFileName = getFileName("testReadAsTextAgain.txt"), retVal = null; t.step(function () { readAsTextSuccess = t.step_func(function (str) { assert_equals(retVal, undefined, "incorrect returned value"); assert_equals(str, stringInFile, "incorrect read value"); t.done(); }); resolveSuccess = t.step_func(function (dir) { file = dir.createFile(fsTestFileName); file.openStream("w", t.step_func(function (fs) { fs.write(stringInFile); fs.close(); retVal = file.readAsText(readAsTextSuccess); })); }); resolveError = t.step_func(function (error) { assert_unreached("resolve() error callback invoked: name: " + error.name + ", msg: " + error.message); }); prepareForTesting(t, function () { tizen.filesystem.resolve("documents", resolveSuccess, resolveError, "rw"); } ); }); </script> </body> </html>
qiuzhong/crosswalk-test-suite
webapi/tct-filesystem-tizen-tests/filesystem/File_readAsText.html
HTML
bsd-3-clause
2,371
<!DOCTYPE html> <html debug="true"> <head> <!-- Loads the resources of ExtJS and OpenLayers. Use the URL-parameter `extjs` to require a specific version of Ext, e.g. `LayerOpacity.html?extjs=5.0.1` --> <script src="../../examples/include-ext.js"></script> <script src="http://openlayers.org/api/2.13.1/OpenLayers.js"></script> <script type="text/javascript"> Ext.Loader.setConfig({ disableCaching: false, enabled: true, paths: { GeoExt: '../../src/GeoExt' } }); Ext.Loader.syncRequire([ 'GeoExt.panel.Map', 'GeoExt.slider.LayerOpacity' ]); function test_constructor(t) { t.plan(8); var record, store, slider; var store = Ext.create('GeoExt.data.LayerStore', { data : [ new OpenLayers.Layer("a") ] }); record = store.getAt(0); var layer = record.getLayer(); slider = Ext.create("GeoExt.slider.LayerOpacity", { layer: record }); t.eq(slider.layer.id, record.get("id"), "layer parameter is a GeoExt.data.LayerRecord"); slider.destroy(); slider = Ext.create("GeoExt.slider.LayerOpacity", { layer: layer }); t.eq(layer.id, slider.layer.id, "layer parameter is a OpenLayers.Layer.WMS"); slider.destroy(); slider = Ext.create("GeoExt.slider.LayerOpacity", { layer: layer }); t.eq(slider.value, 100, "ctor sets value to max value if layer opacity is " + "null and value isn't defined in config"); slider = Ext.create("GeoExt.slider.LayerOpacity", { layer: layer, changeVisibility: true }); t.eq(slider.changeVisibility, true, "ctor sets changeVisibility to true in instance"); slider.destroy(); layer.setOpacity(0.0); slider = Ext.create("GeoExt.slider.LayerOpacity", { layer: layer, changeVisibility: true }); t.eq(layer.getVisibility(), false, "ctor makes layer invisible if layer opacity is 0"); layer.setVisibility(true); slider.destroy(); layer.setOpacity(0.5); slider = Ext.create("GeoExt.slider.LayerOpacity",{ layer: layer, changeVisibility: true }); t.eq(layer.getVisibility(), true, "ctor does not change layer visibility if layer opacity is non 0"); slider.destroy(); layer.opacity = null; slider = Ext.create("GeoExt.slider.LayerOpacity", { layer: layer, value: 0, changeVisibility: true }); t.eq(layer.getVisibility(), false, "ctor makes layer invisible if layer opacity is " + "null and value is min value"); layer.setVisibility(true); slider.destroy(); layer.opacity = null; slider = Ext.create("GeoExt.slider.LayerOpacity", { layer: layer, value: 0.5, changeVisibility: true }); t.eq(layer.getVisibility(), true, "ctor does not change layer visibility if layer " + "opacity is null and value is not min value"); layer.setVisibility(true); slider.destroy(); } function test_constructor_complementary(t) { t.plan(5); var layer1, layer2, record1, record2, slider; var store = Ext.create('GeoExt.data.LayerStore', { data : [ new OpenLayers.Layer("1"), new OpenLayers.Layer("2") ] }); var layer1 = store.getAt(0).getLayer(); var layer2 = store.getAt(1).getLayer(); record1 = store.getAt(0); record2 = store.getAt(1); slider = Ext.create("GeoExt.slider.LayerOpacity", { layer: layer1, complementaryLayer: layer2 }); t.ok(slider.complementaryLayer == layer2, "ctor correctly sets complementary layer in " + "the instance [layer]"); slider.destroy(); slider = Ext.create("GeoExt.slider.LayerOpacity", { layer: record1, complementaryLayer: record2 }); t.ok(slider.complementaryLayer == layer2, "ctor correctly sets complementary layer in " + "the instance [record]"); slider.destroy(); layer1.setOpacity(1); slider = Ext.create("GeoExt.slider.LayerOpacity", { layer: layer1, complementaryLayer: layer2 }); t.eq(layer2.getVisibility(), false, "ctor makes complementary layer invisible if the " + "main layer opacity is 1"); layer2.setVisibility(true); slider.destroy(); layer1.setOpacity(0.5); slider = Ext.create("GeoExt.slider.LayerOpacity", { layer: layer1, complementaryLayer: layer2 }); t.eq(layer2.getVisibility(), true, "ctor does not change complementary layer visibility "+ "if the main layer opacity is not 1"); slider.destroy(); layer1.opacity = null; slider = Ext.create("GeoExt.slider.LayerOpacity", { layer: layer1, complementaryLayer: layer2, value: 100 }); t.eq(layer2.getVisibility(), false, "ctor makes complementary layer invisible if the " + "main layer opacity is null but the slider " + "value is set to max value in the config"); slider.destroy(); } function test_initalOpacity(t) { t.plan(3); var slider = new GeoExt.LayerOpacitySlider({ layer: new OpenLayers.Layer('foo') }); t.ok(slider.getValue() == 100, "set the value to 100 if the layer has no opacity"); slider.destroy(); slider = new GeoExt.LayerOpacitySlider({ layer: new OpenLayers.Layer('foo', { opacity: 0 }) }); t.ok(slider.getValue() == 0, "initial layer's opacity sets the slider value"); slider.destroy(); slider = new GeoExt.LayerOpacitySlider({ layer: new OpenLayers.Layer('foo', { opacity: 0.42 }) }); t.ok(slider.getValue() == 42, "initial layer's opacity sets the slider value"); slider.destroy(); } function test_aggressive(t) { t.plan(2); var slider1 = new GeoExt.LayerOpacitySlider({ renderTo: document.body, layer: new OpenLayers.Layer('foo'), aggressive: false }); slider1.on({ changecomplete: function() { t.ok(true, "changecomplete triggered in non-aggressive mode"); } }); var slider2 = new GeoExt.LayerOpacitySlider({ renderTo: document.body, layer: new OpenLayers.Layer('foo'), aggressive: true }); slider2.on({ change: function() { t.ok(true, "change triggered in aggressive mode"); } }); slider1.setValue(42, undefined, true); slider2.setValue(42, undefined, true); slider1.destroy(); slider2.destroy(); } function test_visibility(t) { t.plan(3); var slider, layer; layer = new OpenLayers.Layer("a"); slider = new GeoExt.LayerOpacitySlider({ renderTo: document.body, layer: layer, changeVisibility: true, changeVisibilityDelay: 0 }); slider.setValue(slider.minValue); t.eq(layer.getVisibility(), false, "setting slider value to min value makes the " + "layer invisible"); slider.setValue(slider.minValue + 1); t.eq(layer.getVisibility(), true, "setting slider value to some value different " + "than min value makes the layer visible again"); slider.setValue(slider.minValue + 2); t.eq(layer.getVisibility(), true, "setting slider value to some other value different " + "than min value does not make the layer invisible"); slider.destroy(); } function test_visibility_complementary_layer(t) { t.plan(4); var layer1, layer2, slider; var layer1 = new OpenLayers.Layer("1"); var layer2 = new OpenLayers.Layer("2"); slider = new GeoExt.LayerOpacitySlider({ renderTo: document.body, layer: layer1, complementaryLayer: layer2, changeVisibilityDelay: 0 }); slider.value = 99; slider.setValue(slider.maxValue); t.eq(layer2.getVisibility(), false, "setting slider value to max value makes " + "complementary layer invisible"); slider.setValue(slider.maxValue - 1); t.eq(layer2.getVisibility(), true, "setting slider value to some value different " + "than max value makes the complementary layer " + "visible again"); slider.setValue(slider.maxValue - 2); t.eq(layer2.getVisibility(), true, "setting slider value to some other value different " + "than max value does not make the complementary layer " + "invisible"); slider.setValue(slider.minValue); t.eq(layer2.getVisibility(), true, "setting slider value to min value does not make " + "the complementary layer invisible"); slider.destroy(); } function test_setlayer(t) { t.plan(2); var layer1, layer2, slider; layer1 = new OpenLayers.Layer("1"); layer1.setOpacity(0.3); layer2 = new OpenLayers.Layer("2"); layer2.setOpacity(0.6); slider = new GeoExt.LayerOpacitySlider({ renderTo: document.body, value: 100 }); slider.setLayer(layer1); t.eq(slider.getValue(), 30, "Opacity of first layer is used"); slider.setLayer(layer2); t.eq(slider.getValue(), 60, "Opacity of second layer is used"); slider.destroy(); } function test_changelayerEvent(t) { t.plan(2); var map = new OpenLayers.Map(); var layer1 = new OpenLayers.Layer("1"); var layer2 = new OpenLayers.Layer("2"); map.addLayers([layer1, layer2]); slider = new GeoExt.LayerOpacitySlider({ layer: layer1, renderTo: document.body, value: 100 }); slider.setLayer(layer1); layer1.setOpacity(0.9); t.eq(slider.getValue(), 90, "value set from changelayer event"); layer2.setOpacity(0.1); t.eq(slider.getValue(), 90, "listen to the right layer"); map.destroy(); slider.destroy(); } function test_inverse(t) { t.plan(2); var map = new OpenLayers.Map(); var layer1 = new OpenLayers.Layer("1"); var layer2 = new OpenLayers.Layer("2"); map.addLayers([layer1, layer2]); slider = new GeoExt.LayerOpacitySlider({ layer: layer1, inverse: true, renderTo: document.body }); slider.setLayer(layer1); layer1.setOpacity(0.9); t.eq(slider.getValue(), 10, "value set correctly from changelayer event when inverse is true"); slider.setValue(40, undefined, true); t.eq(layer1.opacity, 0.6, "opacity set correctly through slider move when inverse is true"); map.destroy(); slider.destroy(); } function test_inverse_visibility(t) { t.plan(4); var layer1, layer2, slider; var layer1 = new OpenLayers.Layer("1"); var layer2 = new OpenLayers.Layer("2"); slider = new GeoExt.LayerOpacitySlider({ renderTo: document.body, layer: layer1, complementaryLayer: layer2, inverse: true, changeVisibilityDelay: 0 }); slider.value = 99; slider.setValue(slider.minValue); t.eq(layer2.getVisibility(), false, "setting slider value to min value makes " + "complementary layer invisible"); slider.setValue(slider.maxValue - 1); t.eq(layer2.getVisibility(), true, "setting slider value to some value different " + "than min value makes the complementary layer " + "visible again"); slider.setValue(slider.maxValue - 2); t.eq(layer2.getVisibility(), true, "setting slider value to some other value different " + "than min value does not make the complementary layer " + "invisible"); slider.setValue(slider.maxValue); t.eq(layer2.getVisibility(), true, "setting slider value to max value does not make " + "the complementary layer invisible"); slider.destroy(); } function test_setValue_called_once(t) { t.plan(1); var map, layer, slider, log; map = new OpenLayers.Map("div"); layer = new OpenLayers.Layer(""); map.addLayer(layer); slider = new GeoExt.LayerOpacitySlider({ renderTo: document.body, layer: layer, aggressive: true, delay: undefined }); slider.setValue = function(v) { log.cnt++; log.v = v; GeoExt.LayerOpacitySlider.prototype.setValue.apply( this, arguments); }; log = {cnt: 0}; slider.setValue(50); t.eq(log.cnt, 1, "setValue called exactly once"); slider.destroy(); map.destroy(); } </script> <body> <div id="map"></div> </body> </html>
bentrm/geoext2
tests/slider/LayerOpacity.html
HTML
bsd-3-clause
15,498
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_AURA_CLIENT_VISIBILITY_CLIENT_H_ #define UI_AURA_CLIENT_VISIBILITY_CLIENT_H_ #include "ui/aura/aura_export.h" namespace aura { class Window; namespace client { // An interface implemented by an object that manages the visibility of Windows' // layers as Window visibility changes. class AURA_EXPORT VisibilityClient { public: // Called when |window|'s visibility is changing to |visible|. The implementor // can perform additional actions before reflecting the visibility change on // the underlying layer. virtual void UpdateLayerVisibility(Window* window, bool visible) = 0; protected: virtual ~VisibilityClient() {} }; // Sets the VisibilityClient on the Window. AURA_EXPORT void SetVisibilityClient(Window* window, VisibilityClient* client); // Gets the VisibilityClient for the window. This will crawl up |window|'s // hierarchy until it finds one. AURA_EXPORT VisibilityClient* GetVisibilityClient(Window* window); } // namespace clients } // namespace aura #endif // UI_AURA_CLIENT_VISIBILITY_CLIENT_H_
scheib/chromium
ui/aura/client/visibility_client.h
C
bsd-3-clause
1,214
--- id: 5900f3c31000cf542c50fed5 title: 'Problem 86: Cuboid route' challengeType: 5 forumTopicId: 302200 dashedName: problem-86-cuboid-route --- # --description-- A spider, S, sits in one corner of a cuboid room, measuring 6 by 5 by 3, and a fly, F, sits in the opposite corner. By travelling on the surfaces of the room the shortest "straight line" distance from S to F is 10 and the path is shown on the diagram. <img class="img-responsive center-block" alt="a diagram of a spider and fly's path from one corner of a cuboid room to the opposite corner" src="https://cdn-media-1.freecodecamp.org/project-euler/cuboid-route.png" style="background-color: white; padding: 10px;" /> However, there are up to three "shortest" path candidates for any given cuboid and the shortest route doesn't always have integer length. It can be shown that there are exactly `2060` distinct cuboids, ignoring rotations, with integer dimensions, up to a maximum size of M by M by M, for which the shortest route has integer length when M = 100. This is the least value of M for which the number of solutions first exceeds two thousand; the number of solutions when M = 99 is `1975`. Find the least value of M such that the number of solutions first exceeds `n`. # --hints-- `cuboidRoute(2000)` should return a number. ```js assert(typeof cuboidRoute(2000) === 'number'); ``` `cuboidRoute(2000)` should return `100`. ```js assert.strictEqual(cuboidRoute(2000), 100); ``` `cuboidRoute(25000)` should return `320`. ```js assert.strictEqual(cuboidRoute(25000), 320); ``` `cuboidRoute(500000)` should return `1309`. ```js assert.strictEqual(cuboidRoute(500000), 1309); ``` `cuboidRoute(1000000)` should return `1818`. ```js assert.strictEqual(cuboidRoute(1000000), 1818); ``` # --seed-- ## --seed-contents-- ```js function cuboidRoute(n) { return true; } cuboidRoute(2000); ``` # --solutions-- ```js function cuboidRoute(n) { // Based on https://www.mathblog.dk/project-euler-86-shortest-path-cuboid/ function getLength(a, b) { return Math.sqrt(a ** 2 + b ** 2); } let M = 2; let counter = 0; while (counter < n) { M++; for (let baseHeightWidth = 3; baseHeightWidth <= 2 * M; baseHeightWidth++) { const pathLength = getLength(M, baseHeightWidth); if (Number.isInteger(pathLength)) { if (baseHeightWidth <= M) { counter += Math.floor(baseHeightWidth / 2); } else { counter += 1 + M - Math.floor((baseHeightWidth + 1) / 2); } } } } return M; } ```
raisedadead/FreeCodeCamp
curriculum/challenges/portuguese/10-coding-interview-prep/project-euler/problem-86-cuboid-route.md
Markdown
bsd-3-clause
2,545
### # Copyright (c) 2002-2005, Jeremiah Fincher # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions, and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions, and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the author of this software nor the name of # contributors to this software may be used to endorse or promote products # derived from this software without specific prior written consent. # # 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. ### from supybot.test import * import copy import pickle import supybot.ircmsgs as ircmsgs import supybot.ircutils as ircutils # The test framework used to provide these, but not it doesn't. We'll add # messages to as we find bugs (if indeed we find bugs). msgs = [] rawmsgs = [] class IrcMsgTestCase(SupyTestCase): def testLen(self): for msg in msgs: if msg.prefix: strmsg = str(msg) self.failIf(len(msg) != len(strmsg) and \ strmsg.replace(':', '') == strmsg) def testRepr(self): IrcMsg = ircmsgs.IrcMsg for msg in msgs: self.assertEqual(msg, eval(repr(msg))) def testStr(self): for (rawmsg, msg) in zip(rawmsgs, msgs): strmsg = str(msg).strip() self.failIf(rawmsg != strmsg and \ strmsg.replace(':', '') == strmsg) def testEq(self): for msg in msgs: self.assertEqual(msg, msg) self.failIf(msgs and msgs[0] == []) # Comparison to unhashable type. def testNe(self): for msg in msgs: self.failIf(msg != msg) ## def testImmutability(self): ## s = 'something else' ## t = ('foo', 'bar', 'baz') ## for msg in msgs: ## self.assertRaises(AttributeError, setattr, msg, 'prefix', s) ## self.assertRaises(AttributeError, setattr, msg, 'nick', s) ## self.assertRaises(AttributeError, setattr, msg, 'user', s) ## self.assertRaises(AttributeError, setattr, msg, 'host', s) ## self.assertRaises(AttributeError, setattr, msg, 'command', s) ## self.assertRaises(AttributeError, setattr, msg, 'args', t) ## if msg.args: ## def setArgs(msg): ## msg.args[0] = s ## self.assertRaises(TypeError, setArgs, msg) def testInit(self): for msg in msgs: self.assertEqual(msg, ircmsgs.IrcMsg(prefix=msg.prefix, command=msg.command, args=msg.args)) self.assertEqual(msg, ircmsgs.IrcMsg(msg=msg)) self.assertRaises(ValueError, ircmsgs.IrcMsg, args=('foo', 'bar'), prefix='foo!bar@baz') def testPickleCopy(self): for msg in msgs: self.assertEqual(msg, pickle.loads(pickle.dumps(msg))) self.assertEqual(msg, copy.copy(msg)) def testHashNotZero(self): zeroes = 0 for msg in msgs: if hash(msg) == 0: zeroes += 1 self.failIf(zeroes > (len(msgs)/10), 'Too many zero hashes.') def testMsgKeywordHandledProperly(self): msg = ircmsgs.notice('foo', 'bar') msg2 = ircmsgs.IrcMsg(msg=msg, command='PRIVMSG') self.assertEqual(msg2.command, 'PRIVMSG') self.assertEqual(msg2.args, msg.args) def testMalformedIrcMsgRaised(self): self.assertRaises(ircmsgs.MalformedIrcMsg, ircmsgs.IrcMsg, ':foo') self.assertRaises(ircmsgs.MalformedIrcMsg, ircmsgs.IrcMsg, args=('biff',), prefix='foo!bar@baz') def testTags(self): m = ircmsgs.privmsg('foo', 'bar') self.failIf(m.repliedTo) m.tag('repliedTo') self.failUnless(m.repliedTo) m.tag('repliedTo') self.failUnless(m.repliedTo) m.tag('repliedTo', 12) self.assertEqual(m.repliedTo, 12) class FunctionsTestCase(SupyTestCase): def testIsAction(self): L = [':jemfinch!~jfincher@ts26-2.homenet.ohio-state.edu PRIVMSG' ' #sourcereview :ACTION does something', ':supybot!~supybot@underthemain.net PRIVMSG #sourcereview ' ':ACTION beats angryman senseless with a Unix manual (#2)', ':supybot!~supybot@underthemain.net PRIVMSG #sourcereview ' ':ACTION beats ang senseless with a 50lb Unix manual (#2)', ':supybot!~supybot@underthemain.net PRIVMSG #sourcereview ' ':ACTION resizes angryman\'s terminal to 40x24 (#16)'] msgs = map(ircmsgs.IrcMsg, L) for msg in msgs: self.failUnless(ircmsgs.isAction(msg)) def testIsActionIsntStupid(self): m = ircmsgs.privmsg('#x', '\x01NOTANACTION foo\x01') self.failIf(ircmsgs.isAction(m)) m = ircmsgs.privmsg('#x', '\x01ACTION foo bar\x01') self.failUnless(ircmsgs.isAction(m)) def testIsCtcp(self): self.failUnless(ircmsgs.isCtcp(ircmsgs.privmsg('foo', '\x01VERSION\x01'))) self.failIf(ircmsgs.isCtcp(ircmsgs.privmsg('foo', '\x01'))) def testIsActionFalseWhenNoSpaces(self): msg = ircmsgs.IrcMsg('PRIVMSG #foo :\x01ACTIONfoobar\x01') self.failIf(ircmsgs.isAction(msg)) def testUnAction(self): s = 'foo bar baz' msg = ircmsgs.action('#foo', s) self.assertEqual(ircmsgs.unAction(msg), s) def testBan(self): channel = '#osu' ban = '*!*@*.edu' exception = '*!*@*ohio-state.edu' noException = ircmsgs.ban(channel, ban) self.assertEqual(ircutils.separateModes(noException.args[1:]), [('+b', ban)]) withException = ircmsgs.ban(channel, ban, exception) self.assertEqual(ircutils.separateModes(withException.args[1:]), [('+b', ban), ('+e', exception)]) def testBans(self): channel = '#osu' bans = ['*!*@*', 'jemfinch!*@*'] exceptions = ['*!*@*ohio-state.edu'] noException = ircmsgs.bans(channel, bans) self.assertEqual(ircutils.separateModes(noException.args[1:]), [('+b', bans[0]), ('+b', bans[1])]) withExceptions = ircmsgs.bans(channel, bans, exceptions) self.assertEqual(ircutils.separateModes(withExceptions.args[1:]), [('+b', bans[0]), ('+b', bans[1]), ('+e', exceptions[0])]) def testUnban(self): channel = '#supybot' ban = 'foo!bar@baz' self.assertEqual(str(ircmsgs.unban(channel, ban)), 'MODE %s -b :%s\r\n' % (channel, ban)) def testJoin(self): channel = '#osu' key = 'michiganSucks' self.assertEqual(ircmsgs.join(channel).args, ('#osu',)) self.assertEqual(ircmsgs.join(channel, key).args, ('#osu', 'michiganSucks')) def testJoins(self): channels = ['#osu', '#umich'] keys = ['michiganSucks', 'osuSucks'] self.assertEqual(ircmsgs.joins(channels).args, ('#osu,#umich',)) self.assertEqual(ircmsgs.joins(channels, keys).args, ('#osu,#umich', 'michiganSucks,osuSucks')) keys.pop() self.assertEqual(ircmsgs.joins(channels, keys).args, ('#osu,#umich', 'michiganSucks')) def testQuit(self): self.failUnless(ircmsgs.quit(prefix='foo!bar@baz')) def testOps(self): m = ircmsgs.ops('#foo', ['foo', 'bar', 'baz']) self.assertEqual(str(m), 'MODE #foo +ooo foo bar :baz\r\n') def testDeops(self): m = ircmsgs.deops('#foo', ['foo', 'bar', 'baz']) self.assertEqual(str(m), 'MODE #foo -ooo foo bar :baz\r\n') def testVoices(self): m = ircmsgs.voices('#foo', ['foo', 'bar', 'baz']) self.assertEqual(str(m), 'MODE #foo +vvv foo bar :baz\r\n') def testDevoices(self): m = ircmsgs.devoices('#foo', ['foo', 'bar', 'baz']) self.assertEqual(str(m), 'MODE #foo -vvv foo bar :baz\r\n') def testHalfops(self): m = ircmsgs.halfops('#foo', ['foo', 'bar', 'baz']) self.assertEqual(str(m), 'MODE #foo +hhh foo bar :baz\r\n') def testDehalfops(self): m = ircmsgs.dehalfops('#foo', ['foo', 'bar', 'baz']) self.assertEqual(str(m), 'MODE #foo -hhh foo bar :baz\r\n') def testMode(self): m = ircmsgs.mode('#foo', ('-b', 'foo!bar@baz')) s = str(m) self.assertEqual(s, 'MODE #foo -b :foo!bar@baz\r\n') def testIsSplit(self): m = ircmsgs.IrcMsg(prefix="caker!~caker@ns.theshore.net", command="QUIT", args=('jupiter.oftc.net quasar.oftc.net',)) self.failUnless(ircmsgs.isSplit(m)) m = ircmsgs.IrcMsg(prefix="bzbot!Brad2901@ACC87473.ipt.aol.com", command="QUIT", args=('Read error: 110 (Connection timed out)',)) self.failIf(ircmsgs.isSplit(m)) m = ircmsgs.IrcMsg(prefix="JibberJim!~none@8212cl.b0nwbeoe.co.uk", command="QUIT", args=('"Bye!"',)) self.failIf(ircmsgs.isSplit(m)) # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
buildbot/supybot
test/test_ircmsgs.py
Python
bsd-3-clause
10,535
define('b',{}); define('c',{}); define('second',['b', 'c'], function (b, c) { console.log(b.name); console.log(c.name); });
alkaest2002/gzts-lab
web/app/assets/frameworks/bower_components/r.js/build/tests/lib/stubModules/perModule/expected-second.js
JavaScript
bsd-3-clause
135
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ppapi/proxy/video_capture_resource.h" #include <stddef.h> #include "base/bind.h" #include "ppapi/c/dev/ppp_video_capture_dev.h" #include "ppapi/proxy/dispatch_reply_message.h" #include "ppapi/proxy/plugin_dispatcher.h" #include "ppapi/proxy/plugin_globals.h" #include "ppapi/proxy/plugin_resource_tracker.h" #include "ppapi/proxy/ppapi_messages.h" #include "ppapi/proxy/ppb_buffer_proxy.h" #include "ppapi/proxy/resource_message_params.h" #include "ppapi/shared_impl/proxy_lock.h" #include "ppapi/shared_impl/tracked_callback.h" namespace ppapi { namespace proxy { VideoCaptureResource::VideoCaptureResource( Connection connection, PP_Instance instance, PluginDispatcher* dispatcher) : PluginResource(connection, instance), open_state_(BEFORE_OPEN), enumeration_helper_(this) { SendCreate(RENDERER, PpapiHostMsg_VideoCapture_Create()); ppp_video_capture_impl_ = static_cast<const PPP_VideoCapture_Dev*>( dispatcher->local_get_interface()(PPP_VIDEO_CAPTURE_DEV_INTERFACE)); } VideoCaptureResource::~VideoCaptureResource() { } void VideoCaptureResource::OnReplyReceived( const ResourceMessageReplyParams& params, const IPC::Message& msg) { if (enumeration_helper_.HandleReply(params, msg)) return; if (params.sequence()) { PluginResource::OnReplyReceived(params, msg); return; } PPAPI_BEGIN_MESSAGE_MAP(VideoCaptureResource, msg) PPAPI_DISPATCH_PLUGIN_RESOURCE_CALL( PpapiPluginMsg_VideoCapture_OnDeviceInfo, OnPluginMsgOnDeviceInfo) PPAPI_DISPATCH_PLUGIN_RESOURCE_CALL( PpapiPluginMsg_VideoCapture_OnStatus, OnPluginMsgOnStatus) PPAPI_DISPATCH_PLUGIN_RESOURCE_CALL( PpapiPluginMsg_VideoCapture_OnError, OnPluginMsgOnError) PPAPI_DISPATCH_PLUGIN_RESOURCE_CALL( PpapiPluginMsg_VideoCapture_OnBufferReady, OnPluginMsgOnBufferReady) PPAPI_DISPATCH_PLUGIN_RESOURCE_CALL_UNHANDLED(NOTREACHED()) PPAPI_END_MESSAGE_MAP() } int32_t VideoCaptureResource::EnumerateDevices( const PP_ArrayOutput& output, scoped_refptr<TrackedCallback> callback) { return enumeration_helper_.EnumerateDevices(output, callback); } int32_t VideoCaptureResource::MonitorDeviceChange( PP_MonitorDeviceChangeCallback callback, void* user_data) { return enumeration_helper_.MonitorDeviceChange(callback, user_data); } int32_t VideoCaptureResource::Open( const std::string& device_id, const PP_VideoCaptureDeviceInfo_Dev& requested_info, uint32_t buffer_count, scoped_refptr<TrackedCallback> callback) { if (open_state_ != BEFORE_OPEN) return PP_ERROR_FAILED; if (TrackedCallback::IsPending(open_callback_)) return PP_ERROR_INPROGRESS; open_callback_ = callback; Call<PpapiPluginMsg_VideoCapture_OpenReply>( RENDERER, PpapiHostMsg_VideoCapture_Open(device_id, requested_info, buffer_count), base::BindOnce(&VideoCaptureResource::OnPluginMsgOpenReply, this)); return PP_OK_COMPLETIONPENDING; } int32_t VideoCaptureResource::StartCapture() { if (open_state_ != OPENED) return PP_ERROR_FAILED; Post(RENDERER, PpapiHostMsg_VideoCapture_StartCapture()); return PP_OK; } int32_t VideoCaptureResource::ReuseBuffer(uint32_t buffer) { if (buffer >= buffer_in_use_.size() || !buffer_in_use_[buffer]) return PP_ERROR_BADARGUMENT; Post(RENDERER, PpapiHostMsg_VideoCapture_ReuseBuffer(buffer)); return PP_OK; } int32_t VideoCaptureResource::StopCapture() { if (open_state_ != OPENED) return PP_ERROR_FAILED; Post(RENDERER, PpapiHostMsg_VideoCapture_StopCapture()); return PP_OK; } void VideoCaptureResource::Close() { if (open_state_ == CLOSED) return; Post(RENDERER, PpapiHostMsg_VideoCapture_Close()); open_state_ = CLOSED; if (TrackedCallback::IsPending(open_callback_)) open_callback_->PostAbort(); } int32_t VideoCaptureResource::EnumerateDevicesSync( const PP_ArrayOutput& devices) { return enumeration_helper_.EnumerateDevicesSync(devices); } void VideoCaptureResource::LastPluginRefWasDeleted() { enumeration_helper_.LastPluginRefWasDeleted(); } void VideoCaptureResource::OnPluginMsgOnDeviceInfo( const ResourceMessageReplyParams& params, const struct PP_VideoCaptureDeviceInfo_Dev& info, const std::vector<HostResource>& buffers, uint32_t buffer_size) { if (!ppp_video_capture_impl_) return; std::vector<base::UnsafeSharedMemoryRegion> regions; for (size_t i = 0; i < params.handles().size(); ++i) { base::UnsafeSharedMemoryRegion region; params.TakeUnsafeSharedMemoryRegionAtIndex(i, &region); DCHECK_EQ(buffer_size, region.GetSize()); regions.push_back(std::move(region)); } CHECK(regions.size() == buffers.size()); PluginResourceTracker* tracker = PluginGlobals::Get()->plugin_resource_tracker(); std::unique_ptr<PP_Resource[]> resources(new PP_Resource[buffers.size()]); for (size_t i = 0; i < buffers.size(); ++i) { // We assume that the browser created a new set of resources. DCHECK(!tracker->PluginResourceForHostResource(buffers[i])); resources[i] = ppapi::proxy::PPB_Buffer_Proxy::AddProxyResource( buffers[i], std::move(regions[i])); } buffer_in_use_ = std::vector<bool>(buffers.size()); CallWhileUnlocked(ppp_video_capture_impl_->OnDeviceInfo, pp_instance(), pp_resource(), &info, static_cast<uint32_t>(buffers.size()), resources.get()); for (size_t i = 0; i < buffers.size(); ++i) tracker->ReleaseResource(resources[i]); } void VideoCaptureResource::OnPluginMsgOnStatus( const ResourceMessageReplyParams& params, uint32_t status) { switch (status) { case PP_VIDEO_CAPTURE_STATUS_STARTING: case PP_VIDEO_CAPTURE_STATUS_STOPPING: // Those states are not sent by the browser. NOTREACHED(); break; } if (ppp_video_capture_impl_) { CallWhileUnlocked(ppp_video_capture_impl_->OnStatus, pp_instance(), pp_resource(), status); } } void VideoCaptureResource::OnPluginMsgOnError( const ResourceMessageReplyParams& params, uint32_t error_code) { open_state_ = CLOSED; if (ppp_video_capture_impl_) { CallWhileUnlocked(ppp_video_capture_impl_->OnError, pp_instance(), pp_resource(), error_code); } } void VideoCaptureResource::OnPluginMsgOnBufferReady( const ResourceMessageReplyParams& params, uint32_t buffer) { SetBufferInUse(buffer); if (ppp_video_capture_impl_) { CallWhileUnlocked(ppp_video_capture_impl_->OnBufferReady, pp_instance(), pp_resource(), buffer); } } void VideoCaptureResource::OnPluginMsgOpenReply( const ResourceMessageReplyParams& params) { if (open_state_ == BEFORE_OPEN && params.result() == PP_OK) open_state_ = OPENED; // The callback may have been aborted by Close(). if (TrackedCallback::IsPending(open_callback_)) open_callback_->Run(params.result()); } void VideoCaptureResource::SetBufferInUse(uint32_t buffer_index) { CHECK(buffer_index < buffer_in_use_.size()); buffer_in_use_[buffer_index] = true; } } // namespace proxy } // namespace ppapi
chromium/chromium
ppapi/proxy/video_capture_resource.cc
C++
bsd-3-clause
7,527
module Head where {-@ measure hd :: [a] -> a hd (x:xs) = x @-} -- Strengthened constructors -- data [a] where -- [] :: [a] -- as before -- (:) :: x:a -> xs:[a] -> {v:[a] | hd v = x} {-@ cons :: x:a -> _ -> {v:[a] | hd v = x} @-} cons x xs = x : xs {-@ test :: {v:_ | hd v = 0} @-} test :: [Int] test = cons 0 [1,2,3,4]
abakst/liquidhaskell
tests/todo/partialmeasureOld.hs
Haskell
bsd-3-clause
356
// Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_solaris.go // +build amd64,solaris package syscall const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 PathMax = 0x400 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int64 } type Timeval32 struct { Sec int32 Usec int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 const ( S_IFMT = 0xf000 S_IFIFO = 0x1000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFBLK = 0x6000 S_IFREG = 0x8000 S_IFLNK = 0xa000 S_IFSOCK = 0xc000 S_ISUID = 0x800 S_ISGID = 0x400 S_ISVTX = 0x200 S_IRUSR = 0x100 S_IWUSR = 0x80 S_IXUSR = 0x40 ) type Stat_t struct { Dev uint64 Ino uint64 Mode uint32 Nlink uint32 Uid uint32 Gid uint32 Rdev uint64 Size int64 Atim Timespec Mtim Timespec Ctim Timespec Blksize int32 Pad_cgo_0 [4]byte Blocks int64 Fstype [16]int8 } type Flock_t struct { Type int16 Whence int16 Pad_cgo_0 [4]byte Start int64 Len int64 Sysid int32 Pid int32 Pad [4]int64 } type Dirent struct { Ino uint64 Off int64 Reclen uint16 Name [1]int8 Pad_cgo_0 [5]byte } type RawSockaddrInet4 struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 X__sin6_src_id uint32 } type RawSockaddrUnix struct { Family uint16 Path [108]int8 } type RawSockaddrDatalink struct { Family uint16 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [244]int8 } type RawSockaddr struct { Family uint16 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [236]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *int8 Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *Iovec Iovlen int32 Pad_cgo_1 [4]byte Accrights *int8 Accrightslen int32 Pad_cgo_2 [4]byte } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { X__icmp6_filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x20 SizeofSockaddrAny = 0xfc SizeofSockaddrUnix = 0x6e SizeofSockaddrDatalink = 0xfc SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x30 SizeofCmsghdr = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x24 SizeofICMPv6Filter = 0x20 ) type FdSet struct { Bits [1024]int64 } const ( SizeofIfMsghdr = 0x54 SizeofIfData = 0x44 SizeofIfaMsghdr = 0x14 SizeofRtMsghdr = 0x4c SizeofRtMetrics = 0x28 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Data IfData } type IfData struct { Type uint8 Addrlen uint8 Hdrlen uint8 Pad_cgo_0 [1]byte Mtu uint32 Metric uint32 Baudrate uint32 Ipackets uint32 Ierrors uint32 Opackets uint32 Oerrors uint32 Collisions uint32 Ibytes uint32 Obytes uint32 Imcasts uint32 Omcasts uint32 Iqdrops uint32 Noproto uint32 Lastchange Timeval32 } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Metric int32 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Pad_cgo_0 [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Use int32 Inits uint32 Rmx RtMetrics } type RtMetrics struct { Locks uint32 Mtu uint32 Hopcount uint32 Expire uint32 Recvpipe uint32 Sendpipe uint32 Ssthresh uint32 Rtt uint32 Rttvar uint32 Pksent uint32 } const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x80 SizeofBpfProgram = 0x10 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x14 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint64 Drop uint64 Capt uint64 Padding [13]uint64 } type BpfProgram struct { Len uint32 Pad_cgo_0 [4]byte Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfTimeval struct { Sec int32 Usec int32 } type BpfHdr struct { Tstamp BpfTimeval Caplen uint32 Datalen uint32 Hdrlen uint16 Pad_cgo_0 [2]byte } const ( _AT_FDCWD = 0xffd19553 ) type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [19]uint8 Pad_cgo_0 [1]byte }
Cofyc/go
src/syscall/ztypes_solaris_amd64.go
GO
bsd-3-clause
5,643
<!DOCTYPE html> <html> <head> <script src="resources/link-highlight-helper.js"></script> <link rel="stylesheet" type="text/css" href="resources/link-highlight-style.css"> <style> #outerDiv { width: 150px; } #outerDiv, #outerDiv div { padding: 15px; border-style: solid; } </style> </head> <body onload="runTest();"> <div class="opaqueHighlight" id="outerDiv" style="cursor: pointer"> <div style="cursor: pointer;"> <div style="cursor: default;"> <div id="innerDiv"></div> </div> </div> </div> <script> function runTest() { useMockHighlight(); var clientRect = document.getElementById("innerDiv").getBoundingClientRect(); x = (clientRect.left + clientRect.right) / 2; y = (clientRect.top + clientRect.bottom) / 2; if (window.testRunner) testRunner.waitUntilDone(); if (window.eventSender) { eventSender.gestureShowPress(x, y); window.setTimeout(function() { testRunner.notifyDone(); }, 0); } else { debug("This test requires DumpRenderTree."); } } </script> </body> </html>
nwjs/chromium.src
third_party/blink/web_tests/compositing/gestures/gesture-tapHighlight-nested-cursor.html
HTML
bsd-3-clause
1,309
var faker = new function () { function define(obj, name, desc) { } if (something) { define(this, 'base', {}); } define(a, b, c); function other () { define(this, '__proto__', {}); } };
alkaest2002/gzts-lab
web/app/assets/frameworks/bower_components/r.js/build/tests/lib/shimFakeDefine/faker.js
JavaScript
bsd-3-clause
234
// Filename: pnmimage_base.h // Created by: drose (14Jun00) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #ifndef PNMIMAGE_BASE_H #define PNMIMAGE_BASE_H // This header file make a few typedefs and other definitions // essential to everything in the PNMImage package. #include "pandabase.h" #include "pnotify.h" // Since we no longer include pnm.h directly, we have to provide our // own definitions for xel and xelval. // For now, we have PGM_BIGGRAYS defined, which gives us 16-bit // channels. Undefine this if you have memory problems and need to // use 8-bit channels instead. #define PGM_BIGGRAYS #ifdef PGM_BIGGRAYS typedef unsigned short gray; #define PGM_MAXMAXVAL 65535 #else // PGM_BIGGRAYS typedef unsigned char gray; #define PGM_MAXMAXVAL 255 #endif // PGM_BIGGRAYS #define PNM_MAXMAXVAL PGM_MAXMAXVAL struct pixel { PUBLISHED: pixel() { } pixel(gray fill) : r(fill), g(fill), b(fill) { } pixel(gray r, gray g, gray b) : r(r), g(g), b(b) { } gray operator [](int i) const { nassertr(i >= 0 && i < 3, 0); return *(&r + i); } gray &operator [](int i) { nassertr(i >= 0 && i < 3, r); return *(&r + i); } pixel operator + (const pixel &other) const { return pixel(r + other.r, g + other.g, b + other.b); } pixel operator - (const pixel &other) const { return pixel(r - other.r, g - other.g, b - other.b); } pixel operator * (const double mult) const { return pixel(r * mult, g * mult, b * mult); } void operator += (const pixel &other) { r += other.r; g += other.g; b += other.b; } void operator -= (const pixel &other) { r -= other.r; g -= other.g; b -= other.b; } void operator *= (const double mult) { r *= mult; g *= mult; b *= mult; } #ifdef HAVE_PYTHON static int size() { return 3; } void output(ostream &out) { out << "pixel(r=" << r << ", g=" << g << ", b=" << b << ")"; } #endif gray r, g, b; }; typedef gray pixval; typedef pixel xel; typedef gray xelval; // These macros are borrowed from ppm.h. #define PPM_GETR(p) ((p).r) #define PPM_GETG(p) ((p).g) #define PPM_GETB(p) ((p).b) #define PPM_PUTR(p,red) ((p).r = (red)) #define PPM_PUTG(p,grn) ((p).g = (grn)) #define PPM_PUTB(p,blu) ((p).b = (blu)) #define PPM_ASSIGN(p,red,grn,blu) { (p).r = (red); (p).g = (grn); (p).b = (blu); } #define PPM_EQUAL(p,q) ( (p).r == (q).r && (p).g == (q).g && (p).b == (q).b ) #define PNM_ASSIGN1(x,v) PPM_ASSIGN(x,0,0,v) #define PPM_DEPTH(newp,p,oldmaxval,newmaxval) \ PPM_ASSIGN( (newp), \ ( (int) PPM_GETR(p) * (newmaxval) + (oldmaxval) / 2 ) / (oldmaxval), \ ( (int) PPM_GETG(p) * (newmaxval) + (oldmaxval) / 2 ) / (oldmaxval), \ ( (int) PPM_GETB(p) * (newmaxval) + (oldmaxval) / 2 ) / (oldmaxval) ) // pnm defines these functions, and it's easier to emulate them than // to rewrite the code that calls them. EXPCL_PANDA_PNMIMAGE void pm_message(const char *format, ...); EXPCL_PANDA_PNMIMAGE void pm_error(const char *format, ...); // doesn't return. EXPCL_PANDA_PNMIMAGE int pm_maxvaltobits(int maxval); EXPCL_PANDA_PNMIMAGE int pm_bitstomaxval(int bits); EXPCL_PANDA_PNMIMAGE char *pm_allocrow(int cols, int size); EXPCL_PANDA_PNMIMAGE void pm_freerow(char *itrow); EXPCL_PANDA_PNMIMAGE int pm_readbigshort(istream *in, short *sP); EXPCL_PANDA_PNMIMAGE int pm_writebigshort(ostream *out, short s); EXPCL_PANDA_PNMIMAGE int pm_readbiglong(istream *in, long *lP); EXPCL_PANDA_PNMIMAGE int pm_writebiglong(ostream *out, long l); EXPCL_PANDA_PNMIMAGE int pm_readlittleshort(istream *in, short *sP); EXPCL_PANDA_PNMIMAGE int pm_writelittleshort(ostream *out, short s); EXPCL_PANDA_PNMIMAGE int pm_readlittlelong(istream *in, long *lP); EXPCL_PANDA_PNMIMAGE int pm_writelittlelong(ostream *out, long l); // These ratios are used to compute the brightness of a colored pixel; they // define the relative contributions of each of the components. static const float lumin_red = 0.299f; static const float lumin_grn = 0.587f; static const float lumin_blu = 0.114f; #endif
hj3938/panda3d
panda/src/pnmimage/pnmimage_base.h
C
bsd-3-clause
4,373
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. (function() { 'use strict'; cr.define('cr.translateInternals', function() { var detectionLogs_ = null; function detectionLogs() { if (detectionLogs_ === null) detectionLogs_ = []; return detectionLogs_; } /** * Initializes UI and sends a message to the browser for * initialization. */ function initialize() { cr.ui.decorate('tabbox', cr.ui.TabBox); chrome.send('requestInfo'); var button = $('detection-logs-dump'); button.addEventListener('click', onDetectionLogsDump); var tabpanelNodeList = document.getElementsByTagName('tabpanel'); var tabpanels = Array.prototype.slice.call(tabpanelNodeList, 0); var tabpanelIds = tabpanels.map(function(tab) { return tab.id; }); var tabNodeList = document.getElementsByTagName('tab'); var tabs = Array.prototype.slice.call(tabNodeList, 0); tabs.forEach(function(tab) { tab.onclick = function(e) { var tabbox = document.querySelector('tabbox'); var tabpanel = tabpanels[tabbox.selectedIndex]; var hash = tabpanel.id.match(/(?:^tabpanel-)(.+)/)[1]; window.location.hash = hash; }; }); var activateTabByHash = function() { var hash = window.location.hash; // Remove the first character '#'. hash = hash.substring(1); var id = 'tabpanel-' + hash; if (tabpanelIds.indexOf(id) == -1) return; $(id).selected = true; }; window.onhashchange = activateTabByHash; activateTabByHash(); } /** * Creates a new LI element with a button to dismiss the item. * * @param {string} text The lable of the LI element. * @param {Function} func Callback called when the button is clicked. */ function createLIWithDismissingButton(text, func) { var span = document.createElement('span'); span.textContent = text; var li = document.createElement('li'); li.appendChild(span); var button = document.createElement('button'); button.textContent = 'X'; button.addEventListener('click', function(e) { e.preventDefault(); func(); }, false); li.appendChild(button); return li; } /** * Formats the language name to a human-readable text. For example, if * |langCode| is 'en', this may return 'en (English)'. * * @param {string} langCode ISO 639 language code. * @return {string} The formatted string. */ function formatLanguageCode(langCode) { var key = 'language-' + langCode; if (loadTimeData.valueExists(key)) { var langName = loadTimeData.getString(key); return langCode + ' (' + langName + ')'; } return langCode; } /** * Formats the error type to a human-readable text. * * @param {string} error Translation error type from the browser. * @return {string} The formatted string. */ function formatTranslateErrorsType(error) { // This list is from chrome/common/translate/translate_errors.h. // If this header file is updated, the below list also should be updated. var errorStrs = { 0: 'None', 1: 'Network', 2: 'Initialization Error', 3: 'Unknown Language', 4: 'Unsupported Language', 5: 'Identical Languages', 6: 'Translation Error', 7: 'Translation Timeout', 8: 'Unexpected Script Error', 9: 'Bad Origin', 10: 'Script Load Error', }; if (error < 0 || errorStrs.length <= error) { console.error('Invalid error code:', error); return 'Invalid Error Code'; } return errorStrs[error]; } /** * Handles the message of 'prefsUpdated' from the browser. * * @param {Object} detail the object which represents pref values. */ function onPrefsUpdated(detail) { var ul; ul = document.querySelector('#prefs-blocked-languages ul'); ul.innerHTML = ''; if ('translate_blocked_languages' in detail) { var langs = detail['translate_blocked_languages']; langs.forEach(function(langCode) { var text = formatLanguageCode(langCode); var li = createLIWithDismissingButton(text, function() { chrome.send('removePrefItem', ['blocked_languages', langCode]); }); ul.appendChild(li); }); } ul = document.querySelector('#prefs-language-blacklist ul'); ul.innerHTML = ''; if ('translate_language_blacklist' in detail) { var langs = detail['translate_language_blacklist']; langs.forEach(function(langCode) { var text = formatLanguageCode(langCode); var li = createLIWithDismissingButton(text, function() { chrome.send('removePrefItem', ['language_blacklist', langCode]); }); ul.appendChild(li); }); } ul = document.querySelector('#prefs-site-blacklist ul'); ul.innerHTML = ''; if ('translate_site_blacklist' in detail) { var sites = detail['translate_site_blacklist']; sites.forEach(function(site) { var li = createLIWithDismissingButton(site, function() { chrome.send('removePrefItem', ['site_blacklist', site]); }); ul.appendChild(li); }); } ul = document.querySelector('#prefs-whitelists ul'); ul.innerHTML = ''; if ('translate_whitelists' in detail) { var pairs = detail['translate_whitelists']; Object.keys(pairs).forEach(function(fromLangCode) { var toLangCode = pairs[fromLangCode]; var text = formatLanguageCode(fromLangCode) + ' \u2192 ' + formatLanguageCode(toLangCode); var li = createLIWithDismissingButton(text, function() { chrome.send('removePrefItem', ['whitelists', fromLangCode, toLangCode]); }); ul.appendChild(li); }); } var p = document.querySelector('#prefs-dump p'); var content = JSON.stringify(detail, null, 2); p.textContent = content; } /** * Handles the message of 'supportedLanguagesUpdated' from the browser. * * @param {Object} details the object which represents the supported * languages by the Translate server. */ function onSupportedLanguagesUpdated(details) { var span = $('prefs-supported-languages-last-updated').querySelector('span'); span.textContent = formatDate(new Date(details['last_updated'])); var ul = $('prefs-supported-languages-languages'); ul.innerHTML = ''; var languages = details['languages']; for (var i = 0; i < languages.length; i++) { var language = languages[i]; var li = document.createElement('li'); var text = formatLanguageCode(language); if (details['alpha_languages'].indexOf(language) != -1) text += ' - alpha'; li.innerText = text; ul.appendChild(li); } } /** * Addes '0's to |number| as a string. |width| is length of the string * including '0's. * * @param {string} number The number to be converted into a string. * @param {number} width The width of the returned string. * @return {string} The formatted string. */ function padWithZeros(number, width) { var numberStr = number.toString(); var restWidth = width - numberStr.length; if (restWidth <= 0) return numberStr; return Array(restWidth + 1).join('0') + numberStr; } /** * Formats |date| as a Date object into a string. The format is like * '2006-01-02 15:04:05'. * * @param {Date} date Date to be formatted. * @return {string} The formatted string. */ function formatDate(date) { var year = date.getFullYear(); var month = date.getMonth() + 1; var day = date.getDate(); var hour = date.getHours(); var minute = date.getMinutes(); var second = date.getSeconds(); var yearStr = padWithZeros(year, 4); var monthStr = padWithZeros(month, 2); var dayStr = padWithZeros(day, 2); var hourStr = padWithZeros(hour, 2); var minuteStr = padWithZeros(minute, 2); var secondStr = padWithZeros(second, 2); var str = yearStr + '-' + monthStr + '-' + dayStr + ' ' + hourStr + ':' + minuteStr + ':' + secondStr; return str; } /** * Appends a new TD element to the specified element. * * @param {string} parent The element to which a new TD element is appended. * @param {string} content The text content of the element. * @param {string} className The class name of the element. */ function appendTD(parent, content, className) { var td = document.createElement('td'); td.textContent = content; td.className = className; parent.appendChild(td); } /** * Handles the message of 'languageDetectionInfoAdded' from the * browser. * * @param {Object} detail The object which represents the logs. */ function onLanguageDetectionInfoAdded(detail) { cr.translateInternals.detectionLogs().push(detail); var tr = document.createElement('tr'); appendTD(tr, formatDate(new Date(detail['time'])), 'detection-logs-time'); appendTD(tr, detail['url'], 'detection-logs-url'); appendTD(tr, formatLanguageCode(detail['content_language']), 'detection-logs-content-language'); appendTD(tr, formatLanguageCode(detail['cld_language']), 'detection-logs-cld-language'); appendTD(tr, detail['is_cld_reliable'], 'detection-logs-is-cld-reliable'); appendTD(tr, formatLanguageCode(detail['html_root_language']), 'detection-logs-html-root-language'); appendTD(tr, formatLanguageCode(detail['adopted_language']), 'detection-logs-adopted-language'); appendTD(tr, formatLanguageCode(detail['content']), 'detection-logs-content'); // TD (and TR) can't use the CSS property 'max-height', so DIV // in the content is needed. var contentTD = tr.querySelector('.detection-logs-content'); var div = document.createElement('div'); div.textContent = contentTD.textContent; contentTD.textContent = ''; contentTD.appendChild(div); var tabpanel = $('tabpanel-detection-logs'); var tbody = tabpanel.getElementsByTagName('tbody')[0]; tbody.appendChild(tr); } /** * Handles the message of 'translateErrorDetailsAdded' from the * browser. * * @param {Object} details The object which represents the logs. */ function onTranslateErrorDetailsAdded(details) { var tr = document.createElement('tr'); appendTD(tr, formatDate(new Date(details['time'])), 'error-logs-time'); appendTD(tr, details['url'], 'error-logs-url'); appendTD( tr, details['error'] + ': ' + formatTranslateErrorsType(details['error']), 'error-logs-error'); var tabpanel = $('tabpanel-error-logs'); var tbody = tabpanel.getElementsByTagName('tbody')[0]; tbody.appendChild(tr); } /** * Handles the message of 'translateEventDetailsAdded' from the browser. * * @param {Object} details The object which contains event information. */ function onTranslateEventDetailsAdded(details) { var tr = document.createElement('tr'); appendTD(tr, formatDate(new Date(details['time'])), 'event-logs-time'); appendTD(tr, details['filename'] + ': ' + details['line'], 'event-logs-place'); appendTD(tr, details['message'], 'event-logs-message'); var tbody = $('tabpanel-event-logs').getElementsByTagName('tbody')[0]; tbody.appendChild(tr); } /** * The callback entry point from the browser. This function will be * called by the browser. * * @param {string} message The name of the sent message. * @param {Object} details The argument of the sent message. */ function messageHandler(message, details) { switch (message) { case 'languageDetectionInfoAdded': onLanguageDetectionInfoAdded(details); break; case 'prefsUpdated': onPrefsUpdated(details); break; case 'supportedLanguagesUpdated': onSupportedLanguagesUpdated(details); break; case 'translateErrorDetailsAdded': onTranslateErrorDetailsAdded(details); break; case 'translateEventDetailsAdded': onTranslateEventDetailsAdded(details); break; default: console.error('Unknown message:', message); break; } } /** * The callback of button#detetion-logs-dump. */ function onDetectionLogsDump() { var data = JSON.stringify(cr.translateInternals.detectionLogs()); var blob = new Blob([data], {'type': 'text/json'}); var url = URL.createObjectURL(blob); var filename = 'translate_internals_detect_logs_dump.json'; var a = document.createElement('a'); a.setAttribute('href', url); a.setAttribute('download', filename); var event = document.createEvent('MouseEvent'); event.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, null); a.dispatchEvent(event); } return { detectionLogs: detectionLogs, initialize: initialize, messageHandler: messageHandler, }; }); /** * The entry point of the UI. */ function main() { cr.doc.addEventListener('DOMContentLoaded', cr.translateInternals.initialize); } main(); })();
TeamEOS/external_chromium_org
chrome/browser/resources/translate_internals/translate_internals.js
JavaScript
bsd-3-clause
14,159
/*------------------------------------------------------------------------- * drawElements Quality Program Tester Core * ---------------------------------------- * * Copyright 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Template class that is either type of Left or Right. *//*--------------------------------------------------------------------*/ #include "tcuEither.hpp" namespace tcu { namespace { enum { COPYCHECK_VALUE = 1637423219 }; class TestClassWithConstructor { public: TestClassWithConstructor (int i) : m_i (i) , m_copyCheck (COPYCHECK_VALUE) { } ~TestClassWithConstructor (void) { DE_TEST_ASSERT(m_copyCheck == COPYCHECK_VALUE); } TestClassWithConstructor (const TestClassWithConstructor& other) : m_i (other.m_i) , m_copyCheck (other.m_copyCheck) { } TestClassWithConstructor& operator= (const TestClassWithConstructor& other) { TCU_CHECK(m_copyCheck == COPYCHECK_VALUE); if (this == &other) return *this; m_i = other.m_i; m_copyCheck = other.m_copyCheck; TCU_CHECK(m_copyCheck == COPYCHECK_VALUE); return *this; } int getValue (void) const { TCU_CHECK(m_copyCheck == COPYCHECK_VALUE); return m_i; } private: int m_i; int m_copyCheck; }; } // anonymous void Either_selfTest (void) { // Simple test for first { const int intValue = 1503457782; const Either<int, float> either (intValue); TCU_CHECK(either.isFirst()); TCU_CHECK(!either.isSecond()); TCU_CHECK(either.is<int>()); TCU_CHECK(!either.is<float>()); TCU_CHECK(either.getFirst() == intValue); TCU_CHECK(either.get<int>() == intValue); } // Simple test for second { const float floatValue = 0.43223332995f; const Either<int, float> either (floatValue); TCU_CHECK(!either.isFirst()); TCU_CHECK(either.isSecond()); TCU_CHECK(!either.is<int>()); TCU_CHECK(either.is<float>()); TCU_CHECK(either.getSecond() == floatValue); TCU_CHECK(either.get<float>() == floatValue); } // Assign first value { const int intValue = 1942092699; const float floatValue = 0.43223332995f; Either<int, float> either (floatValue); either = intValue; TCU_CHECK(either.isFirst()); TCU_CHECK(!either.isSecond()); TCU_CHECK(either.is<int>()); TCU_CHECK(!either.is<float>()); TCU_CHECK(either.getFirst() == intValue); TCU_CHECK(either.get<int>() == intValue); } // Assign second value { const int intValue = 1942092699; const float floatValue = 0.43223332995f; Either<int, float> either (intValue); either = floatValue; TCU_CHECK(!either.isFirst()); TCU_CHECK(either.isSecond()); TCU_CHECK(!either.is<int>()); TCU_CHECK(either.is<float>()); TCU_CHECK(either.getSecond() == floatValue); TCU_CHECK(either.get<float>() == floatValue); } // Assign first either value { const int intValue = 1942092699; const float floatValue = 0.43223332995f; Either<int, float> either (floatValue); const Either<int, float> otherEither (intValue); either = otherEither; TCU_CHECK(either.isFirst()); TCU_CHECK(!either.isSecond()); TCU_CHECK(either.is<int>()); TCU_CHECK(!either.is<float>()); TCU_CHECK(either.getFirst() == intValue); TCU_CHECK(either.get<int>() == intValue); } // Assign second either value { const int intValue = 1942092699; const float floatValue = 0.43223332995f; Either<int, float> either (intValue); const Either<int, float> otherEither (floatValue); either = otherEither; TCU_CHECK(!either.isFirst()); TCU_CHECK(either.isSecond()); TCU_CHECK(!either.is<int>()); TCU_CHECK(either.is<float>()); TCU_CHECK(either.getSecond() == floatValue); TCU_CHECK(either.get<float>() == floatValue); } // Simple test for first with constructor { const TestClassWithConstructor testObject (171899615); const Either<TestClassWithConstructor, int> either (testObject); TCU_CHECK(either.isFirst()); TCU_CHECK(!either.isSecond()); TCU_CHECK(either.is<TestClassWithConstructor>()); TCU_CHECK(!either.is<int>()); TCU_CHECK(either.getFirst().getValue() == testObject.getValue()); TCU_CHECK(either.get<TestClassWithConstructor>().getValue() == testObject.getValue()); } // Simple test for second with constructor { const TestClassWithConstructor testObject (171899615); const Either<int, TestClassWithConstructor> either (testObject); TCU_CHECK(!either.isFirst()); TCU_CHECK(either.isSecond()); TCU_CHECK(either.is<TestClassWithConstructor>()); TCU_CHECK(!either.is<int>()); TCU_CHECK(either.getSecond().getValue() == testObject.getValue()); TCU_CHECK(either.get<TestClassWithConstructor>().getValue() == testObject.getValue()); } // Assign first with constructor { const int intValue = 1942092699; const TestClassWithConstructor testObject (171899615); Either<TestClassWithConstructor, int> either (intValue); either = testObject; TCU_CHECK(either.isFirst()); TCU_CHECK(!either.isSecond()); TCU_CHECK(either.is<TestClassWithConstructor>()); TCU_CHECK(!either.is<int>()); TCU_CHECK(either.getFirst().getValue() == testObject.getValue()); TCU_CHECK(either.get<TestClassWithConstructor>().getValue() == testObject.getValue()); } // Assign second with constructor { const int intValue = 1942092699; const TestClassWithConstructor testObject (171899615); Either<int, TestClassWithConstructor> either (intValue); either = testObject; TCU_CHECK(!either.isFirst()); TCU_CHECK(either.isSecond()); TCU_CHECK(either.is<TestClassWithConstructor>()); TCU_CHECK(!either.is<int>()); TCU_CHECK(either.getSecond().getValue() == testObject.getValue()); TCU_CHECK(either.get<TestClassWithConstructor>().getValue() == testObject.getValue()); } // Assign first either with constructor { const int intValue = 1942092699; const TestClassWithConstructor testObject (171899615); Either<TestClassWithConstructor, int> either (intValue); const Either<TestClassWithConstructor, int> otherEither (testObject); either = otherEither; TCU_CHECK(either.isFirst()); TCU_CHECK(!either.isSecond()); TCU_CHECK(either.is<TestClassWithConstructor>()); TCU_CHECK(!either.is<int>()); TCU_CHECK(either.getFirst().getValue() == testObject.getValue()); TCU_CHECK(either.get<TestClassWithConstructor>().getValue() == testObject.getValue()); } // Assign second either with constructor { const int intValue = 1942092699; const TestClassWithConstructor testObject (171899615); Either<int, TestClassWithConstructor> either (intValue); const Either<int, TestClassWithConstructor> otherEither (testObject); either = otherEither; TCU_CHECK(!either.isFirst()); TCU_CHECK(either.isSecond()); TCU_CHECK(either.is<TestClassWithConstructor>()); TCU_CHECK(!either.is<int>()); TCU_CHECK(either.getSecond().getValue() == testObject.getValue()); TCU_CHECK(either.get<TestClassWithConstructor>().getValue() == testObject.getValue()); } } } // tcu
endlessm/chromium-browser
third_party/angle/third_party/VK-GL-CTS/src/framework/common/tcuEither.cpp
C++
bsd-3-clause
7,576
var express = require('../') , request = require('supertest'); describe('app', function(){ describe('.response', function(){ it('should extend the response prototype', function(done){ var app = express(); app.response.shout = function(str){ this.send(str.toUpperCase()); }; app.use(function(req, res){ res.shout('hey'); }); request(app) .get('/') .expect('HEY', done); }) it('should not be influenced by other app protos', function(done){ var app = express() , app2 = express(); app.response.shout = function(str){ this.send(str.toUpperCase()); }; app2.response.shout = function(str){ this.send(str); }; app.use(function(req, res){ res.shout('hey'); }); request(app) .get('/') .expect('HEY', done); }) }) })
pkristoff/cnpa-regional-contest-web
vendor/assets/bower_components/express/test/app.response.js
JavaScript
gpl-2.0
896
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"), require("../../addon/mode/overlay")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../htmlmixed/htmlmixed", "../../addon/mode/overlay"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("tornado:inner", function() { var keywords = ["and","as","assert","autoescape","block","break","class","comment","context", "continue","datetime","def","del","elif","else","end","escape","except", "exec","extends","false","finally","for","from","global","if","import","in", "include","is","json_encode","lambda","length","linkify","load","module", "none","not","or","pass","print","put","raise","raw","return","self","set", "squeeze","super","true","try","url_escape","while","with","without","xhtml_escape","yield"]; keywords = new RegExp("^((" + keywords.join(")|(") + "))\\b"); function tokenBase (stream, state) { stream.eatWhile(/[^\{]/); var ch = stream.next(); if (ch == "{") { if (ch = stream.eat(/\{|%|#/)) { state.tokenize = inTag(ch); return "tag"; } } } function inTag (close) { if (close == "{") { close = "}"; } return function (stream, state) { var ch = stream.next(); if ((ch == close) && stream.eat("}")) { state.tokenize = tokenBase; return "tag"; } if (stream.match(keywords)) { return "keyword"; } return close == "#" ? "comment" : "string"; }; } return { startState: function () { return {tokenize: tokenBase}; }, token: function (stream, state) { return state.tokenize(stream, state); } }; }); CodeMirror.defineMode("tornado", function(config) { var htmlBase = CodeMirror.getMode(config, "text/html"); var tornadoInner = CodeMirror.getMode(config, "tornado:inner"); return CodeMirror.overlayMode(htmlBase, tornadoInner); }); CodeMirror.defineMIME("text/x-tornado", "tornado"); });
bobmagicii/atlantis
www/share/js/codemirror-modes/tornado/tornado.js
JavaScript
bsd-2-clause
2,497
/* Copyright (c) 2008-2015, Avian Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. There is NO WARRANTY for this software. See license.txt for details. */ package java.lang; public class ArithmeticException extends RuntimeException { public ArithmeticException(String message) { super(message); } public ArithmeticException() { this(null); } }
bgould/avian
classpath/java/lang/ArithmeticException.java
Java
isc
558
--TEST-- Test rename() function : variation - various relative, absolute paths --CREDITS-- Dave Kelsey <d_kelsey@uk.ibm.com> --SKIPIF-- <?php if (substr(PHP_OS, 0, 3) == 'WIN') die('skip.. not for Windows'); ?> --FILE-- <?php /* Prototype : bool rename(string old_name, string new_name[, resource context]) * Description: Rename a file * Source code: ext/standard/file.c * Alias to functions: */ /* Creating unique files in various dirs by passing relative paths to $dir arg */ echo "*** Testing rename() with absolute and relative paths ***\n"; $mainDir = "renameVar11"; $subDir = "renameVar11Sub"; $absMainDir = dirname(__FILE__)."/".$mainDir; mkdir($absMainDir); $absSubDir = $absMainDir."/".$subDir; mkdir($absSubDir); $fromFile = "renameMe.tmp"; $toFile = "IwasRenamed.tmp"; $old_dir_path = getcwd(); chdir(dirname(__FILE__)); $allDirs = array( // absolute paths "$absSubDir/", "$absSubDir/../".$subDir, "$absSubDir//.././".$subDir, "$absSubDir/../../".$mainDir."/./".$subDir, "$absSubDir/..///".$subDir."//..//../".$subDir, "$absSubDir/BADDIR", // relative paths $mainDir."/".$subDir, $mainDir."//".$subDir, $mainDir."///".$subDir, "./".$mainDir."/../".$mainDir."/".$subDir, "BADDIR", ); for($i = 0; $i<count($allDirs); $i++) { $j = $i+1; $dir = $allDirs[$i]; echo "\n-- Iteration $j --\n"; touch($absSubDir."/".$fromFile); $res = rename($dir."/".$fromFile, $dir."/".$toFile); var_dump($res); if ($res == true) { $res = rename($dir."/".$toFile, $dir."/".$fromFile); var_dump($res); } unlink($absSubDir."/".$fromFile); } chdir($old_dir_path); rmdir($absSubDir); rmdir($absMainDir); echo "\n*** Done ***\n"; ?> --EXPECTF-- *** Testing rename() with absolute and relative paths *** -- Iteration 1 -- bool(true) bool(true) -- Iteration 2 -- bool(true) bool(true) -- Iteration 3 -- bool(true) bool(true) -- Iteration 4 -- bool(true) bool(true) -- Iteration 5 -- Warning: rename(%s/renameVar11/renameVar11Sub/..///renameVar11Sub//..//../renameVar11Sub/renameMe.tmp,%s/renameVar11/renameVar11Sub/..///renameVar11Sub//..//../renameVar11Sub/IwasRenamed.tmp): %s in %s on line %d bool(false) -- Iteration 6 -- Warning: rename(%s/renameVar11/renameVar11Sub/BADDIR/renameMe.tmp,%s/renameVar11/renameVar11Sub/BADDIR/IwasRenamed.tmp): %s in %s on line %d bool(false) -- Iteration 7 -- bool(true) bool(true) -- Iteration 8 -- bool(true) bool(true) -- Iteration 9 -- bool(true) bool(true) -- Iteration 10 -- bool(true) bool(true) -- Iteration 11 -- Warning: rename(BADDIR/renameMe.tmp,BADDIR/IwasRenamed.tmp): %s in %s on line %d bool(false) *** Done ***
ericpp/hippyvm
test_phpt/ext/standard/file/rename_variation12.phpt
PHP
mit
2,641
// Type definitions for beeper 1.1 // Project: https://github.com/sindresorhus/beeper#readme // Definitions by: BendingBender <https://github.com/BendingBender> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = beeper; declare function beeper(count?: number, cb?: () => void): void; declare function beeper(melody: string, cb?: () => void): void;
magny/DefinitelyTyped
types/beeper/index.d.ts
TypeScript
mit
375
# Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. module AWS class ELB class LoadBalancerCollection include ListenerOpts include Core::Collection::Simple # Creates and returns a load balancer. A load balancer requires: # # * a unique name # * at least one availability zone # * at least one listener # # An example that creates a load balancer in two availability zones # with a single listener: # # load_balancer = elb.load_balancers.create('my-load-balancer', # :availability_zones => %w(us-west-2a us-west-2b), # :listeners => [{ # :port => 80, # :protocol => :http, # :instance_port => 80, # :instance_protocol => :http, # }]) # # @param [String] name The name of your load balancer. The name must # be unique within your set of load balancers. # # @param [Hash] options # # @option options [required,Array] :availability_zones An array of # one or more availability zones. Values may be availability zone # name strings, or {AWS::EC2::AvailabilityZone} objects. # # @option options [required,Array<Hash>] :listeners An array of load # balancer listener options: # * `:protocol` - *required* - (String) Specifies the LoadBalancer # transport protocol to use for routing - HTTP, HTTPS, TCP or SSL. # This property cannot be modified for the life of the # LoadBalancer. # * `:load_balancer_port` - *required* - (Integer) Specifies the # external LoadBalancer port number. This property cannot be # modified for the life of the LoadBalancer. # * `:instance_protocol` - (String) Specifies the protocol to use for # routing traffic to back-end instances - HTTP, HTTPS, TCP, or SSL. # This property cannot be modified for the life of the # LoadBalancer. If the front-end protocol is HTTP or HTTPS, # InstanceProtocol has to be at the same protocol layer, i.e., HTTP # or HTTPS. Likewise, if the front-end protocol is TCP or SSL, # InstanceProtocol has to be TCP or SSL. If there is another # listener with the same InstancePort whose InstanceProtocol is # secure, i.e., HTTPS or SSL, the listener's InstanceProtocol has # to be secure, i.e., HTTPS or SSL. If there is another listener # with the same InstancePort whose InstanceProtocol is HTTP or TCP, # the listener's InstanceProtocol must be either HTTP or TCP. # * `:instance_port` - *required* - (Integer) Specifies the TCP port # on which the instance server is listening. This property cannot # be modified for the life of the LoadBalancer. # * `:ssl_certificate_id` - (String) The ARN string of the server # certificate. To get the ARN of the server certificate, call the # AWS Identity and Access Management UploadServerCertificate API. # # @option options [Array] :subnets An list of VPC subets to attach the # load balancer to. This can be an array of subnet ids (strings) or # {EC2::Subnet} objects. VPC only. # # @option options [Array] :security_groups The security groups assigned to # your load balancer within your VPC. This can be an array of # security group ids or {EC2::SecurityGroup} objects. VPC only. # # @option options [String] :scheme ('internal' The type of a load # balancer. Accepts 'internet-facing' or 'internal'. VPC only. # def create name, options = {} if listeners = options[:listeners] options[:listeners] = [listeners].flatten.map do |listener| format_listener_opts(listener) end end if zones = options[:availability_zones] options[:availability_zones] = [zones].flatten.map do |zone| zone.is_a?(EC2::AvailabilityZone) ? zone.name : zone end end if groups = options[:security_groups] options[:security_groups] = [groups].flatten.map do |group| group.is_a?(EC2::SecurityGroup) ? group.id : group end end if subnets = options[:subnets] options[:subnets] = [subnets].flatten.map do |subnet| subnet.is_a?(EC2::Subnet) ? subnet.id : subnet end end options[:load_balancer_name] = name.to_s resp = client.create_load_balancer(options) LoadBalancer.new(name, :dns_name => resp[:dns_name], :config => config) end # @return [LoadBalancer] Returns the load balancer with the given # name. This does not make a request, just returns a reference. def [] name LoadBalancer.new(name, :config => config) end protected def _each_item options = {}, &block response = client.describe_load_balancers(options) response.data[:load_balancer_descriptions].each do |description| load_balancer = LoadBalancer.new_from( :describe_load_balancers, description, description[:load_balancer_name], :config => config) yield(load_balancer) end end end end end
nicolasbrechet/our-boxen
vendor/bundle/ruby/2.0.0/gems/aws-sdk-1.51.0/lib/aws/elb/load_balancer_collection.rb
Ruby
mit
5,961
-------------------------------- -- @module GridAction -- @extend ActionInterval -- @parent_module cc -------------------------------- -- returns the grid -- @function [parent=#GridAction] getGrid -- @param self -- @return GridBase#GridBase ret (return value: cc.GridBase) -------------------------------- -- -- @function [parent=#GridAction] startWithTarget -- @param self -- @param #cc.Node target -------------------------------- -- -- @function [parent=#GridAction] clone -- @param self -- @return GridAction#GridAction ret (return value: cc.GridAction) -------------------------------- -- -- @function [parent=#GridAction] reverse -- @param self -- @return GridAction#GridAction ret (return value: cc.GridAction) return nil
kinzhang/cocos2d-js-v3.2
frameworks/js-bindings/cocos2d-x/cocos/scripting/lua-bindings/auto/api/GridAction.lua
Lua
mit
776
ace.define("ace/theme/kuroir",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { exports.isDark = false; exports.cssClass = "ace-kuroir"; exports.cssText = "\ .ace-kuroir .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ .ace-kuroir .ace_print-margin {\ width: 1px;\ background: #e8e8e8;\ }\ .ace-kuroir {\ background-color: #E8E9E8;\ color: #363636;\ }\ .ace-kuroir .ace_cursor {\ color: #202020;\ }\ .ace-kuroir .ace_marker-layer .ace_selection {\ background: rgba(245, 170, 0, 0.57);\ }\ .ace-kuroir.ace_multiselect .ace_selection.ace_start {\ box-shadow: 0 0 3px 0px #E8E9E8;\ border-radius: 2px;\ }\ .ace-kuroir .ace_marker-layer .ace_step {\ background: rgb(198, 219, 174);\ }\ .ace-kuroir .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(0, 0, 0, 0.29);\ }\ .ace-kuroir .ace_marker-layer .ace_active-line {\ background: rgba(203, 220, 47, 0.22);\ }\ .ace-kuroir .ace_gutter-active-line {\ background-color: rgba(203, 220, 47, 0.22);\ }\ .ace-kuroir .ace_marker-layer .ace_selected-word {\ border: 1px solid rgba(245, 170, 0, 0.57);\ }\ .ace-kuroir .ace_invisible {\ color: #BFBFBF\ }\ .ace-kuroir .ace_fold {\ border-color: #363636;\ }\ .ace-kuroir .ace_constant{color:#CD6839;}.ace-kuroir .ace_constant.ace_numeric{color:#9A5925;}.ace-kuroir .ace_support{color:#104E8B;}.ace-kuroir .ace_support.ace_function{color:#005273;}.ace-kuroir .ace_support.ace_constant{color:#CF6A4C;}.ace-kuroir .ace_storage{color:#A52A2A;}.ace-kuroir .ace_invalid.ace_illegal{color:#FD1224;\ background-color:rgba(255, 6, 0, 0.15);}.ace-kuroir .ace_invalid.ace_deprecated{text-decoration:underline;\ font-style:italic;\ color:#FD1732;\ background-color:#E8E9E8;}.ace-kuroir .ace_string{color:#639300;}.ace-kuroir .ace_string.ace_regexp{color:#417E00;\ background-color:#C9D4BE;}.ace-kuroir .ace_comment{color:rgba(148, 148, 148, 0.91);\ background-color:rgba(220, 220, 220, 0.56);}.ace-kuroir .ace_variable{color:#009ACD;}.ace-kuroir .ace_meta.ace_tag{color:#005273;}.ace-kuroir .ace_markup.ace_heading{color:#B8012D;\ background-color:rgba(191, 97, 51, 0.051);}.ace-kuroir .ace_markup.ace_list{color:#8F5B26;}\ "; var dom = acequire("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
jedfoster/brace
theme/kuroir.js
JavaScript
mit
2,265
/* * Copyright 2005 Red Hat, Inc. and/or its affiliates. * * 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.drools.core.event.rule.impl; import org.kie.api.event.rule.RuleFlowGroupEvent; import org.kie.internal.runtime.KnowledgeRuntime; import org.kie.api.runtime.rule.RuleFlowGroup; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; public class RuleFlowGroupEventImpl implements RuleFlowGroupEvent, Externalizable { private RuleFlowGroup ruleFlowGroup; private KnowledgeRuntime kruntime; public RuleFlowGroupEventImpl(RuleFlowGroup ruleFlowGroup, KnowledgeRuntime kruntime) { this.ruleFlowGroup = ruleFlowGroup; this.kruntime = kruntime; } public RuleFlowGroup getRuleFlowGroup() { return ruleFlowGroup; } public KnowledgeRuntime getKieRuntime() { return this.kruntime; } public void writeExternal(ObjectOutput out) throws IOException { new SerializableRuleFlowGroup( this.ruleFlowGroup ).writeExternal( out ); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.ruleFlowGroup = new SerializableRuleFlowGroup( ); ((SerializableRuleFlowGroup)this.ruleFlowGroup).readExternal( in ); this.kruntime = null; // we null this as it isn't serializable; } @Override public String toString() { return "==>[RuleFlowGroupEventImpl: getRuleFlowGroup()=" + getRuleFlowGroup() + ", getKnowledgeRuntime()=" + getKieRuntime() + "]"; } }
rokn/Count_Words_2015
testing/drools-master/drools-core/src/main/java/org/drools/core/event/rule/impl/RuleFlowGroupEventImpl.java
Java
mit
2,161
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.Structure { internal abstract class AbstractSyntaxTriviaStructureProvider : AbstractSyntaxStructureProvider { public sealed override void CollectBlockSpans( SyntaxNode node, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { throw new NotSupportedException(); } } }
AlekseyTs/roslyn
src/Features/Core/Portable/Structure/Syntax/AbstractSyntaxTriviaStructureProvider.cs
C#
mit
760
/* * TCC - Tiny C Compiler * * Copyright (c) 2001-2004 Fabrice Bellard * * 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 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 */ #ifndef _TCC_H #define _TCC_H #define _GNU_SOURCE #include "config.h" #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include <errno.h> #include <math.h> #include <fcntl.h> #include <setjmp.h> #include <time.h> #ifndef _WIN32 # include <unistd.h> # include <sys/time.h> # ifndef CONFIG_TCC_STATIC # include <dlfcn.h> # endif /* XXX: need to define this to use them in non ISOC99 context */ extern float strtof (const char *__nptr, char **__endptr); extern long double strtold (const char *__nptr, char **__endptr); #endif #ifdef _WIN32 # include <windows.h> # include <io.h> /* open, close etc. */ # include <direct.h> /* getcwd */ # ifdef __GNUC__ # include <stdint.h> # endif # define inline __inline # define snprintf _snprintf # define vsnprintf _vsnprintf # ifndef __GNUC__ # define strtold (long double)strtod # define strtof (float)strtod # define strtoll _strtoi64 # define strtoull _strtoui64 # endif # ifdef LIBTCC_AS_DLL # define LIBTCCAPI __declspec(dllexport) # define PUB_FUNC LIBTCCAPI # endif # define inp next_inp /* inp is an intrinsic on msvc/mingw */ # ifdef _MSC_VER # pragma warning (disable : 4244) // conversion from 'uint64_t' to 'int', possible loss of data # pragma warning (disable : 4267) // conversion from 'size_t' to 'int', possible loss of data # pragma warning (disable : 4996) // The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name # pragma warning (disable : 4018) // signed/unsigned mismatch # pragma warning (disable : 4146) // unary minus operator applied to unsigned type, result still unsigned # define ssize_t intptr_t # endif # undef CONFIG_TCC_STATIC #endif #ifndef O_BINARY # define O_BINARY 0 #endif #ifndef offsetof #define offsetof(type, field) ((size_t) &((type *)0)->field) #endif #ifndef countof #define countof(tab) (sizeof(tab) / sizeof((tab)[0])) #endif #ifdef _MSC_VER # define NORETURN __declspec(noreturn) # define ALIGNED(x) __declspec(align(x)) #else # define NORETURN __attribute__((noreturn)) # define ALIGNED(x) __attribute__((aligned(x))) #endif #ifdef _WIN32 # define IS_DIRSEP(c) (c == '/' || c == '\\') # define IS_ABSPATH(p) (IS_DIRSEP(p[0]) || (p[0] && p[1] == ':' && IS_DIRSEP(p[2]))) # define PATHCMP stricmp # define PATHSEP ";" #else # define IS_DIRSEP(c) (c == '/') # define IS_ABSPATH(p) IS_DIRSEP(p[0]) # define PATHCMP strcmp # define PATHSEP ":" #endif /* -------------------------------------------- */ /* parser debug */ /* #define PARSE_DEBUG */ /* preprocessor debug */ /* #define PP_DEBUG */ /* include file debug */ /* #define INC_DEBUG */ /* memory leak debug */ /* #define MEM_DEBUG */ /* assembler debug */ /* #define ASM_DEBUG */ /* target selection */ /* #define TCC_TARGET_I386 *//* i386 code generator */ /* #define TCC_TARGET_X86_64 *//* x86-64 code generator */ /* #define TCC_TARGET_ARM *//* ARMv4 code generator */ /* #define TCC_TARGET_ARM64 *//* ARMv8 code generator */ /* #define TCC_TARGET_C67 *//* TMS320C67xx code generator */ /* default target is I386 */ #if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_ARM) && \ !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_C67) && \ !defined(TCC_TARGET_X86_64) # if defined __x86_64__ || defined _AMD64_ # define TCC_TARGET_X86_64 # elif defined __arm__ # define TCC_TARGET_ARM # define TCC_ARM_EABI # define TCC_ARM_HARDFLOAT # elif defined __aarch64__ # define TCC_TARGET_ARM64 # else # define TCC_TARGET_I386 # endif # ifdef _WIN32 # define TCC_TARGET_PE 1 # endif #endif /* only native compiler supports -run */ #if defined _WIN32 == defined TCC_TARGET_PE # if (defined __i386__ || defined _X86_) && defined TCC_TARGET_I386 # define TCC_IS_NATIVE # elif (defined __x86_64__ || defined _AMD64_) && defined TCC_TARGET_X86_64 # define TCC_IS_NATIVE # elif defined __arm__ && defined TCC_TARGET_ARM # define TCC_IS_NATIVE # elif defined __aarch64__ && defined TCC_TARGET_ARM64 # define TCC_IS_NATIVE # endif #endif #if defined TCC_IS_NATIVE && !defined CONFIG_TCCBOOT # define CONFIG_TCC_BACKTRACE # if (defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64) \ && !defined TCC_UCLIBC && !defined TCC_MUSL # define CONFIG_TCC_BCHECK /* enable bound checking code */ # endif #endif /* ------------ path configuration ------------ */ #ifndef CONFIG_SYSROOT # define CONFIG_SYSROOT "" #endif #ifndef CONFIG_TCCDIR # define CONFIG_TCCDIR "/usr/local/lib/tcc" #endif #ifndef CONFIG_LDDIR # define CONFIG_LDDIR "lib" #endif #ifdef CONFIG_TRIPLET # define USE_TRIPLET(s) s "/" CONFIG_TRIPLET # define ALSO_TRIPLET(s) USE_TRIPLET(s) ":" s #else # define USE_TRIPLET(s) s # define ALSO_TRIPLET(s) s #endif /* path to find crt1.o, crti.o and crtn.o */ #ifndef CONFIG_TCC_CRTPREFIX # define CONFIG_TCC_CRTPREFIX USE_TRIPLET(CONFIG_SYSROOT "/usr/" CONFIG_LDDIR) #endif /* Below: {B} is substituted by CONFIG_TCCDIR (rsp. -B option) */ /* system include paths */ #ifndef CONFIG_TCC_SYSINCLUDEPATHS # ifdef TCC_TARGET_PE # define CONFIG_TCC_SYSINCLUDEPATHS "{B}/include"PATHSEP"{B}/include/winapi" # else # define CONFIG_TCC_SYSINCLUDEPATHS \ "{B}/include" \ ":" ALSO_TRIPLET(CONFIG_SYSROOT "/usr/local/include") \ ":" ALSO_TRIPLET(CONFIG_SYSROOT "/usr/include") # endif #endif /* library search paths */ #ifndef CONFIG_TCC_LIBPATHS # ifdef TCC_TARGET_PE # define CONFIG_TCC_LIBPATHS "{B}/lib" # else # define CONFIG_TCC_LIBPATHS \ ALSO_TRIPLET(CONFIG_SYSROOT "/usr/" CONFIG_LDDIR) \ ":" ALSO_TRIPLET(CONFIG_SYSROOT "/" CONFIG_LDDIR) \ ":" ALSO_TRIPLET(CONFIG_SYSROOT "/usr/local/" CONFIG_LDDIR) # endif #endif /* name of ELF interpreter */ #ifndef CONFIG_TCC_ELFINTERP # if defined __FreeBSD__ # define CONFIG_TCC_ELFINTERP "/libexec/ld-elf.so.1" # elif defined __FreeBSD_kernel__ # if defined(TCC_TARGET_X86_64) # define CONFIG_TCC_ELFINTERP "/lib/ld-kfreebsd-x86-64.so.1" # else # define CONFIG_TCC_ELFINTERP "/lib/ld.so.1" # endif # elif defined __DragonFly__ # define CONFIG_TCC_ELFINTERP "/usr/libexec/ld-elf.so.2" # elif defined __NetBSD__ # define CONFIG_TCC_ELFINTERP "/usr/libexec/ld.elf_so" # elif defined __GNU__ # define CONFIG_TCC_ELFINTERP "/lib/ld.so" # elif defined(TCC_TARGET_PE) # define CONFIG_TCC_ELFINTERP "-" # elif defined(TCC_UCLIBC) # define CONFIG_TCC_ELFINTERP "/lib/ld-uClibc.so.0" /* is there a uClibc for x86_64 ? */ # elif defined TCC_TARGET_ARM64 # if defined(TCC_MUSL) # define CONFIG_TCC_ELFINTERP "/lib/ld-musl-aarch64.so.1" # else # define CONFIG_TCC_ELFINTERP "/lib/ld-linux-aarch64.so.1" # endif # elif defined(TCC_TARGET_X86_64) # if defined(TCC_MUSL) # define CONFIG_TCC_ELFINTERP "/lib/ld-musl-x86_64.so.1" # else # define CONFIG_TCC_ELFINTERP "/lib64/ld-linux-x86-64.so.2" # endif # elif !defined(TCC_ARM_EABI) # if defined(TCC_MUSL) # define CONFIG_TCC_ELFINTERP "/lib/ld-musl-arm.so.1" # else # define CONFIG_TCC_ELFINTERP "/lib/ld-linux.so.2" # endif # endif #endif /* var elf_interp dans *-gen.c */ #ifdef CONFIG_TCC_ELFINTERP # define DEFAULT_ELFINTERP(s) CONFIG_TCC_ELFINTERP #else # define DEFAULT_ELFINTERP(s) default_elfinterp(s) #endif /* (target specific) libtcc1.a */ #ifndef TCC_LIBTCC1 # define TCC_LIBTCC1 "libtcc1.a" #endif /* library to use with CONFIG_USE_LIBGCC instead of libtcc1.a */ #if defined CONFIG_USE_LIBGCC && !defined TCC_LIBGCC #define TCC_LIBGCC USE_TRIPLET(CONFIG_SYSROOT "/" CONFIG_LDDIR) "/libgcc_s.so.1" #endif /* -------------------------------------------- */ #include "libtcc.h" #include "elf.h" #include "stab.h" /* -------------------------------------------- */ #ifndef PUB_FUNC /* functions used by tcc.c but not in libtcc.h */ # define PUB_FUNC #endif #ifndef ONE_SOURCE # define ONE_SOURCE 1 #endif #if ONE_SOURCE #define ST_INLN static inline #define ST_FUNC static #define ST_DATA static #else #define ST_INLN #define ST_FUNC #define ST_DATA extern #endif #ifdef TCC_PROFILE /* profile all functions */ # define static #endif /* -------------------------------------------- */ /* include the target specific definitions */ #define TARGET_DEFS_ONLY #ifdef TCC_TARGET_I386 # include "i386-gen.c" # include "i386-link.c" #endif #ifdef TCC_TARGET_X86_64 # include "x86_64-gen.c" # include "x86_64-link.c" #endif #ifdef TCC_TARGET_ARM # include "arm-gen.c" # include "arm-link.c" # include "arm-asm.c" #endif #ifdef TCC_TARGET_ARM64 # include "arm64-gen.c" # include "arm64-link.c" #endif #ifdef TCC_TARGET_C67 # define TCC_TARGET_COFF # include "coff.h" # include "c67-gen.c" # include "c67-link.c" #endif #undef TARGET_DEFS_ONLY /* -------------------------------------------- */ #if PTR_SIZE == 8 # define ELFCLASSW ELFCLASS64 # define ElfW(type) Elf##64##_##type # define ELFW(type) ELF##64##_##type # define ElfW_Rel ElfW(Rela) # define SHT_RELX SHT_RELA # define REL_SECTION_FMT ".rela%s" #else # define ELFCLASSW ELFCLASS32 # define ElfW(type) Elf##32##_##type # define ELFW(type) ELF##32##_##type # define ElfW_Rel ElfW(Rel) # define SHT_RELX SHT_REL # define REL_SECTION_FMT ".rel%s" #endif /* target address type */ #define addr_t ElfW(Addr) #if PTR_SIZE == 8 && !defined TCC_TARGET_PE # define LONG_SIZE 8 #else # define LONG_SIZE 4 #endif /* -------------------------------------------- */ #define INCLUDE_STACK_SIZE 32 #define IFDEF_STACK_SIZE 64 #define VSTACK_SIZE 256 #define STRING_MAX_SIZE 1024 #define TOKSTR_MAX_SIZE 256 #define PACK_STACK_SIZE 8 #define TOK_HASH_SIZE 16384 /* must be a power of two */ #define TOK_ALLOC_INCR 512 /* must be a power of two */ #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */ /* token symbol management */ typedef struct TokenSym { struct TokenSym *hash_next; struct Sym *sym_define; /* direct pointer to define */ struct Sym *sym_label; /* direct pointer to label */ struct Sym *sym_struct; /* direct pointer to structure */ struct Sym *sym_identifier; /* direct pointer to identifier */ int tok; /* token number */ int len; char str[1]; } TokenSym; #ifdef TCC_TARGET_PE typedef unsigned short nwchar_t; #else typedef int nwchar_t; #endif typedef struct CString { int size; /* size in bytes */ void *data; /* either 'char *' or 'nwchar_t *' */ int size_allocated; } CString; /* type definition */ typedef struct CType { int t; struct Sym *ref; } CType; /* constant value */ typedef union CValue { long double ld; double d; float f; uint64_t i; struct { int size; const void *data; } str; int tab[LDOUBLE_SIZE/4]; } CValue; /* value on stack */ typedef struct SValue { CType type; /* type */ unsigned short r; /* register + flags */ unsigned short r2; /* second register, used for 'long long' type. If not used, set to VT_CONST */ CValue c; /* constant, if VT_CONST */ struct Sym *sym; /* symbol, if (VT_SYM | VT_CONST), or if result of unary() for an identifier. */ } SValue; /* symbol attributes */ struct SymAttr { unsigned short aligned : 5, /* alignment as log2+1 (0 == unspecified) */ packed : 1, weak : 1, visibility : 2, dllexport : 1, dllimport : 1, unused : 5; }; /* function attributes or temporary attributes for parsing */ struct FuncAttr { unsigned func_call : 3, /* calling convention (0..5), see below */ func_type : 2, /* FUNC_OLD/NEW/ELLIPSIS */ func_body : 1, /* body was defined */ func_args : 8; /* PE __stdcall args */ }; /* GNUC attribute definition */ typedef struct AttributeDef { struct SymAttr a; struct FuncAttr f; struct Section *section; int alias_target; /* token */ int asm_label; /* associated asm label */ char attr_mode; /* __attribute__((__mode__(...))) */ } AttributeDef; /* symbol management */ typedef struct Sym { int v; /* symbol token */ unsigned short r; /* associated register or VT_CONST/VT_LOCAL and LVAL type */ struct SymAttr a; /* symbol attributes */ union { struct { int c; /* associated number or Elf symbol index */ union { int sym_scope; /* scope level for locals */ int jnext; /* next jump label */ struct FuncAttr f; /* function attributes */ int auxtype; /* bitfield access type */ }; }; long long enum_val; /* enum constant if IS_ENUM_VAL */ int *d; /* define token stream */ }; CType type; /* associated type */ union { struct Sym *next; /* next related symbol (for fields and anoms) */ int asm_label; /* associated asm label */ }; struct Sym *prev; /* prev symbol in stack */ struct Sym *prev_tok; /* previous symbol for this token */ } Sym; /* section definition */ /* XXX: use directly ELF structure for parameters ? */ /* special flag to indicate that the section should not be linked to the other ones */ #define SHF_PRIVATE 0x80000000 /* special flag, too */ #define SECTION_ABS ((void *)1) typedef struct Section { unsigned long data_offset; /* current data offset */ unsigned char *data; /* section data */ unsigned long data_allocated; /* used for realloc() handling */ int sh_name; /* elf section name (only used during output) */ int sh_num; /* elf section number */ int sh_type; /* elf section type */ int sh_flags; /* elf section flags */ int sh_info; /* elf section info */ int sh_addralign; /* elf section alignment */ int sh_entsize; /* elf entry size */ unsigned long sh_size; /* section size (only used during output) */ addr_t sh_addr; /* address at which the section is relocated */ unsigned long sh_offset; /* file offset */ int nb_hashed_syms; /* used to resize the hash table */ struct Section *link; /* link to another section */ struct Section *reloc; /* corresponding section for relocation, if any */ struct Section *hash; /* hash table for symbols */ struct Section *prev; /* previous section on section stack */ char name[1]; /* section name */ } Section; typedef struct DLLReference { int level; void *handle; char name[1]; } DLLReference; /* -------------------------------------------------- */ #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */ #define SYM_FIELD 0x20000000 /* struct/union field symbol space */ #define SYM_FIRST_ANOM 0x10000000 /* first anonymous sym */ /* stored in 'Sym->f.func_type' field */ #define FUNC_NEW 1 /* ansi function prototype */ #define FUNC_OLD 2 /* old function prototype */ #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */ /* stored in 'Sym->f.func_call' field */ #define FUNC_CDECL 0 /* standard c call */ #define FUNC_STDCALL 1 /* pascal c call */ #define FUNC_FASTCALL1 2 /* first param in %eax */ #define FUNC_FASTCALL2 3 /* first parameters in %eax, %edx */ #define FUNC_FASTCALL3 4 /* first parameter in %eax, %edx, %ecx */ #define FUNC_FASTCALLW 5 /* first parameter in %ecx, %edx */ /* field 'Sym.t' for macros */ #define MACRO_OBJ 0 /* object like macro */ #define MACRO_FUNC 1 /* function like macro */ /* field 'Sym.r' for C labels */ #define LABEL_DEFINED 0 /* label is defined */ #define LABEL_FORWARD 1 /* label is forward defined */ #define LABEL_DECLARED 2 /* label is declared but never used */ /* type_decl() types */ #define TYPE_ABSTRACT 1 /* type without variable */ #define TYPE_DIRECT 2 /* type with variable */ #define IO_BUF_SIZE 8192 typedef struct BufferedFile { uint8_t *buf_ptr; uint8_t *buf_end; int fd; struct BufferedFile *prev; int line_num; /* current line number - here to simplify code */ int line_ref; /* tcc -E: last printed line */ int ifndef_macro; /* #ifndef macro / #endif search */ int ifndef_macro_saved; /* saved ifndef_macro */ int *ifdef_stack_ptr; /* ifdef_stack value at the start of the file */ int include_next_index; /* next search path */ char filename[1024]; /* filename */ char *true_filename; /* filename not modified by # line directive */ unsigned char unget[4]; unsigned char buffer[1]; /* extra size for CH_EOB char */ } BufferedFile; #define CH_EOB '\\' /* end of buffer or '\0' char in file */ #define CH_EOF (-1) /* end of file */ /* used to record tokens */ typedef struct TokenString { int *str; int len; int lastlen; int allocated_len; int last_line_num; int save_line_num; /* used to chain token-strings with begin/end_macro() */ struct TokenString *prev; const int *prev_ptr; char alloc; } TokenString; /* inline functions */ typedef struct InlineFunc { TokenString *func_str; Sym *sym; char filename[1]; } InlineFunc; /* include file cache, used to find files faster and also to eliminate inclusion if the include file is protected by #ifndef ... #endif */ typedef struct CachedInclude { int ifndef_macro; int once; int hash_next; /* -1 if none */ char filename[1]; /* path specified in #include */ } CachedInclude; #define CACHED_INCLUDES_HASH_SIZE 32 #ifdef CONFIG_TCC_ASM typedef struct ExprValue { uint64_t v; Sym *sym; int pcrel; } ExprValue; #define MAX_ASM_OPERANDS 30 typedef struct ASMOperand { int id; /* GCC 3 optional identifier (0 if number only supported */ char *constraint; char asm_str[16]; /* computed asm string for operand */ SValue *vt; /* C value of the expression */ int ref_index; /* if >= 0, gives reference to a output constraint */ int input_index; /* if >= 0, gives reference to an input constraint */ int priority; /* priority, used to assign registers */ int reg; /* if >= 0, register number used for this operand */ int is_llong; /* true if double register value */ int is_memory; /* true if memory operand */ int is_rw; /* for '+' modifier */ } ASMOperand; #endif /* extra symbol attributes (not in symbol table) */ struct sym_attr { unsigned got_offset; unsigned plt_offset; int plt_sym; int dyn_index; #ifdef TCC_TARGET_ARM unsigned char plt_thumb_stub:1; #endif }; struct TCCState { int verbose; /* if true, display some information during compilation */ int nostdinc; /* if true, no standard headers are added */ int nostdlib; /* if true, no standard libraries are added */ int nocommon; /* if true, do not use common symbols for .bss data */ int static_link; /* if true, static linking is performed */ int rdynamic; /* if true, all symbols are exported */ int symbolic; /* if true, resolve symbols in the current module first */ int alacarte_link; /* if true, only link in referenced objects from archive */ char *tcc_lib_path; /* CONFIG_TCCDIR or -B option */ char *soname; /* as specified on the command line (-soname) */ char *rpath; /* as specified on the command line (-Wl,-rpath=) */ int enable_new_dtags; /* ditto, (-Wl,--enable-new-dtags) */ /* output type, see TCC_OUTPUT_XXX */ int output_type; /* output format, see TCC_OUTPUT_FORMAT_xxx */ int output_format; /* C language options */ int char_is_unsigned; int leading_underscore; int ms_extensions; /* allow nested named struct w/o identifier behave like unnamed */ int dollars_in_identifiers; /* allows '$' char in identifiers */ int ms_bitfields; /* if true, emulate MS algorithm for aligning bitfields */ /* warning switches */ int warn_write_strings; int warn_unsupported; int warn_error; int warn_none; int warn_implicit_function_declaration; int warn_gcc_compat; /* compile with debug symbol (and use them if error during execution) */ int do_debug; #ifdef CONFIG_TCC_BCHECK /* compile with built-in memory and bounds checker */ int do_bounds_check; #endif #ifdef TCC_TARGET_ARM enum float_abi float_abi; /* float ABI of the generated code*/ #endif int run_test; /* nth test to run with -dt -run */ addr_t text_addr; /* address of text section */ int has_text_addr; unsigned section_align; /* section alignment */ char *init_symbol; /* symbols to call at load-time (not used currently) */ char *fini_symbol; /* symbols to call at unload-time (not used currently) */ #ifdef TCC_TARGET_I386 int seg_size; /* 32. Can be 16 with i386 assembler (.code16) */ #endif #ifdef TCC_TARGET_X86_64 int nosse; /* For -mno-sse support. */ #endif /* array of all loaded dlls (including those referenced by loaded dlls) */ DLLReference **loaded_dlls; int nb_loaded_dlls; /* include paths */ char **include_paths; int nb_include_paths; char **sysinclude_paths; int nb_sysinclude_paths; /* library paths */ char **library_paths; int nb_library_paths; /* crt?.o object path */ char **crt_paths; int nb_crt_paths; /* -include files */ char **cmd_include_files; int nb_cmd_include_files; /* error handling */ void *error_opaque; void (*error_func)(void *opaque, const char *msg); int error_set_jmp_enabled; jmp_buf error_jmp_buf; int nb_errors; /* output file for preprocessing (-E) */ FILE *ppfp; enum { LINE_MACRO_OUTPUT_FORMAT_GCC, LINE_MACRO_OUTPUT_FORMAT_NONE, LINE_MACRO_OUTPUT_FORMAT_STD, LINE_MACRO_OUTPUT_FORMAT_P10 = 11 } Pflag; /* -P switch */ char dflag; /* -dX value */ /* for -MD/-MF: collected dependencies for this compilation */ char **target_deps; int nb_target_deps; /* compilation */ BufferedFile *include_stack[INCLUDE_STACK_SIZE]; BufferedFile **include_stack_ptr; int ifdef_stack[IFDEF_STACK_SIZE]; int *ifdef_stack_ptr; /* included files enclosed with #ifndef MACRO */ int cached_includes_hash[CACHED_INCLUDES_HASH_SIZE]; CachedInclude **cached_includes; int nb_cached_includes; /* #pragma pack stack */ int pack_stack[PACK_STACK_SIZE]; int *pack_stack_ptr; char **pragma_libs; int nb_pragma_libs; /* inline functions are stored as token lists and compiled last only if referenced */ struct InlineFunc **inline_fns; int nb_inline_fns; /* sections */ Section **sections; int nb_sections; /* number of sections, including first dummy section */ Section **priv_sections; int nb_priv_sections; /* number of private sections */ /* got & plt handling */ Section *got; Section *plt; /* temporary dynamic symbol sections (for dll loading) */ Section *dynsymtab_section; /* exported dynamic symbol section */ Section *dynsym; /* copy of the global symtab_section variable */ Section *symtab; /* extra attributes (eg. GOT/PLT value) for symtab symbols */ struct sym_attr *sym_attrs; int nb_sym_attrs; /* tiny assembler state */ Sym *asm_labels; #ifdef TCC_TARGET_PE /* PE info */ int pe_subsystem; unsigned pe_characteristics; unsigned pe_file_align; unsigned pe_stack_size; # ifdef TCC_TARGET_X86_64 Section *uw_pdata; int uw_sym; unsigned uw_offs; # endif #endif #ifdef TCC_IS_NATIVE const char *runtime_main; void **runtime_mem; int nb_runtime_mem; #endif /* used by main and tcc_parse_args only */ struct filespec **files; /* files seen on command line */ int nb_files; /* number thereof */ int nb_libraries; /* number of libs thereof */ int filetype; char *outfile; /* output filename */ int option_r; /* option -r */ int do_bench; /* option -bench */ int gen_deps; /* option -MD */ char *deps_outfile; /* option -MF */ int option_pthread; /* -pthread option */ int argc; char **argv; }; struct filespec { char type; char alacarte; char name[1]; }; /* The current value can be: */ #define VT_VALMASK 0x003f /* mask for value location, register or: */ #define VT_CONST 0x0030 /* constant in vc (must be first non register value) */ #define VT_LLOCAL 0x0031 /* lvalue, offset on stack */ #define VT_LOCAL 0x0032 /* offset on stack */ #define VT_CMP 0x0033 /* the value is stored in processor flags (in vc) */ #define VT_JMP 0x0034 /* value is the consequence of jmp true (even) */ #define VT_JMPI 0x0035 /* value is the consequence of jmp false (odd) */ #define VT_LVAL 0x0100 /* var is an lvalue */ #define VT_SYM 0x0200 /* a symbol value is added */ #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for char/short stored in integer registers) */ #define VT_MUSTBOUND 0x0800 /* bound checking must be done before dereferencing value */ #define VT_BOUNDED 0x8000 /* value is bounded. The address of the bounding function call point is in vc */ #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */ #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */ #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */ #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED) /* types */ #define VT_BTYPE 0x000f /* mask for basic type */ #define VT_VOID 0 /* void type */ #define VT_BYTE 1 /* signed byte type */ #define VT_SHORT 2 /* short type */ #define VT_INT 3 /* integer type */ #define VT_LLONG 4 /* 64 bit integer */ #define VT_PTR 5 /* pointer */ #define VT_FUNC 6 /* function type */ #define VT_STRUCT 7 /* struct/union definition */ #define VT_FLOAT 8 /* IEEE float */ #define VT_DOUBLE 9 /* IEEE double */ #define VT_LDOUBLE 10 /* IEEE long double */ #define VT_BOOL 11 /* ISOC99 boolean type */ #define VT_QLONG 13 /* 128-bit integer. Only used for x86-64 ABI */ #define VT_QFLOAT 14 /* 128-bit float. Only used for x86-64 ABI */ #define VT_UNSIGNED 0x0010 /* unsigned type */ #define VT_DEFSIGN 0x0020 /* explicitly signed or unsigned */ #define VT_ARRAY 0x0040 /* array type (also has VT_PTR) */ #define VT_BITFIELD 0x0080 /* bitfield modifier */ #define VT_CONSTANT 0x0100 /* const modifier */ #define VT_VOLATILE 0x0200 /* volatile modifier */ #define VT_VLA 0x0400 /* VLA type (also has VT_PTR and VT_ARRAY) */ #define VT_LONG 0x0800 /* long type (also has VT_INT rsp. VT_LLONG) */ /* storage */ #define VT_EXTERN 0x00001000 /* extern definition */ #define VT_STATIC 0x00002000 /* static variable */ #define VT_TYPEDEF 0x00004000 /* typedef definition */ #define VT_INLINE 0x00008000 /* inline definition */ /* currently unused: 0x000[1248]0000 */ #define VT_STRUCT_SHIFT 20 /* shift for bitfield shift values (32 - 2*6) */ #define VT_STRUCT_MASK (((1 << (6+6)) - 1) << VT_STRUCT_SHIFT | VT_BITFIELD) #define BIT_POS(t) (((t) >> VT_STRUCT_SHIFT) & 0x3f) #define BIT_SIZE(t) (((t) >> (VT_STRUCT_SHIFT + 6)) & 0x3f) #define VT_UNION (1 << VT_STRUCT_SHIFT | VT_STRUCT) #define VT_ENUM (2 << VT_STRUCT_SHIFT) /* integral type is an enum really */ #define VT_ENUM_VAL (3 << VT_STRUCT_SHIFT) /* integral type is an enum constant really */ #define IS_ENUM(t) ((t & VT_STRUCT_MASK) == VT_ENUM) #define IS_ENUM_VAL(t) ((t & VT_STRUCT_MASK) == VT_ENUM_VAL) #define IS_UNION(t) ((t & (VT_STRUCT_MASK|VT_BTYPE)) == VT_UNION) /* type mask (except storage) */ #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE) #define VT_TYPE (~(VT_STORAGE|VT_STRUCT_MASK)) /* token values */ /* warning: the following compare tokens depend on i386 asm code */ #define TOK_ULT 0x92 #define TOK_UGE 0x93 #define TOK_EQ 0x94 #define TOK_NE 0x95 #define TOK_ULE 0x96 #define TOK_UGT 0x97 #define TOK_Nset 0x98 #define TOK_Nclear 0x99 #define TOK_LT 0x9c #define TOK_GE 0x9d #define TOK_LE 0x9e #define TOK_GT 0x9f #define TOK_LAND 0xa0 #define TOK_LOR 0xa1 #define TOK_DEC 0xa2 #define TOK_MID 0xa3 /* inc/dec, to void constant */ #define TOK_INC 0xa4 #define TOK_UDIV 0xb0 /* unsigned division */ #define TOK_UMOD 0xb1 /* unsigned modulo */ #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */ /* tokens that carry values (in additional token string space / tokc) --> */ #define TOK_CCHAR 0xb3 /* char constant in tokc */ #define TOK_LCHAR 0xb4 #define TOK_CINT 0xb5 /* number in tokc */ #define TOK_CUINT 0xb6 /* unsigned int constant */ #define TOK_CLLONG 0xb7 /* long long constant */ #define TOK_CULLONG 0xb8 /* unsigned long long constant */ #define TOK_STR 0xb9 /* pointer to string in tokc */ #define TOK_LSTR 0xba #define TOK_CFLOAT 0xbb /* float constant */ #define TOK_CDOUBLE 0xbc /* double constant */ #define TOK_CLDOUBLE 0xbd /* long double constant */ #define TOK_PPNUM 0xbe /* preprocessor number */ #define TOK_PPSTR 0xbf /* preprocessor string */ #define TOK_LINENUM 0xc0 /* line number info */ #define TOK_TWODOTS 0xa8 /* C++ token ? */ /* <-- */ #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */ #define TOK_ADDC1 0xc3 /* add with carry generation */ #define TOK_ADDC2 0xc4 /* add with carry use */ #define TOK_SUBC1 0xc5 /* add with carry generation */ #define TOK_SUBC2 0xc6 /* add with carry use */ #define TOK_ARROW 0xc7 #define TOK_DOTS 0xc8 /* three dots */ #define TOK_SHR 0xc9 /* unsigned shift right */ #define TOK_TWOSHARPS 0xca /* ## preprocessing token */ #define TOK_PLCHLDR 0xcb /* placeholder token as defined in C99 */ #define TOK_NOSUBST 0xcc /* means following token has already been pp'd */ #define TOK_PPJOIN 0xcd /* A '##' in the right position to mean pasting */ #define TOK_CLONG 0xce /* long constant */ #define TOK_CULONG 0xcf /* unsigned long constant */ #define TOK_SHL 0x01 /* shift left */ #define TOK_SAR 0x02 /* signed shift right */ /* assignment operators : normal operator or 0x80 */ #define TOK_A_MOD 0xa5 #define TOK_A_AND 0xa6 #define TOK_A_MUL 0xaa #define TOK_A_ADD 0xab #define TOK_A_SUB 0xad #define TOK_A_DIV 0xaf #define TOK_A_XOR 0xde #define TOK_A_OR 0xfc #define TOK_A_SHL 0x81 #define TOK_A_SAR 0x82 #define TOK_EOF (-1) /* end of file */ #define TOK_LINEFEED 10 /* line feed */ /* all identifiers and strings have token above that */ #define TOK_IDENT 256 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x) #define TOK_ASM_int TOK_INT #define DEF_ASMDIR(x) DEF(TOK_ASMDIR_ ## x, "." #x) #define TOK_ASMDIR_FIRST TOK_ASMDIR_byte #define TOK_ASMDIR_LAST TOK_ASMDIR_section #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64 /* only used for i386 asm opcodes definitions */ #define DEF_BWL(x) \ DEF(TOK_ASM_ ## x ## b, #x "b") \ DEF(TOK_ASM_ ## x ## w, #x "w") \ DEF(TOK_ASM_ ## x ## l, #x "l") \ DEF(TOK_ASM_ ## x, #x) #define DEF_WL(x) \ DEF(TOK_ASM_ ## x ## w, #x "w") \ DEF(TOK_ASM_ ## x ## l, #x "l") \ DEF(TOK_ASM_ ## x, #x) #ifdef TCC_TARGET_X86_64 # define DEF_BWLQ(x) \ DEF(TOK_ASM_ ## x ## b, #x "b") \ DEF(TOK_ASM_ ## x ## w, #x "w") \ DEF(TOK_ASM_ ## x ## l, #x "l") \ DEF(TOK_ASM_ ## x ## q, #x "q") \ DEF(TOK_ASM_ ## x, #x) # define DEF_WLQ(x) \ DEF(TOK_ASM_ ## x ## w, #x "w") \ DEF(TOK_ASM_ ## x ## l, #x "l") \ DEF(TOK_ASM_ ## x ## q, #x "q") \ DEF(TOK_ASM_ ## x, #x) # define DEF_BWLX DEF_BWLQ # define DEF_WLX DEF_WLQ /* number of sizes + 1 */ # define NBWLX 5 #else # define DEF_BWLX DEF_BWL # define DEF_WLX DEF_WL /* number of sizes + 1 */ # define NBWLX 4 #endif #define DEF_FP1(x) \ DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \ DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \ DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \ DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s") #define DEF_FP(x) \ DEF(TOK_ASM_ ## f ## x, "f" #x ) \ DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \ DEF_FP1(x) #define DEF_ASMTEST(x,suffix) \ DEF_ASM(x ## o ## suffix) \ DEF_ASM(x ## no ## suffix) \ DEF_ASM(x ## b ## suffix) \ DEF_ASM(x ## c ## suffix) \ DEF_ASM(x ## nae ## suffix) \ DEF_ASM(x ## nb ## suffix) \ DEF_ASM(x ## nc ## suffix) \ DEF_ASM(x ## ae ## suffix) \ DEF_ASM(x ## e ## suffix) \ DEF_ASM(x ## z ## suffix) \ DEF_ASM(x ## ne ## suffix) \ DEF_ASM(x ## nz ## suffix) \ DEF_ASM(x ## be ## suffix) \ DEF_ASM(x ## na ## suffix) \ DEF_ASM(x ## nbe ## suffix) \ DEF_ASM(x ## a ## suffix) \ DEF_ASM(x ## s ## suffix) \ DEF_ASM(x ## ns ## suffix) \ DEF_ASM(x ## p ## suffix) \ DEF_ASM(x ## pe ## suffix) \ DEF_ASM(x ## np ## suffix) \ DEF_ASM(x ## po ## suffix) \ DEF_ASM(x ## l ## suffix) \ DEF_ASM(x ## nge ## suffix) \ DEF_ASM(x ## nl ## suffix) \ DEF_ASM(x ## ge ## suffix) \ DEF_ASM(x ## le ## suffix) \ DEF_ASM(x ## ng ## suffix) \ DEF_ASM(x ## nle ## suffix) \ DEF_ASM(x ## g ## suffix) #endif /* defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64 */ enum tcc_token { TOK_LAST = TOK_IDENT - 1 #define DEF(id, str) ,id #include "tcctok.h" #undef DEF }; /* keywords: tok >= TOK_IDENT && tok < TOK_UIDENT */ #define TOK_UIDENT TOK_DEFINE /* ------------ libtcc.c ------------ */ /* use GNU C extensions */ ST_DATA int gnu_ext; /* use Tiny C extensions */ ST_DATA int tcc_ext; /* XXX: get rid of this ASAP */ ST_DATA struct TCCState *tcc_state; /* public functions currently used by the tcc main function */ ST_FUNC char *pstrcpy(char *buf, int buf_size, const char *s); ST_FUNC char *pstrcat(char *buf, int buf_size, const char *s); ST_FUNC char *pstrncpy(char *out, const char *in, size_t num); PUB_FUNC char *tcc_basename(const char *name); PUB_FUNC char *tcc_fileextension (const char *name); #ifndef MEM_DEBUG PUB_FUNC void tcc_free(void *ptr); PUB_FUNC void *tcc_malloc(unsigned long size); PUB_FUNC void *tcc_mallocz(unsigned long size); PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size); PUB_FUNC char *tcc_strdup(const char *str); #else #define tcc_free(ptr) tcc_free_debug(ptr) #define tcc_malloc(size) tcc_malloc_debug(size, __FILE__, __LINE__) #define tcc_mallocz(size) tcc_mallocz_debug(size, __FILE__, __LINE__) #define tcc_realloc(ptr,size) tcc_realloc_debug(ptr, size, __FILE__, __LINE__) #define tcc_strdup(str) tcc_strdup_debug(str, __FILE__, __LINE__) PUB_FUNC void tcc_free_debug(void *ptr); PUB_FUNC void *tcc_malloc_debug(unsigned long size, const char *file, int line); PUB_FUNC void *tcc_mallocz_debug(unsigned long size, const char *file, int line); PUB_FUNC void *tcc_realloc_debug(void *ptr, unsigned long size, const char *file, int line); PUB_FUNC char *tcc_strdup_debug(const char *str, const char *file, int line); #endif #define free(p) use_tcc_free(p) #define malloc(s) use_tcc_malloc(s) #define realloc(p, s) use_tcc_realloc(p, s) #undef strdup #define strdup(s) use_tcc_strdup(s) PUB_FUNC void tcc_memcheck(void); PUB_FUNC void tcc_error_noabort(const char *fmt, ...); PUB_FUNC NORETURN void tcc_error(const char *fmt, ...); PUB_FUNC void tcc_warning(const char *fmt, ...); /* other utilities */ ST_FUNC void dynarray_add(void *ptab, int *nb_ptr, void *data); ST_FUNC void dynarray_reset(void *pp, int *n); ST_INLN void cstr_ccat(CString *cstr, int ch); ST_FUNC void cstr_cat(CString *cstr, const char *str, int len); ST_FUNC void cstr_wccat(CString *cstr, int ch); ST_FUNC void cstr_new(CString *cstr); ST_FUNC void cstr_free(CString *cstr); ST_FUNC void cstr_reset(CString *cstr); ST_INLN void sym_free(Sym *sym); ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, int c); ST_FUNC Sym *sym_find2(Sym *s, int v); ST_FUNC Sym *sym_push(int v, CType *type, int r, int c); ST_FUNC void sym_pop(Sym **ptop, Sym *b, int keep); ST_INLN Sym *struct_find(int v); ST_INLN Sym *sym_find(int v); ST_FUNC Sym *global_identifier_push(int v, int t, int c); ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen); ST_FUNC int tcc_open(TCCState *s1, const char *filename); ST_FUNC void tcc_close(void); ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags); /* flags: */ #define AFF_PRINT_ERROR 0x10 /* print error if file not found */ #define AFF_REFERENCED_DLL 0x20 /* load a referenced dll from another dll */ #define AFF_TYPE_BIN 0x40 /* file to add is binary */ /* s->filetype: */ #define AFF_TYPE_NONE 0 #define AFF_TYPE_C 1 #define AFF_TYPE_ASM 2 #define AFF_TYPE_ASMPP 3 #define AFF_TYPE_LIB 4 /* values from tcc_object_type(...) */ #define AFF_BINTYPE_REL 1 #define AFF_BINTYPE_DYN 2 #define AFF_BINTYPE_AR 3 #define AFF_BINTYPE_C67 4 ST_FUNC int tcc_add_crt(TCCState *s, const char *filename); ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags); ST_FUNC void tcc_add_pragma_libs(TCCState *s1); PUB_FUNC int tcc_add_library_err(TCCState *s, const char *f); PUB_FUNC void tcc_print_stats(TCCState *s, unsigned total_time); PUB_FUNC int tcc_parse_args(TCCState *s, int *argc, char ***argv, int optind); #ifdef _WIN32 ST_FUNC char *normalize_slashes(char *path); #endif /* tcc_parse_args return codes: */ #define OPT_HELP 1 #define OPT_HELP2 2 #define OPT_V 3 #define OPT_PRINT_DIRS 4 #define OPT_AR 5 #define OPT_IMPDEF 6 #define OPT_M32 32 #define OPT_M64 64 /* ------------ tccpp.c ------------ */ ST_DATA struct BufferedFile *file; ST_DATA int ch, tok; ST_DATA CValue tokc; ST_DATA const int *macro_ptr; ST_DATA int parse_flags; ST_DATA int tok_flags; ST_DATA CString tokcstr; /* current parsed string, if any */ /* display benchmark infos */ ST_DATA int total_lines; ST_DATA int total_bytes; ST_DATA int tok_ident; ST_DATA TokenSym **table_ident; #define TOK_FLAG_BOL 0x0001 /* beginning of line before */ #define TOK_FLAG_BOF 0x0002 /* beginning of file before */ #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */ #define TOK_FLAG_EOF 0x0008 /* end of file */ #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */ #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */ #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a token. line feed is also returned at eof */ #define PARSE_FLAG_ASM_FILE 0x0008 /* we processing an asm file: '#' can be used for line comment, etc. */ #define PARSE_FLAG_SPACES 0x0010 /* next() returns space tokens (for -E) */ #define PARSE_FLAG_ACCEPT_STRAYS 0x0020 /* next() returns '\\' token */ #define PARSE_FLAG_TOK_STR 0x0040 /* return parsed strings instead of TOK_PPSTR */ /* isidnum_table flags: */ #define IS_SPC 1 #define IS_ID 2 #define IS_NUM 4 ST_FUNC TokenSym *tok_alloc(const char *str, int len); ST_FUNC const char *get_tok_str(int v, CValue *cv); ST_FUNC void begin_macro(TokenString *str, int alloc); ST_FUNC void end_macro(void); ST_FUNC int set_idnum(int c, int val); ST_INLN void tok_str_new(TokenString *s); ST_FUNC TokenString *tok_str_alloc(void); ST_FUNC void tok_str_free(TokenString *s); ST_FUNC void tok_str_free_str(int *str); ST_FUNC void tok_str_add(TokenString *s, int t); ST_FUNC void tok_str_add_tok(TokenString *s); ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg); ST_FUNC void define_undef(Sym *s); ST_INLN Sym *define_find(int v); ST_FUNC void free_defines(Sym *b); ST_FUNC Sym *label_find(int v); ST_FUNC Sym *label_push(Sym **ptop, int v, int flags); ST_FUNC void label_pop(Sym **ptop, Sym *slast, int keep); ST_FUNC void parse_define(void); ST_FUNC void preprocess(int is_bof); ST_FUNC void next_nomacro(void); ST_FUNC void next(void); ST_INLN void unget_tok(int last_tok); ST_FUNC void preprocess_start(TCCState *s1, int is_asm); ST_FUNC void preprocess_end(TCCState *s1); ST_FUNC void tccpp_new(TCCState *s); ST_FUNC void tccpp_delete(TCCState *s); ST_FUNC int tcc_preprocess(TCCState *s1); ST_FUNC void skip(int c); ST_FUNC NORETURN void expect(const char *msg); /* space excluding newline */ static inline int is_space(int ch) { return ch == ' ' || ch == '\t' || ch == '\v' || ch == '\f' || ch == '\r'; } static inline int isid(int c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'; } static inline int isnum(int c) { return c >= '0' && c <= '9'; } static inline int isoct(int c) { return c >= '0' && c <= '7'; } static inline int toup(int c) { return (c >= 'a' && c <= 'z') ? c - 'a' + 'A' : c; } /* ------------ tccgen.c ------------ */ #define SYM_POOL_NB (8192 / sizeof(Sym)) ST_DATA Sym *sym_free_first; ST_DATA void **sym_pools; ST_DATA int nb_sym_pools; ST_DATA Sym *global_stack; ST_DATA Sym *local_stack; ST_DATA Sym *local_label_stack; ST_DATA Sym *global_label_stack; ST_DATA Sym *define_stack; ST_DATA CType char_pointer_type, func_old_type, int_type, size_type; ST_DATA SValue __vstack[1+/*to make bcheck happy*/ VSTACK_SIZE], *vtop, *pvtop; #define vstack (__vstack + 1) ST_DATA int rsym, anon_sym, ind, loc; ST_DATA int const_wanted; /* true if constant wanted */ ST_DATA int nocode_wanted; /* true if no code generation wanted for an expression */ ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */ ST_DATA CType func_vt; /* current function return type (used by return instruction) */ ST_DATA int func_var; /* true if current function is variadic */ ST_DATA int func_vc; ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */ ST_DATA const char *funcname; ST_DATA int g_debug; ST_FUNC void tcc_debug_start(TCCState *s1); ST_FUNC void tcc_debug_end(TCCState *s1); ST_FUNC void tcc_debug_funcstart(TCCState *s1, Sym *sym); ST_FUNC void tcc_debug_funcend(TCCState *s1, int size); ST_FUNC void tcc_debug_line(TCCState *s1); ST_FUNC int tccgen_compile(TCCState *s1); ST_FUNC void free_inline_functions(TCCState *s); ST_FUNC void check_vstack(void); ST_INLN int is_float(int t); ST_FUNC int ieee_finite(double d); ST_FUNC void test_lvalue(void); ST_FUNC void vpushi(int v); ST_FUNC Sym *external_global_sym(int v, CType *type, int r); ST_FUNC void vset(CType *type, int r, int v); ST_FUNC void vswap(void); ST_FUNC void vpush_global_sym(CType *type, int v); ST_FUNC void vrote(SValue *e, int n); ST_FUNC void vrott(int n); ST_FUNC void vrotb(int n); #ifdef TCC_TARGET_ARM ST_FUNC int get_reg_ex(int rc, int rc2); ST_FUNC void lexpand_nr(void); #endif ST_FUNC void vpushv(SValue *v); ST_FUNC void save_reg(int r); ST_FUNC void save_reg_upstack(int r, int n); ST_FUNC int get_reg(int rc); ST_FUNC void save_regs(int n); ST_FUNC void gaddrof(void); ST_FUNC int gv(int rc); ST_FUNC void gv2(int rc1, int rc2); ST_FUNC void vpop(void); ST_FUNC void gen_op(int op); ST_FUNC int type_size(CType *type, int *a); ST_FUNC void mk_pointer(CType *type); ST_FUNC void vstore(void); ST_FUNC void inc(int post, int c); ST_FUNC void parse_mult_str (CString *astr, const char *msg); ST_FUNC void parse_asm_str(CString *astr); ST_FUNC int lvalue_type(int t); ST_FUNC void indir(void); ST_FUNC void unary(void); ST_FUNC void expr_prod(void); ST_FUNC void expr_sum(void); ST_FUNC void gexpr(void); ST_FUNC int expr_const(void); #if defined CONFIG_TCC_BCHECK || defined TCC_TARGET_C67 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size); #endif #if defined TCC_TARGET_X86_64 && !defined TCC_TARGET_PE ST_FUNC int classify_x86_64_va_arg(CType *ty); #endif /* ------------ tccelf.c ------------ */ #define TCC_OUTPUT_FORMAT_ELF 0 /* default output format: ELF */ #define TCC_OUTPUT_FORMAT_BINARY 1 /* binary image output */ #define TCC_OUTPUT_FORMAT_COFF 2 /* COFF */ #define ARMAG "!<arch>\012" /* For COFF and a.out archives */ typedef struct { unsigned int n_strx; /* index into string table of name */ unsigned char n_type; /* type of symbol */ unsigned char n_other; /* misc info (usually empty) */ unsigned short n_desc; /* description field */ unsigned int n_value; /* value of symbol */ } Stab_Sym; ST_DATA Section *text_section, *data_section, *bss_section; /* predefined sections */ ST_DATA Section *common_section; ST_DATA Section *cur_text_section; /* current section where function code is generated */ #ifdef CONFIG_TCC_ASM ST_DATA Section *last_text_section; /* to handle .previous asm directive */ #endif #ifdef CONFIG_TCC_BCHECK /* bound check related sections */ ST_DATA Section *bounds_section; /* contains global data bound description */ ST_DATA Section *lbounds_section; /* contains local data bound description */ ST_FUNC void tccelf_bounds_new(TCCState *s); #endif /* symbol sections */ ST_DATA Section *symtab_section, *strtab_section; /* debug sections */ ST_DATA Section *stab_section, *stabstr_section; ST_FUNC void tccelf_new(TCCState *s); ST_FUNC void tccelf_delete(TCCState *s); ST_FUNC void tccelf_stab_new(TCCState *s); ST_FUNC Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags); ST_FUNC void section_realloc(Section *sec, unsigned long new_size); ST_FUNC size_t section_add(Section *sec, addr_t size, int align); ST_FUNC void *section_ptr_add(Section *sec, addr_t size); ST_FUNC void section_reserve(Section *sec, unsigned long size); ST_FUNC Section *find_section(TCCState *s1, const char *name); ST_FUNC Section *new_symtab(TCCState *s1, const char *symtab_name, int sh_type, int sh_flags, const char *strtab_name, const char *hash_name, int hash_sh_flags); ST_FUNC void put_extern_sym2(Sym *sym, Section *section, addr_t value, unsigned long size, int can_add_underscore); ST_FUNC void put_extern_sym(Sym *sym, Section *section, addr_t value, unsigned long size); #if PTR_SIZE == 4 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type); #endif ST_FUNC void greloca(Section *s, Sym *sym, unsigned long offset, int type, addr_t addend); ST_FUNC int put_elf_str(Section *s, const char *sym); ST_FUNC int put_elf_sym(Section *s, addr_t value, unsigned long size, int info, int other, int shndx, const char *name); ST_FUNC int set_elf_sym(Section *s, addr_t value, unsigned long size, int info, int other, int shndx, const char *name); ST_FUNC int find_elf_sym(Section *s, const char *name); ST_FUNC void put_elf_reloc(Section *symtab, Section *s, unsigned long offset, int type, int symbol); ST_FUNC void put_elf_reloca(Section *symtab, Section *s, unsigned long offset, int type, int symbol, addr_t addend); ST_FUNC void put_stabs(const char *str, int type, int other, int desc, unsigned long value); ST_FUNC void put_stabs_r(const char *str, int type, int other, int desc, unsigned long value, Section *sec, int sym_index); ST_FUNC void put_stabn(int type, int other, int desc, int value); ST_FUNC void put_stabd(int type, int other, int desc); ST_FUNC void relocate_common_syms(void); ST_FUNC void relocate_syms(TCCState *s1, Section *symtab, int do_resolve); ST_FUNC void relocate_section(TCCState *s1, Section *s); ST_FUNC void tcc_add_linker_symbols(TCCState *s1); ST_FUNC int tcc_object_type(int fd, ElfW(Ehdr) *h); ST_FUNC int tcc_load_object_file(TCCState *s1, int fd, unsigned long file_offset); ST_FUNC int tcc_load_archive(TCCState *s1, int fd); ST_FUNC void tcc_add_bcheck(TCCState *s1); ST_FUNC void tcc_add_runtime(TCCState *s1); ST_FUNC void build_got_entries(TCCState *s1); ST_FUNC struct sym_attr *get_sym_attr(TCCState *s1, int index, int alloc); ST_FUNC void squeeze_multi_relocs(Section *sec, size_t oldrelocoffset); ST_FUNC addr_t get_elf_sym_addr(TCCState *s, const char *name, int err); #if defined TCC_IS_NATIVE || defined TCC_TARGET_PE ST_FUNC void *tcc_get_symbol_err(TCCState *s, const char *name); #endif #ifndef TCC_TARGET_PE ST_FUNC int tcc_load_dll(TCCState *s1, int fd, const char *filename, int level); ST_FUNC int tcc_load_ldscript(TCCState *s1); ST_FUNC uint8_t *parse_comment(uint8_t *p); ST_FUNC void minp(void); ST_INLN void inp(void); ST_FUNC int handle_eob(void); #endif /* ------------ xxx-link.c ------------ */ /* Whether to generate a GOT/PLT entry and when. NO_GOTPLT_ENTRY is first so that unknown relocation don't create a GOT or PLT entry */ enum gotplt_entry { NO_GOTPLT_ENTRY, /* never generate (eg. GLOB_DAT & JMP_SLOT relocs) */ BUILD_GOT_ONLY, /* only build GOT (eg. TPOFF relocs) */ AUTO_GOTPLT_ENTRY, /* generate if sym is UNDEF */ ALWAYS_GOTPLT_ENTRY /* always generate (eg. PLTOFF relocs) */ }; ST_FUNC int code_reloc (int reloc_type); ST_FUNC int gotplt_entry_type (int reloc_type); ST_FUNC unsigned create_plt_entry(TCCState *s1, unsigned got_offset, struct sym_attr *attr); ST_FUNC void relocate_init(Section *sr); ST_FUNC void relocate(TCCState *s1, ElfW_Rel *rel, int type, unsigned char *ptr, addr_t addr, addr_t val); ST_FUNC void relocate_plt(TCCState *s1); /* ------------ xxx-gen.c ------------ */ ST_DATA const int reg_classes[NB_REGS]; ST_FUNC void gsym_addr(int t, int a); ST_FUNC void gsym(int t); ST_FUNC void load(int r, SValue *sv); ST_FUNC void store(int r, SValue *v); ST_FUNC int gfunc_sret(CType *vt, int variadic, CType *ret, int *align, int *regsize); ST_FUNC void gfunc_call(int nb_args); ST_FUNC void gfunc_prolog(CType *func_type); ST_FUNC void gfunc_epilog(void); ST_FUNC int gjmp(int t); ST_FUNC void gjmp_addr(int a); ST_FUNC int gtst(int inv, int t); #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64 ST_FUNC void gtst_addr(int inv, int a); #else #define gtst_addr(inv, a) gsym_addr(gtst(inv, 0), a) #endif ST_FUNC void gen_opi(int op); ST_FUNC void gen_opf(int op); ST_FUNC void gen_cvt_ftoi(int t); ST_FUNC void gen_cvt_ftof(int t); ST_FUNC void ggoto(void); #ifndef TCC_TARGET_C67 ST_FUNC void o(unsigned int c); #endif #ifndef TCC_TARGET_ARM ST_FUNC void gen_cvt_itof(int t); #endif ST_FUNC void gen_vla_sp_save(int addr); ST_FUNC void gen_vla_sp_restore(int addr); ST_FUNC void gen_vla_alloc(CType *type, int align); static inline uint16_t read16le(unsigned char *p) { return p[0] | (uint16_t)p[1] << 8; } static inline void write16le(unsigned char *p, uint16_t x) { p[0] = x & 255; p[1] = x >> 8 & 255; } static inline uint32_t read32le(unsigned char *p) { return read16le(p) | (uint32_t)read16le(p + 2) << 16; } static inline void write32le(unsigned char *p, uint32_t x) { write16le(p, x); write16le(p + 2, x >> 16); } static inline void add32le(unsigned char *p, int32_t x) { write32le(p, read32le(p) + x); } static inline uint64_t read64le(unsigned char *p) { return read32le(p) | (uint64_t)read32le(p + 4) << 32; } static inline void write64le(unsigned char *p, uint64_t x) { write32le(p, x); write32le(p + 4, x >> 32); } static inline void add64le(unsigned char *p, int64_t x) { write64le(p, read64le(p) + x); } /* ------------ i386-gen.c ------------ */ #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64 ST_FUNC void g(int c); ST_FUNC void gen_le16(int c); ST_FUNC void gen_le32(int c); ST_FUNC void gen_addr32(int r, Sym *sym, int c); ST_FUNC void gen_addrpc32(int r, Sym *sym, int c); #endif #ifdef CONFIG_TCC_BCHECK ST_FUNC void gen_bounded_ptr_add(void); ST_FUNC void gen_bounded_ptr_deref(void); #endif /* ------------ x86_64-gen.c ------------ */ #ifdef TCC_TARGET_X86_64 ST_FUNC void gen_addr64(int r, Sym *sym, int64_t c); ST_FUNC void gen_opl(int op); #endif /* ------------ arm-gen.c ------------ */ #ifdef TCC_TARGET_ARM #if defined(TCC_ARM_EABI) && !defined(CONFIG_TCC_ELFINTERP) PUB_FUNC const char *default_elfinterp(struct TCCState *s); #endif ST_FUNC void arm_init(struct TCCState *s); ST_FUNC void gen_cvt_itof1(int t); #endif /* ------------ arm64-gen.c ------------ */ #ifdef TCC_TARGET_ARM64 ST_FUNC void gen_cvt_sxtw(void); ST_FUNC void gen_opl(int op); ST_FUNC void gfunc_return(CType *func_type); ST_FUNC void gen_va_start(void); ST_FUNC void gen_va_arg(CType *t); ST_FUNC void gen_clear_cache(void); #endif /* ------------ c67-gen.c ------------ */ #ifdef TCC_TARGET_C67 #endif /* ------------ tcccoff.c ------------ */ #ifdef TCC_TARGET_COFF ST_FUNC int tcc_output_coff(TCCState *s1, FILE *f); ST_FUNC int tcc_load_coff(TCCState * s1, int fd); #endif /* ------------ tccasm.c ------------ */ ST_FUNC void asm_instr(void); ST_FUNC void asm_global_instr(void); #ifdef CONFIG_TCC_ASM ST_FUNC int find_constraint(ASMOperand *operands, int nb_operands, const char *name, const char **pp); ST_FUNC Sym* get_asm_sym(int name, Sym *csym); ST_FUNC void asm_expr(TCCState *s1, ExprValue *pe); ST_FUNC int asm_int_expr(TCCState *s1); ST_FUNC int tcc_assemble(TCCState *s1, int do_preprocess); /* ------------ i386-asm.c ------------ */ ST_FUNC void gen_expr32(ExprValue *pe); #ifdef TCC_TARGET_X86_64 ST_FUNC void gen_expr64(ExprValue *pe); #endif ST_FUNC void asm_opcode(TCCState *s1, int opcode); ST_FUNC int asm_parse_regvar(int t); ST_FUNC void asm_compute_constraints(ASMOperand *operands, int nb_operands, int nb_outputs, const uint8_t *clobber_regs, int *pout_reg); ST_FUNC void subst_asm_operand(CString *add_str, SValue *sv, int modifier); ST_FUNC void asm_gen_code(ASMOperand *operands, int nb_operands, int nb_outputs, int is_output, uint8_t *clobber_regs, int out_reg); ST_FUNC void asm_clobber(uint8_t *clobber_regs, const char *str); #endif /* ------------ tccpe.c -------------- */ #ifdef TCC_TARGET_PE ST_FUNC int pe_load_file(struct TCCState *s1, const char *filename, int fd); ST_FUNC int pe_output_file(TCCState * s1, const char *filename); ST_FUNC int pe_putimport(TCCState *s1, int dllindex, const char *name, addr_t value); #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64 ST_FUNC SValue *pe_getimport(SValue *sv, SValue *v2); #endif #ifdef TCC_TARGET_X86_64 ST_FUNC void pe_add_unwind_data(unsigned start, unsigned end, unsigned stack); #endif PUB_FUNC int tcc_get_dllexports(const char *filename, char **pp); /* symbol properties stored in Elf32_Sym->st_other */ # define ST_PE_EXPORT 0x10 # define ST_PE_IMPORT 0x20 # define ST_PE_STDCALL 0x40 #endif /* ------------ tccrun.c ----------------- */ #ifdef TCC_IS_NATIVE #ifdef CONFIG_TCC_STATIC #define RTLD_LAZY 0x001 #define RTLD_NOW 0x002 #define RTLD_GLOBAL 0x100 #define RTLD_DEFAULT NULL /* dummy function for profiling */ ST_FUNC void *dlopen(const char *filename, int flag); ST_FUNC void dlclose(void *p); ST_FUNC const char *dlerror(void); ST_FUNC void *dlsym(void *handle, const char *symbol); #endif #ifdef CONFIG_TCC_BACKTRACE ST_DATA int rt_num_callers; ST_DATA const char **rt_bound_error_msg; ST_DATA void *rt_prog_main; ST_FUNC void tcc_set_num_callers(int n); #endif ST_FUNC void tcc_run_free(TCCState *s1); #endif /* ------------ tcctools.c ----------------- */ #if 0 /* included in tcc.c */ ST_FUNC int tcc_tool_ar(TCCState *s, int argc, char **argv); #ifdef TCC_TARGET_PE ST_FUNC int tcc_tool_impdef(TCCState *s, int argc, char **argv); #endif ST_FUNC void tcc_tool_cross(TCCState *s, char **argv, int option); ST_FUNC void gen_makedeps(TCCState *s, const char *target, const char *filename); #endif /********************************************************/ #undef ST_DATA #if ONE_SOURCE #define ST_DATA static #else #define ST_DATA #endif /********************************************************/ #endif /* _TCC_H */
russpowers/Nim
tinyc/tcc.h
C
mit
56,025
let util = require('../../util'); let Hammer = require('../../module/hammer'); let hammerUtil = require('../../hammerUtil'); /** * clears the toolbar div element of children * * @private */ class ManipulationSystem { constructor(body, canvas, selectionHandler) { this.body = body; this.canvas = canvas; this.selectionHandler = selectionHandler; this.editMode = false; this.manipulationDiv = undefined; this.editModeDiv = undefined; this.closeDiv = undefined; this.manipulationHammers = []; this.temporaryUIFunctions = {}; this.temporaryEventFunctions = []; this.touchTime = 0; this.temporaryIds = {nodes: [], edges:[]}; this.guiEnabled = false; this.inMode = false; this.selectedControlNode = undefined; this.options = {}; this.defaultOptions = { enabled: false, initiallyActive: false, addNode: true, addEdge: true, editNode: undefined, editEdge: true, deleteNode: true, deleteEdge: true, controlNodeStyle:{ shape:'dot', size:6, color: {background: '#ff0000', border: '#3c3c3c', highlight: {background: '#07f968', border: '#3c3c3c'}}, borderWidth: 2, borderWidthSelected: 2 } }; util.extend(this.options, this.defaultOptions); this.body.emitter.on('destroy', () => {this._clean();}); this.body.emitter.on('_dataChanged',this._restore.bind(this)); this.body.emitter.on('_resetData', this._restore.bind(this)); } /** * If something changes in the data during editing, switch back to the initial datamanipulation state and close all edit modes. * @private */ _restore() { if (this.inMode !== false) { if (this.options.initiallyActive === true) { this.enableEditMode(); } else { this.disableEditMode(); } } } /** * Set the Options * @param options */ setOptions(options, allOptions, globalOptions) { if (allOptions !== undefined) { if (allOptions.locale !== undefined) {this.options.locale = allOptions.locale} else {this.options.locale = globalOptions.locale;} if (allOptions.locales !== undefined) {this.options.locales = allOptions.locales} else {this.options.locales = globalOptions.locales;} } if (options !== undefined) { if (typeof options === 'boolean') { this.options.enabled = options; } else { this.options.enabled = true; util.deepExtend(this.options, options); } if (this.options.initiallyActive === true) { this.editMode = true; } this._setup(); } } /** * Enable or disable edit-mode. Draws the DOM required and cleans up after itself. * * @private */ toggleEditMode() { if (this.editMode === true) { this.disableEditMode(); } else { this.enableEditMode(); } } enableEditMode() { this.editMode = true; this._clean(); if (this.guiEnabled === true) { this.manipulationDiv.style.display = 'block'; this.closeDiv.style.display = 'block'; this.editModeDiv.style.display = 'none'; this.showManipulatorToolbar(); } } disableEditMode() { this.editMode = false; this._clean(); if (this.guiEnabled === true) { this.manipulationDiv.style.display = 'none'; this.closeDiv.style.display = 'none'; this.editModeDiv.style.display = 'block'; this._createEditButton(); } } /** * Creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar. * * @private */ showManipulatorToolbar() { // restore the state of any bound functions or events, remove control nodes, restore physics this._clean(); // reset global variables this.manipulationDOM = {}; // if the gui is enabled, draw all elements. if (this.guiEnabled === true) { // a _restore will hide these menus this.editMode = true; this.manipulationDiv.style.display = 'block'; this.closeDiv.style.display = 'block'; let selectedNodeCount = this.selectionHandler._getSelectedNodeCount(); let selectedEdgeCount = this.selectionHandler._getSelectedEdgeCount(); let selectedTotalCount = selectedNodeCount + selectedEdgeCount; let locale = this.options.locales[this.options.locale]; let needSeperator = false; if (this.options.addNode !== false) { this._createAddNodeButton(locale); needSeperator = true; } if (this.options.addEdge !== false) { if (needSeperator === true) { this._createSeperator(1); } else { needSeperator = true; } this._createAddEdgeButton(locale); } if (selectedNodeCount === 1 && typeof this.options.editNode === 'function') { if (needSeperator === true) { this._createSeperator(2); } else { needSeperator = true; } this._createEditNodeButton(locale); } else if (selectedEdgeCount === 1 && selectedNodeCount === 0 && this.options.editEdge !== false) { if (needSeperator === true) { this._createSeperator(3); } else { needSeperator = true; } this._createEditEdgeButton(locale); } // remove buttons if (selectedTotalCount !== 0) { if (selectedNodeCount > 0 && this.options.deleteNode !== false) { if (needSeperator === true) { this._createSeperator(4); } this._createDeleteButton(locale); } else if (selectedNodeCount === 0 && this.options.deleteEdge !== false) { if (needSeperator === true) { this._createSeperator(4); } this._createDeleteButton(locale); } } // bind the close button this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); // refresh this bar based on what has been selected this._temporaryBindEvent('select', this.showManipulatorToolbar.bind(this)); } // redraw to show any possible changes this.body.emitter.emit('_redraw'); } /** * Create the toolbar for adding Nodes */ addNodeMode() { // when using the gui, enable edit mode if it wasnt already. if (this.editMode !== true) { this.enableEditMode(); } // restore the state of any bound functions or events, remove control nodes, restore physics this._clean(); this.inMode = 'addNode'; if (this.guiEnabled === true) { let locale = this.options.locales[this.options.locale]; this.manipulationDOM = {}; this._createBackButton(locale); this._createSeperator(); this._createDescription(locale['addDescription'] || this.options.locales['en']['addDescription']); // bind the close button this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); } this._temporaryBindEvent('click', this._performAddNode.bind(this)); } /** * call the bound function to handle the editing of the node. The node has to be selected. */ editNode() { // when using the gui, enable edit mode if it wasnt already. if (this.editMode !== true) { this.enableEditMode(); } // restore the state of any bound functions or events, remove control nodes, restore physics this._clean(); let node = this.selectionHandler._getSelectedNode(); if (node !== undefined) { this.inMode = 'editNode'; if (typeof this.options.editNode === 'function') { if (node.isCluster !== true) { let data = util.deepExtend({}, node.options, false); data.x = node.x; data.y = node.y; if (this.options.editNode.length === 2) { this.options.editNode(data, (finalizedData) => { if (finalizedData !== null && finalizedData !== undefined && this.inMode === 'editNode') { // if for whatever reason the mode has changes (due to dataset change) disregard the callback) { this.body.data.nodes.getDataSet().update(finalizedData); } this.showManipulatorToolbar(); }); } else { throw new Error('The function for edit does not support two arguments (data, callback)'); } } else { alert(this.options.locales[this.options.locale]['editClusterError'] || this.options.locales['en']['editClusterError']); } } else { throw new Error('No function has been configured to handle the editing of nodes.'); } } else { this.showManipulatorToolbar(); } } /** * create the toolbar to connect nodes */ addEdgeMode() { // when using the gui, enable edit mode if it wasnt already. if (this.editMode !== true) { this.enableEditMode(); } // restore the state of any bound functions or events, remove control nodes, restore physics this._clean(); this.inMode = 'addEdge'; if (this.guiEnabled === true) { let locale = this.options.locales[this.options.locale]; this.manipulationDOM = {}; this._createBackButton(locale); this._createSeperator(); this._createDescription(locale['edgeDescription'] || this.options.locales['en']['edgeDescription']); // bind the close button this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); } // temporarily overload functions this._temporaryBindUI('onTouch', this._handleConnect.bind(this)); this._temporaryBindUI('onDragEnd', this._finishConnect.bind(this)); this._temporaryBindUI('onDrag', this._dragControlNode.bind(this)); this._temporaryBindUI('onRelease', this._finishConnect.bind(this)); this._temporaryBindUI('onDragStart', () => {}); this._temporaryBindUI('onHold', () => {}); } /** * create the toolbar to edit edges */ editEdgeMode() { // when using the gui, enable edit mode if it wasn't already. if (this.editMode !== true) { this.enableEditMode(); } // restore the state of any bound functions or events, remove control nodes, restore physics this._clean(); this.inMode = 'editEdge'; if (typeof this.options.editEdge === 'object' && typeof this.options.editEdge.editWithoutDrag === "function") { this.edgeBeingEditedId = this.selectionHandler.getSelectedEdges()[0]; if (this.edgeBeingEditedId !== undefined) { var edge = this.body.edges[this.edgeBeingEditedId]; this._performEditEdge(edge.from, edge.to); return; } } if (this.guiEnabled === true) { let locale = this.options.locales[this.options.locale]; this.manipulationDOM = {}; this._createBackButton(locale); this._createSeperator(); this._createDescription(locale['editEdgeDescription'] || this.options.locales['en']['editEdgeDescription']); // bind the close button this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); } this.edgeBeingEditedId = this.selectionHandler.getSelectedEdges()[0]; if (this.edgeBeingEditedId !== undefined) { let edge = this.body.edges[this.edgeBeingEditedId]; // create control nodes let controlNodeFrom = this._getNewTargetNode(edge.from.x, edge.from.y); let controlNodeTo = this._getNewTargetNode(edge.to.x, edge.to.y); this.temporaryIds.nodes.push(controlNodeFrom.id); this.temporaryIds.nodes.push(controlNodeTo.id); this.body.nodes[controlNodeFrom.id] = controlNodeFrom; this.body.nodeIndices.push(controlNodeFrom.id); this.body.nodes[controlNodeTo.id] = controlNodeTo; this.body.nodeIndices.push(controlNodeTo.id); // temporarily overload UI functions, cleaned up automatically because of _temporaryBindUI this._temporaryBindUI('onTouch', this._controlNodeTouch.bind(this)); // used to get the position this._temporaryBindUI('onTap', () => {}); // disabled this._temporaryBindUI('onHold', () => {}); // disabled this._temporaryBindUI('onDragStart', this._controlNodeDragStart.bind(this));// used to select control node this._temporaryBindUI('onDrag', this._controlNodeDrag.bind(this)); // used to drag control node this._temporaryBindUI('onDragEnd', this._controlNodeDragEnd.bind(this)); // used to connect or revert control nodes this._temporaryBindUI('onMouseMove', () => {}); // disabled // create function to position control nodes correctly on movement // automatically cleaned up because we use the temporary bind this._temporaryBindEvent('beforeDrawing', (ctx) => { let positions = edge.edgeType.findBorderPositions(ctx); if (controlNodeFrom.selected === false) { controlNodeFrom.x = positions.from.x; controlNodeFrom.y = positions.from.y; } if (controlNodeTo.selected === false) { controlNodeTo.x = positions.to.x; controlNodeTo.y = positions.to.y; } }); this.body.emitter.emit('_redraw'); } else { this.showManipulatorToolbar(); } } /** * delete everything in the selection */ deleteSelected() { // when using the gui, enable edit mode if it wasnt already. if (this.editMode !== true) { this.enableEditMode(); } // restore the state of any bound functions or events, remove control nodes, restore physics this._clean(); this.inMode = 'delete'; let selectedNodes = this.selectionHandler.getSelectedNodes(); let selectedEdges = this.selectionHandler.getSelectedEdges(); let deleteFunction = undefined; if (selectedNodes.length > 0) { for (let i = 0; i < selectedNodes.length; i++) { if (this.body.nodes[selectedNodes[i]].isCluster === true) { alert(this.options.locales[this.options.locale]['deleteClusterError'] || this.options.locales['en']['deleteClusterError']); return; } } if (typeof this.options.deleteNode === 'function') { deleteFunction = this.options.deleteNode; } } else if (selectedEdges.length > 0) { if (typeof this.options.deleteEdge === 'function') { deleteFunction = this.options.deleteEdge; } } if (typeof deleteFunction === 'function') { let data = {nodes: selectedNodes, edges: selectedEdges}; if (deleteFunction.length === 2) { deleteFunction(data, (finalizedData) => { if (finalizedData !== null && finalizedData !== undefined && this.inMode === 'delete') { // if for whatever reason the mode has changes (due to dataset change) disregard the callback) { this.body.data.edges.getDataSet().remove(finalizedData.edges); this.body.data.nodes.getDataSet().remove(finalizedData.nodes); this.body.emitter.emit('startSimulation'); this.showManipulatorToolbar(); } else { this.body.emitter.emit('startSimulation'); this.showManipulatorToolbar(); } }); } else { throw new Error('The function for delete does not support two arguments (data, callback)') } } else { this.body.data.edges.getDataSet().remove(selectedEdges); this.body.data.nodes.getDataSet().remove(selectedNodes); this.body.emitter.emit('startSimulation'); this.showManipulatorToolbar(); } } //********************************************** PRIVATE ***************************************// /** * draw or remove the DOM * @private */ _setup() { if (this.options.enabled === true) { // Enable the GUI this.guiEnabled = true; this._createWrappers(); if (this.editMode === false) { this._createEditButton(); } else { this.showManipulatorToolbar(); } } else { this._removeManipulationDOM(); // disable the gui this.guiEnabled = false; } } /** * create the div overlays that contain the DOM * @private */ _createWrappers() { // load the manipulator HTML elements. All styling done in css. if (this.manipulationDiv === undefined) { this.manipulationDiv = document.createElement('div'); this.manipulationDiv.className = 'vis-manipulation'; if (this.editMode === true) { this.manipulationDiv.style.display = 'block'; } else { this.manipulationDiv.style.display = 'none'; } this.canvas.frame.appendChild(this.manipulationDiv); } // container for the edit button. if (this.editModeDiv === undefined) { this.editModeDiv = document.createElement('div'); this.editModeDiv.className = 'vis-edit-mode'; if (this.editMode === true) { this.editModeDiv.style.display = 'none'; } else { this.editModeDiv.style.display = 'block'; } this.canvas.frame.appendChild(this.editModeDiv); } // container for the close div button if (this.closeDiv === undefined) { this.closeDiv = document.createElement('div'); this.closeDiv.className = 'vis-close'; this.closeDiv.style.display = this.manipulationDiv.style.display; this.canvas.frame.appendChild(this.closeDiv); } } /** * generate a new target node. Used for creating new edges and editing edges * @param x * @param y * @returns {*} * @private */ _getNewTargetNode(x,y) { let controlNodeStyle = util.deepExtend({}, this.options.controlNodeStyle); controlNodeStyle.id = 'targetNode' + util.randomUUID(); controlNodeStyle.hidden = false; controlNodeStyle.physics = false; controlNodeStyle.x = x; controlNodeStyle.y = y; // we have to define the bounding box in order for the nodes to be drawn immediately let node = this.body.functions.createNode(controlNodeStyle); node.shape.boundingBox = {left: x, right:x, top:y, bottom:y}; return node; } /** * Create the edit button */ _createEditButton() { // restore everything to it's original state (if applicable) this._clean(); // reset the manipulationDOM this.manipulationDOM = {}; // empty the editModeDiv util.recursiveDOMDelete(this.editModeDiv); // create the contents for the editMode button let locale = this.options.locales[this.options.locale]; let button = this._createButton('editMode', 'vis-button vis-edit vis-edit-mode', locale['edit'] || this.options.locales['en']['edit']); this.editModeDiv.appendChild(button); // bind a hammer listener to the button, calling the function toggleEditMode. this._bindHammerToDiv(button, this.toggleEditMode.bind(this)); } /** * this function cleans up after everything this module does. Temporary elements, functions and events are removed, physics restored, hammers removed. * @private */ _clean() { // not in mode this.inMode = false; // _clean the divs if (this.guiEnabled === true) { util.recursiveDOMDelete(this.editModeDiv); util.recursiveDOMDelete(this.manipulationDiv); // removes all the bindings and overloads this._cleanManipulatorHammers(); } // remove temporary nodes and edges this._cleanupTemporaryNodesAndEdges(); // restore overloaded UI functions this._unbindTemporaryUIs(); // remove the temporaryEventFunctions this._unbindTemporaryEvents(); // restore the physics if required this.body.emitter.emit('restorePhysics'); } /** * Each dom element has it's own hammer. They are stored in this.manipulationHammers. This cleans them up. * @private */ _cleanManipulatorHammers() { // _clean hammer bindings if (this.manipulationHammers.length != 0) { for (let i = 0; i < this.manipulationHammers.length; i++) { this.manipulationHammers[i].destroy(); } this.manipulationHammers = []; } } /** * Remove all DOM elements created by this module. * @private */ _removeManipulationDOM() { // removes all the bindings and overloads this._clean(); // empty the manipulation divs util.recursiveDOMDelete(this.manipulationDiv); util.recursiveDOMDelete(this.editModeDiv); util.recursiveDOMDelete(this.closeDiv); // remove the manipulation divs if (this.manipulationDiv) {this.canvas.frame.removeChild(this.manipulationDiv);} if (this.editModeDiv) {this.canvas.frame.removeChild(this.editModeDiv);} if (this.closeDiv) {this.canvas.frame.removeChild(this.closeDiv);} // set the references to undefined this.manipulationDiv = undefined; this.editModeDiv = undefined; this.closeDiv = undefined; } /** * create a seperator line. the index is to differentiate in the manipulation dom * @param index * @private */ _createSeperator(index = 1) { this.manipulationDOM['seperatorLineDiv' + index] = document.createElement('div'); this.manipulationDOM['seperatorLineDiv' + index].className = 'vis-separator-line'; this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv' + index]); } // ---------------------- DOM functions for buttons --------------------------// _createAddNodeButton(locale) { let button = this._createButton('addNode', 'vis-button vis-add', locale['addNode'] || this.options.locales['en']['addNode']); this.manipulationDiv.appendChild(button); this._bindHammerToDiv(button, this.addNodeMode.bind(this)); } _createAddEdgeButton(locale) { let button = this._createButton('addEdge', 'vis-button vis-connect', locale['addEdge'] || this.options.locales['en']['addEdge']); this.manipulationDiv.appendChild(button); this._bindHammerToDiv(button, this.addEdgeMode.bind(this)); } _createEditNodeButton(locale) { let button = this._createButton('editNode', 'vis-button vis-edit', locale['editNode'] || this.options.locales['en']['editNode']); this.manipulationDiv.appendChild(button); this._bindHammerToDiv(button, this.editNode.bind(this)); } _createEditEdgeButton(locale) { let button = this._createButton('editEdge', 'vis-button vis-edit', locale['editEdge'] || this.options.locales['en']['editEdge']); this.manipulationDiv.appendChild(button); this._bindHammerToDiv(button, this.editEdgeMode.bind(this)); } _createDeleteButton(locale) { if (this.options.rtl) { var deleteBtnClass = 'vis-button vis-delete-rtl'; } else { var deleteBtnClass = 'vis-button vis-delete'; } let button = this._createButton('delete', deleteBtnClass, locale['del'] || this.options.locales['en']['del']); this.manipulationDiv.appendChild(button); this._bindHammerToDiv(button, this.deleteSelected.bind(this)); } _createBackButton(locale) { let button = this._createButton('back', 'vis-button vis-back', locale['back'] || this.options.locales['en']['back']); this.manipulationDiv.appendChild(button); this._bindHammerToDiv(button, this.showManipulatorToolbar.bind(this)); } _createButton(id, className, label, labelClassName = 'vis-label') { this.manipulationDOM[id+'Div'] = document.createElement('div'); this.manipulationDOM[id+'Div'].className = className; this.manipulationDOM[id+'Label'] = document.createElement('div'); this.manipulationDOM[id+'Label'].className = labelClassName; this.manipulationDOM[id+'Label'].innerHTML = label; this.manipulationDOM[id+'Div'].appendChild(this.manipulationDOM[id+'Label']); return this.manipulationDOM[id+'Div']; } _createDescription(label) { this.manipulationDiv.appendChild( this._createButton('description', 'vis-button vis-none', label) ); } // -------------------------- End of DOM functions for buttons ------------------------------// /** * this binds an event until cleanup by the clean functions. * @param event * @param newFunction * @private */ _temporaryBindEvent(event, newFunction) { this.temporaryEventFunctions.push({event:event, boundFunction:newFunction}); this.body.emitter.on(event, newFunction); } /** * this overrides an UI function until cleanup by the clean function * @param UIfunctionName * @param newFunction * @private */ _temporaryBindUI(UIfunctionName, newFunction) { if (this.body.eventListeners[UIfunctionName] !== undefined) { this.temporaryUIFunctions[UIfunctionName] = this.body.eventListeners[UIfunctionName]; this.body.eventListeners[UIfunctionName] = newFunction; } else { throw new Error('This UI function does not exist. Typo? You tried: ' + UIfunctionName + ' possible are: ' + JSON.stringify(Object.keys(this.body.eventListeners))); } } /** * Restore the overridden UI functions to their original state. * * @private */ _unbindTemporaryUIs() { for (let functionName in this.temporaryUIFunctions) { if (this.temporaryUIFunctions.hasOwnProperty(functionName)) { this.body.eventListeners[functionName] = this.temporaryUIFunctions[functionName]; delete this.temporaryUIFunctions[functionName]; } } this.temporaryUIFunctions = {}; } /** * Unbind the events created by _temporaryBindEvent * @private */ _unbindTemporaryEvents() { for (let i = 0; i < this.temporaryEventFunctions.length; i++) { let eventName = this.temporaryEventFunctions[i].event; let boundFunction = this.temporaryEventFunctions[i].boundFunction; this.body.emitter.off(eventName, boundFunction); } this.temporaryEventFunctions = []; } /** * Bind an hammer instance to a DOM element. * @param domElement * @param funct */ _bindHammerToDiv(domElement, boundFunction) { let hammer = new Hammer(domElement, {}); hammerUtil.onTouch(hammer, boundFunction); this.manipulationHammers.push(hammer); } /** * Neatly clean up temporary edges and nodes * @private */ _cleanupTemporaryNodesAndEdges() { // _clean temporary edges for (let i = 0; i < this.temporaryIds.edges.length; i++) { this.body.edges[this.temporaryIds.edges[i]].disconnect(); delete this.body.edges[this.temporaryIds.edges[i]]; let indexTempEdge = this.body.edgeIndices.indexOf(this.temporaryIds.edges[i]); if (indexTempEdge !== -1) {this.body.edgeIndices.splice(indexTempEdge,1);} } // _clean temporary nodes for (let i = 0; i < this.temporaryIds.nodes.length; i++) { delete this.body.nodes[this.temporaryIds.nodes[i]]; let indexTempNode = this.body.nodeIndices.indexOf(this.temporaryIds.nodes[i]); if (indexTempNode !== -1) {this.body.nodeIndices.splice(indexTempNode,1);} } this.temporaryIds = {nodes: [], edges: []}; } // ------------------------------------------ EDIT EDGE FUNCTIONS -----------------------------------------// /** * the touch is used to get the position of the initial click * @param event * @private */ _controlNodeTouch(event) { this.selectionHandler.unselectAll(); this.lastTouch = this.body.functions.getPointer(event.center); this.lastTouch.translation = util.extend({},this.body.view.translation); // copy the object } /** * the drag start is used to mark one of the control nodes as selected. * @param event * @private */ _controlNodeDragStart(event) { let pointer = this.lastTouch; let pointerObj = this.selectionHandler._pointerToPositionObject(pointer); let from = this.body.nodes[this.temporaryIds.nodes[0]]; let to = this.body.nodes[this.temporaryIds.nodes[1]]; let edge = this.body.edges[this.edgeBeingEditedId]; this.selectedControlNode = undefined; let fromSelect = from.isOverlappingWith(pointerObj); let toSelect = to.isOverlappingWith(pointerObj); if (fromSelect === true) { this.selectedControlNode = from; edge.edgeType.from = from; } else if (toSelect === true) { this.selectedControlNode = to; edge.edgeType.to = to; } // we use the selection to find the node that is being dragged. We explicitly select it here. if (this.selectedControlNode !== undefined) { this.selectionHandler.selectObject(this.selectedControlNode) } this.body.emitter.emit('_redraw'); } /** * dragging the control nodes or the canvas * @param event * @private */ _controlNodeDrag(event) { this.body.emitter.emit('disablePhysics'); let pointer = this.body.functions.getPointer(event.center); let pos = this.canvas.DOMtoCanvas(pointer); if (this.selectedControlNode !== undefined) { this.selectedControlNode.x = pos.x; this.selectedControlNode.y = pos.y; } else { // if the drag was not started properly because the click started outside the network div, start it now. let diffX = pointer.x - this.lastTouch.x; let diffY = pointer.y - this.lastTouch.y; this.body.view.translation = {x:this.lastTouch.translation.x + diffX, y:this.lastTouch.translation.y + diffY}; } this.body.emitter.emit('_redraw'); } /** * connecting or restoring the control nodes. * @param event * @private */ _controlNodeDragEnd(event) { let pointer = this.body.functions.getPointer(event.center); let pointerObj = this.selectionHandler._pointerToPositionObject(pointer); let edge = this.body.edges[this.edgeBeingEditedId]; // if the node that was dragged is not a control node, return if (this.selectedControlNode === undefined) { return; } // we use the selection to find the node that is being dragged. We explicitly DEselect the control node here. this.selectionHandler.unselectAll(); let overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj); let node = undefined; for (let i = overlappingNodeIds.length-1; i >= 0; i--) { if (overlappingNodeIds[i] !== this.selectedControlNode.id) { node = this.body.nodes[overlappingNodeIds[i]]; break; } } // perform the connection if (node !== undefined && this.selectedControlNode !== undefined) { if (node.isCluster === true) { alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']) } else { let from = this.body.nodes[this.temporaryIds.nodes[0]]; if (this.selectedControlNode.id === from.id) { this._performEditEdge(node.id, edge.to.id); } else { this._performEditEdge(edge.from.id, node.id); } } } else { edge.updateEdgeType(); this.body.emitter.emit('restorePhysics'); } this.body.emitter.emit('_redraw'); } // ------------------------------------ END OF EDIT EDGE FUNCTIONS -----------------------------------------// // ------------------------------------------- ADD EDGE FUNCTIONS -----------------------------------------// /** * the function bound to the selection event. It checks if you want to connect a cluster and changes the description * to walk the user through the process. * * @private */ _handleConnect(event) { // check to avoid double fireing of this function. if (new Date().valueOf() - this.touchTime > 100) { this.lastTouch = this.body.functions.getPointer(event.center); this.lastTouch.translation = util.extend({},this.body.view.translation); // copy the object let pointer = this.lastTouch; let node = this.selectionHandler.getNodeAt(pointer); if (node !== undefined) { if (node.isCluster === true) { alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']) } else { // create a node the temporary line can look at let targetNode = this._getNewTargetNode(node.x,node.y); this.body.nodes[targetNode.id] = targetNode; this.body.nodeIndices.push(targetNode.id); // create a temporary edge let connectionEdge = this.body.functions.createEdge({ id: 'connectionEdge' + util.randomUUID(), from: node.id, to: targetNode.id, physics: false, smooth: { enabled: true, type: 'continuous', roundness: 0.5 } }); this.body.edges[connectionEdge.id] = connectionEdge; this.body.edgeIndices.push(connectionEdge.id); this.temporaryIds.nodes.push(targetNode.id); this.temporaryIds.edges.push(connectionEdge.id); } } this.touchTime = new Date().valueOf(); } } _dragControlNode(event) { let pointer = this.body.functions.getPointer(event.center); if (this.temporaryIds.nodes[0] !== undefined) { let targetNode = this.body.nodes[this.temporaryIds.nodes[0]]; // there is only one temp node in the add edge mode. targetNode.x = this.canvas._XconvertDOMtoCanvas(pointer.x); targetNode.y = this.canvas._YconvertDOMtoCanvas(pointer.y); this.body.emitter.emit('_redraw'); } else { let diffX = pointer.x - this.lastTouch.x; let diffY = pointer.y - this.lastTouch.y; this.body.view.translation = {x:this.lastTouch.translation.x + diffX, y:this.lastTouch.translation.y + diffY}; } } /** * Connect the new edge to the target if one exists, otherwise remove temp line * @param event * @private */ _finishConnect(event) { let pointer = this.body.functions.getPointer(event.center); let pointerObj = this.selectionHandler._pointerToPositionObject(pointer); // remember the edge id let connectFromId = undefined; if (this.temporaryIds.edges[0] !== undefined) { connectFromId = this.body.edges[this.temporaryIds.edges[0]].fromId; } // get the overlapping node but NOT the temporary node; let overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj); let node = undefined; for (let i = overlappingNodeIds.length-1; i >= 0; i--) { // if the node id is NOT a temporary node, accept the node. if (this.temporaryIds.nodes.indexOf(overlappingNodeIds[i]) === -1) { node = this.body.nodes[overlappingNodeIds[i]]; break; } } // clean temporary nodes and edges. this._cleanupTemporaryNodesAndEdges(); // perform the connection if (node !== undefined) { if (node.isCluster === true) { alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']); } else { if (this.body.nodes[connectFromId] !== undefined && this.body.nodes[node.id] !== undefined) { this._performAddEdge(connectFromId, node.id); } } } this.body.emitter.emit('_redraw'); } // --------------------------------------- END OF ADD EDGE FUNCTIONS -------------------------------------// // ------------------------------ Performing all the actual data manipulation ------------------------// /** * Adds a node on the specified location */ _performAddNode(clickData) { let defaultData = { id: util.randomUUID(), x: clickData.pointer.canvas.x, y: clickData.pointer.canvas.y, label: 'new' }; if (typeof this.options.addNode === 'function') { if (this.options.addNode.length === 2) { this.options.addNode(defaultData, (finalizedData) => { if (finalizedData !== null && finalizedData !== undefined && this.inMode === 'addNode') { // if for whatever reason the mode has changes (due to dataset change) disregard the callback this.body.data.nodes.getDataSet().add(finalizedData); this.showManipulatorToolbar(); } }); } else { throw new Error('The function for add does not support two arguments (data,callback)'); this.showManipulatorToolbar(); } } else { this.body.data.nodes.getDataSet().add(defaultData); this.showManipulatorToolbar(); } } /** * connect two nodes with a new edge. * * @private */ _performAddEdge(sourceNodeId, targetNodeId) { let defaultData = {from: sourceNodeId, to: targetNodeId}; if (typeof this.options.addEdge === 'function') { if (this.options.addEdge.length === 2) { this.options.addEdge(defaultData, (finalizedData) => { if (finalizedData !== null && finalizedData !== undefined && this.inMode === 'addEdge') { // if for whatever reason the mode has changes (due to dataset change) disregard the callback this.body.data.edges.getDataSet().add(finalizedData); this.selectionHandler.unselectAll(); this.showManipulatorToolbar(); } }); } else { throw new Error('The function for connect does not support two arguments (data,callback)'); } } else { this.body.data.edges.getDataSet().add(defaultData); this.selectionHandler.unselectAll(); this.showManipulatorToolbar(); } } /** * connect two nodes with a new edge. * * @private */ _performEditEdge(sourceNodeId, targetNodeId) { let defaultData = {id: this.edgeBeingEditedId, from: sourceNodeId, to: targetNodeId, label: this.body.data.edges._data[this.edgeBeingEditedId].label }; let eeFunct = this.options.editEdge; if (typeof eeFunct === 'object') { eeFunct = eeFunct.editWithoutDrag; } if (typeof eeFunct === 'function') { if (eeFunct.length === 2) { eeFunct(defaultData, (finalizedData) => { if (finalizedData === null || finalizedData === undefined || this.inMode !== 'editEdge') { // if for whatever reason the mode has changes (due to dataset change) disregard the callback) { this.body.edges[defaultData.id].updateEdgeType(); this.body.emitter.emit('_redraw'); this.showManipulatorToolbar(); } else { this.body.data.edges.getDataSet().update(finalizedData); this.selectionHandler.unselectAll(); this.showManipulatorToolbar(); } }); } else { throw new Error('The function for edit does not support two arguments (data, callback)'); } } else { this.body.data.edges.getDataSet().update(defaultData); this.selectionHandler.unselectAll(); this.showManipulatorToolbar(); } } } export default ManipulationSystem;
AnttiKurittu/kirjuri
views/js/vis-4.18.0/lib/network/modules/ManipulationSystem.js
JavaScript
mit
38,796
<h1>Service components in <code>ng</code></h1> <div class="component-breakdown"> <div> <table class="definition-table"> <tr> <th>Name</th> <th>Description</th> </tr> <tr> <td><a href="api/ng/service/$anchorScroll">$anchorScroll</a></td> <td><p>When called, it checks the current value of <a href="api/ng/service/$location#hash">$location.hash()</a> and scrolls to the related element, according to the rules specified in the <a href="http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document">Html5 spec</a>.</p> </td> </tr> <tr> <td><a href="api/ng/service/$animate">$animate</a></td> <td><p>The $animate service provides rudimentary DOM manipulation functions to insert, remove and move elements within the DOM, as well as adding and removing classes. This service is the core service used by the ngAnimate $animator service which provides high-level animation hooks for CSS and JavaScript.</p> </td> </tr> <tr> <td><a href="api/ng/service/$cacheFactory">$cacheFactory</a></td> <td><p>Factory that constructs <a href="api/ng/type/$cacheFactory.Cache">Cache</a> objects and gives access to them.</p> </td> </tr> <tr> <td><a href="api/ng/service/$templateCache">$templateCache</a></td> <td><p>The first time a template is used, it is loaded in the template cache for quick retrieval. You can load templates directly into the cache in a <code>script</code> tag, or by consuming the <code>$templateCache</code> service directly.</p> </td> </tr> <tr> <td><a href="api/ng/service/$compile">$compile</a></td> <td><p>Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link <a href="api/ng/type/$rootScope.Scope"><code>scope</code></a> and the template together.</p> </td> </tr> <tr> <td><a href="api/ng/service/$controller">$controller</a></td> <td><p><code>$controller</code> service is responsible for instantiating controllers.</p> </td> </tr> <tr> <td><a href="api/ng/service/$document">$document</a></td> <td><p>A <a href="api/ng/function/angular.element">jQuery or jqLite</a> wrapper for the browser&#39;s <code>window.document</code> object.</p> </td> </tr> <tr> <td><a href="api/ng/service/$exceptionHandler">$exceptionHandler</a></td> <td><p>Any uncaught exception in angular expressions is delegated to this service. The default implementation simply delegates to <code>$log.error</code> which logs it into the browser console.</p> </td> </tr> <tr> <td><a href="api/ng/service/$filter">$filter</a></td> <td><p>Filters are used for formatting data displayed to the user.</p> </td> </tr> <tr> <td><a href="api/ng/service/$http">$http</a></td> <td><p>The <code>$http</code> service is a core Angular service that facilitates communication with the remote HTTP servers via the browser&#39;s <a href="https://developer.mozilla.org/en/xmlhttprequest">XMLHttpRequest</a> object or via <a href="http://en.wikipedia.org/wiki/JSONP">JSONP</a>.</p> </td> </tr> <tr> <td><a href="api/ng/service/$httpBackend">$httpBackend</a></td> <td><p>HTTP backend used by the <a href="api/ng/service/$http">service</a> that delegates to XMLHttpRequest object or JSONP and deals with browser incompatibilities.</p> </td> </tr> <tr> <td><a href="api/ng/service/$interpolate">$interpolate</a></td> <td><p>Compiles a string with markup into an interpolation function. This service is used by the HTML <a href="api/ng/service/$compile">$compile</a> service for data binding. See <a href="api/ng/provider/$interpolateProvider">$interpolateProvider</a> for configuring the interpolation markup.</p> </td> </tr> <tr> <td><a href="api/ng/service/$interval">$interval</a></td> <td><p>Angular&#39;s wrapper for <code>window.setInterval</code>. The <code>fn</code> function is executed every <code>delay</code> milliseconds.</p> </td> </tr> <tr> <td><a href="api/ng/service/$locale">$locale</a></td> <td><p>$locale service provides localization rules for various Angular components. As of right now the only public api is:</p> </td> </tr> <tr> <td><a href="api/ng/service/$location">$location</a></td> <td><p>The $location service parses the URL in the browser address bar (based on the <a href="https://developer.mozilla.org/en/window.location">window.location</a>) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar.</p> </td> </tr> <tr> <td><a href="api/ng/service/$log">$log</a></td> <td><p>Simple service for logging. Default implementation safely writes the message into the browser&#39;s console (if present).</p> </td> </tr> <tr> <td><a href="api/ng/service/$parse">$parse</a></td> <td><p>Converts Angular <a href="guide/expression">expression</a> into a function.</p> </td> </tr> <tr> <td><a href="api/ng/service/$q">$q</a></td> <td><p>A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.</p> </td> </tr> <tr> <td><a href="api/ng/service/$rootElement">$rootElement</a></td> <td><p>The root element of Angular application. This is either the element where <a href="api/ng/directive/ngApp">ngApp</a> was declared or the element passed into <a href="api/ng/function/angular.bootstrap"><code>angular.bootstrap</code></a>. The element represent the root element of application. It is also the location where the applications <a href="api/auto/service/$injector">$injector</a> service gets published, it can be retrieved using <code>$rootElement.injector()</code>.</p> </td> </tr> <tr> <td><a href="api/ng/service/$rootScope">$rootScope</a></td> <td><p>Every application has a single root <a href="api/ng/type/$rootScope.Scope">scope</a>. All other scopes are descendant scopes of the root scope. Scopes provide separation between the model and the view, via a mechanism for watching the model for changes. They also provide an event emission/broadcast and subscription facility. See the <a href="guide/scope">developer guide on scopes</a>.</p> </td> </tr> <tr> <td><a href="api/ng/service/$sceDelegate">$sceDelegate</a></td> <td><p><code>$sceDelegate</code> is a service that is used by the <code>$sce</code> service to provide <a href="api/ng/service/$sce">Strict Contextual Escaping (SCE)</a> services to AngularJS.</p> </td> </tr> <tr> <td><a href="api/ng/service/$sce">$sce</a></td> <td><p><code>$sce</code> is a service that provides Strict Contextual Escaping services to AngularJS.</p> </td> </tr> <tr> <td><a href="api/ng/service/$templateRequest">$templateRequest</a></td> <td><p>The <code>$templateRequest</code> service downloads the provided template using <code>$http</code> and, upon success, stores the contents inside of <code>$templateCache</code>. If the HTTP request fails or the response data of the HTTP request is empty then a <code>$compile</code> error will be thrown (the exception can be thwarted by setting the 2nd parameter of the function to true).</p> </td> </tr> <tr> <td><a href="api/ng/service/$timeout">$timeout</a></td> <td><p>Angular&#39;s wrapper for <code>window.setTimeout</code>. The <code>fn</code> function is wrapped into a try/catch block and delegates any exceptions to <a href="api/ng/service/$exceptionHandler">$exceptionHandler</a> service.</p> </td> </tr> <tr> <td><a href="api/ng/service/$window">$window</a></td> <td><p>A reference to the browser&#39;s <code>window</code> object. While <code>window</code> is globally available in JavaScript, it causes testability problems, because it is a global variable. In angular we always refer to it through the <code>$window</code> service, so it may be overridden, removed or mocked for testing.</p> </td> </tr> </table> </div> </div>
viral810/ngSimpleCMS
web/bundles/sunraangular/js/angular/angular-1.3.3/docs/partials/api/ng/service.html
HTML
mit
8,622
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact Commercial Usage Licensees holding valid commercial licenses may use this file in accordance with the Commercial Software License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Sencha. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. Build date: 2013-05-16 14:36:50 (f9be68accb407158ba2b1be2c226a6ce1f649314) */ /** * This class is intended to be extended or created via the {@link Ext.Component#componentLayout layout} * configuration property. See {@link Ext.Component#componentLayout} for additional details. * @private */ Ext.define('Ext.layout.component.Component', { /* Begin Definitions */ extend: 'Ext.layout.Layout', /* End Definitions */ type: 'component', isComponentLayout: true, nullBox: {}, usesContentHeight: true, usesContentWidth: true, usesHeight: true, usesWidth: true, beginLayoutCycle: function (ownerContext, firstCycle) { var me = this, owner = me.owner, ownerCtContext = ownerContext.ownerCtContext, heightModel = ownerContext.heightModel, widthModel = ownerContext.widthModel, body = owner.el.dom === document.body, lastBox = owner.lastBox || me.nullBox, lastSize = owner.el.lastBox || me.nullBox, dirty = !body, ownerLayout, v, widthName, heightName; me.callParent(arguments); if (firstCycle) { if (me.usesContentWidth) { ++ownerContext.consumersContentWidth; } if (me.usesContentHeight) { ++ownerContext.consumersContentHeight; } if (me.usesWidth) { ++ownerContext.consumersWidth; } if (me.usesHeight) { ++ownerContext.consumersHeight; } if (ownerCtContext && !ownerCtContext.hasRawContent) { ownerLayout = owner.ownerLayout; if (ownerLayout.usesWidth) { ++ownerContext.consumersWidth; } if (ownerLayout.usesHeight) { ++ownerContext.consumersHeight; } } } // we want to publish configured dimensions as early as possible and since this is // a write phase... if (widthModel.configured) { // If the owner.el is the body, owner.width is not dirty (we don't want to write // it to the body el). For other el's, the width may already be correct in the // DOM (e.g., it is rendered in the markup initially). If the width is not // correct in the DOM, this is only going to be the case on the first cycle. widthName = widthModel.names.width; if (!body) { dirty = firstCycle ? owner[widthName] !== lastSize.width : widthModel.constrained; } ownerContext.setWidth(owner[widthName], dirty); } else if (ownerContext.isTopLevel) { if (widthModel.calculated) { v = lastBox.width; ownerContext.setWidth(v, /*dirty=*/v != lastSize.width); } v = lastBox.x; ownerContext.setProp('x', v, /*dirty=*/v != lastSize.x); } if (heightModel.configured) { heightName = heightModel.names.height; if (!body) { dirty = firstCycle ? owner[heightName] !== lastSize.height : heightModel.constrained; } ownerContext.setHeight(owner[heightName], dirty); } else if (ownerContext.isTopLevel) { if (heightModel.calculated) { v = lastBox.height; ownerContext.setHeight(v, v != lastSize.height); } v = lastBox.y; ownerContext.setProp('y', v, /*dirty=*/v != lastSize.y); } }, finishedLayout: function(ownerContext) { var me = this, elementChildren = ownerContext.children, owner = me.owner, len, i, elContext, lastBox, props; // NOTE: In the code below we cannot use getProp because that will generate a layout dependency // Set lastBox on managed child Elements. // So that ContextItem.constructor can snag the lastBox for use by its undo method. if (elementChildren) { len = elementChildren.length; for (i = 0; i < len; i++) { elContext = elementChildren[i]; elContext.el.lastBox = elContext.props; } } // Cache the size from which we are changing so that notifyOwner can notify the owningComponent with all essential information ownerContext.previousSize = me.lastComponentSize; // Cache the currently layed out size me.lastComponentSize = owner.el.lastBox = props = ownerContext.props; // lastBox is a copy of the defined props to allow save/restore of these (panel // collapse needs this) lastBox = owner.lastBox || (owner.lastBox = {}); lastBox.x = props.x; lastBox.y = props.y; lastBox.width = props.width; lastBox.height = props.height; lastBox.invalid = false; me.callParent(arguments); }, notifyOwner: function(ownerContext) { var me = this, currentSize = me.lastComponentSize, prevSize = ownerContext.previousSize, args = [currentSize.width, currentSize.height]; if (prevSize) { args.push(prevSize.width, prevSize.height); } // Call afterComponentLayout passing new size, and only passing old size if there *was* an old size. me.owner.afterComponentLayout.apply(me.owner, args); }, /** * Returns the owner component's resize element. * @return {Ext.Element} */ getTarget : function() { return this.owner.el; }, /** * Returns the element into which rendering must take place. Defaults to the owner Component's encapsulating element. * * May be overridden in Component layout managers which implement an inner element. * @return {Ext.Element} */ getRenderTarget : function() { return this.owner.el; }, cacheTargetInfo: function(ownerContext) { var me = this, targetInfo = me.targetInfo, target; if (!targetInfo) { target = ownerContext.getEl('getTarget', me); me.targetInfo = targetInfo = { padding: target.getPaddingInfo(), border: target.getBorderInfo() }; } return targetInfo; }, measureAutoDimensions: function (ownerContext, dimensions) { // Subtle But Important: // // We don't want to call getProp/hasProp et.al. unless we in fact need that value // for our results! If we call it and don't need it, the layout manager will think // we depend on it and will schedule us again should it change. var me = this, owner = me.owner, containerLayout = owner.layout, heightModel = ownerContext.heightModel, widthModel = ownerContext.widthModel, boxParent = ownerContext.boxParent, isBoxParent = ownerContext.isBoxParent, props = ownerContext.props, isContainer, ret = { gotWidth: false, gotHeight: false, isContainer: (isContainer = !ownerContext.hasRawContent) }, hv = dimensions || 3, zeroWidth, zeroHeight, needed = 0, got = 0, ready, size, temp; // Note: this method is called *a lot*, so we have to be careful not to waste any // time or make useless calls or, especially, read the DOM when we can avoid it. //--------------------------------------------------------------------- // Width if (widthModel.shrinkWrap && ownerContext.consumersContentWidth) { ++needed; zeroWidth = !(hv & 1); if (isContainer) { // as a componentLayout for a container, we rely on the container layout to // produce contentWidth... if (zeroWidth) { ret.contentWidth = 0; ret.gotWidth = true; ++got; } else if ((ret.contentWidth = ownerContext.getProp('contentWidth')) !== undefined) { ret.gotWidth = true; ++got; } } else { size = props.contentWidth; if (typeof size == 'number') { // if (already determined) ret.contentWidth = size; ret.gotWidth = true; ++got; } else { if (zeroWidth) { ready = true; } else if (!ownerContext.hasDomProp('containerChildrenSizeDone')) { ready = false; } else if (isBoxParent || !boxParent || boxParent.widthModel.shrinkWrap) { // if we have no boxParent, we are ready, but a shrinkWrap boxParent // artificially provides width early in the measurement process so // we are ready to go in that case as well... ready = true; } else { // lastly, we have a boxParent that will be given a width, so we // can wait for that width to be set in order to properly measure // whatever is inside... ready = boxParent.hasDomProp('width'); } if (ready) { if (zeroWidth) { temp = 0; } else if (containerLayout && containerLayout.measureContentWidth) { // Allow the container layout to do the measurement since it // may have a better idea of how to do it even with no items: temp = containerLayout.measureContentWidth(ownerContext); } else { temp = me.measureContentWidth(ownerContext); } if (!isNaN(ret.contentWidth = temp)) { ownerContext.setContentWidth(temp, true); ret.gotWidth = true; ++got; } } } } } else if (widthModel.natural && ownerContext.consumersWidth) { ++needed; size = props.width; // zeroWidth does not apply if (typeof size == 'number') { // if (already determined) ret.width = size; ret.gotWidth = true; ++got; } else { if (isBoxParent || !boxParent) { ready = true; } else { // lastly, we have a boxParent that will be given a width, so we // can wait for that width to be set in order to properly measure // whatever is inside... ready = boxParent.hasDomProp('width'); } if (ready) { if (!isNaN(ret.width = me.measureOwnerWidth(ownerContext))) { ownerContext.setWidth(ret.width, false); ret.gotWidth = true; ++got; } } } } //--------------------------------------------------------------------- // Height if (heightModel.shrinkWrap && ownerContext.consumersContentHeight) { ++needed; zeroHeight = !(hv & 2); if (isContainer) { // don't ask unless we need to know... if (zeroHeight) { ret.contentHeight = 0; ret.gotHeight = true; ++got; } else if ((ret.contentHeight = ownerContext.getProp('contentHeight')) !== undefined) { ret.gotHeight = true; ++got; } } else { size = props.contentHeight; if (typeof size == 'number') { // if (already determined) ret.contentHeight = size; ret.gotHeight = true; ++got; } else { if (zeroHeight) { ready = true; } else if (!ownerContext.hasDomProp('containerChildrenSizeDone')) { ready = false; } else if (owner.noWrap) { ready = true; } else if (!widthModel.shrinkWrap) { // fixed width, so we need the width to determine the height... ready = (ownerContext.bodyContext || ownerContext).hasDomProp('width');// && (!ownerContext.bodyContext || ownerContext.bodyContext.hasDomProp('width')); } else if (isBoxParent || !boxParent || boxParent.widthModel.shrinkWrap) { // if we have no boxParent, we are ready, but an autoWidth boxParent // artificially provides width early in the measurement process so // we are ready to go in that case as well... ready = true; } else { // lastly, we have a boxParent that will be given a width, so we // can wait for that width to be set in order to properly measure // whatever is inside... ready = boxParent.hasDomProp('width'); } if (ready) { if (zeroHeight) { temp = 0; } else if (containerLayout && containerLayout.measureContentHeight) { // Allow the container layout to do the measurement since it // may have a better idea of how to do it even with no items: temp = containerLayout.measureContentHeight(ownerContext); } else { temp = me.measureContentHeight(ownerContext); } if (!isNaN(ret.contentHeight = temp)) { ownerContext.setContentHeight(temp, true); ret.gotHeight = true; ++got; } } } } } else if (heightModel.natural && ownerContext.consumersHeight) { ++needed; size = props.height; // zeroHeight does not apply if (typeof size == 'number') { // if (already determined) ret.height = size; ret.gotHeight = true; ++got; } else { if (isBoxParent || !boxParent) { ready = true; } else { // lastly, we have a boxParent that will be given a width, so we // can wait for that width to be set in order to properly measure // whatever is inside... ready = boxParent.hasDomProp('width'); } if (ready) { if (!isNaN(ret.height = me.measureOwnerHeight(ownerContext))) { ownerContext.setHeight(ret.height, false); ret.gotHeight = true; ++got; } } } } if (boxParent) { ownerContext.onBoxMeasured(); } ret.gotAll = got == needed; // see if we can avoid calling this method by storing something on ownerContext. return ret; }, measureContentWidth: function (ownerContext) { // contentWidth includes padding, but not border, framing or margins return ownerContext.el.getWidth() - ownerContext.getFrameInfo().width; }, measureContentHeight: function (ownerContext) { // contentHeight includes padding, but not border, framing or margins return ownerContext.el.getHeight() - ownerContext.getFrameInfo().height; }, measureOwnerHeight: function (ownerContext) { return ownerContext.el.getHeight(); }, measureOwnerWidth: function (ownerContext) { return ownerContext.el.getWidth(); } });
ryancanulla/findMe
web/ext/src/layout/component/Component.js
JavaScript
mit
17,347
#include <node.h> #include "zopfli.h" #include "zopfli-binding.h" #include "png/zopflipng.h" namespace nodezopfli { using namespace v8; using namespace node; NAN_INLINE Nan::NAN_METHOD_RETURN_TYPE ParseArgs(const Nan::FunctionCallbackInfo<v8::Value>& info, ZopfliFormat& format, ZopfliOptions& zopfli_options) { ZopfliInitOptions(&zopfli_options); format = ZOPFLI_FORMAT_GZIP; if(info.Length() < 1 || !Buffer::HasInstance(info[0])) { Nan::ThrowTypeError("First argument must be a buffer"); } if(info.Length() >= 2 && info[1]->IsString()) { std::string given_format(*Nan::Utf8String(info[1])); if(given_format.compare("gzip") == 0) { format = ZOPFLI_FORMAT_GZIP; } else if(given_format.compare("zlib") == 0) { format = ZOPFLI_FORMAT_ZLIB; } else if(given_format.compare("deflate") == 0) { format = ZOPFLI_FORMAT_DEFLATE; } else { Nan::ThrowTypeError("Invalid Zopfli format"); } } else { Nan::ThrowTypeError("Second argument must be a string"); } if(info.Length() >= 3 && info[2]->IsObject()) { Local<Object> options = info[2].As<Object>(); if (!options.IsEmpty()) { Local<String> option_name; Local<Value> fieldValue; // Whether to print output option_name = Nan::New<String>("verbose").ToLocalChecked(); if (Nan::Has(options, option_name).FromJust()) { zopfli_options.verbose = Nan::Get(options, option_name).ToLocalChecked()->BooleanValue(); } // Whether to print more detailed output option_name = Nan::New<String>("verbose_more").ToLocalChecked(); if (Nan::Has(options, option_name).FromJust()) { zopfli_options.verbose_more = Nan::Get(options, option_name).ToLocalChecked()->BooleanValue(); } /* Maximum amount of times to rerun forward and backward pass to optimize LZ77 compression cost. Good values: 10, 15 for small files, 5 for files over several MB in size or it will be too slow. */ option_name = Nan::New<String>("numiterations").ToLocalChecked(); if (Nan::Has(options, option_name).FromJust()) { zopfli_options.numiterations = Nan::Get(options, option_name).ToLocalChecked()->Int32Value(); } /* If true, chooses the optimal block split points only after doing the iterative LZ77 compression. If false, chooses the block split points first, then does iterative LZ77 on each individual block. Depending on the file, either first or last gives the best compression. Default: false (0). */ option_name = Nan::New<String>("blocksplitting").ToLocalChecked(); if (Nan::Has(options, option_name).FromJust()) { zopfli_options.blocksplitting = Nan::Get(options, option_name).ToLocalChecked()->Int32Value(); } /* If true, chooses the optimal block split points only after doing the iterative LZ77 compression. If false, chooses the block split points first, then does iterative LZ77 on each individual block. Depending on the file, either first or last gives the best compression. Default: false (0). */ option_name = Nan::New<String>("blocksplittinglast").ToLocalChecked(); if (Nan::Has(options, option_name).FromJust()) { zopfli_options.blocksplittinglast = Nan::Get(options, option_name).ToLocalChecked()->Int32Value(); } /* Maximum amount of blocks to split into (0 for unlimited, but this can give extreme results that hurt compression on some files). Default value: 15. */ option_name = Nan::New<String>("blocksplittingmax").ToLocalChecked(); if (Nan::Has(options, option_name).FromJust()) { zopfli_options.blocksplittingmax = Nan::Get(options, option_name).ToLocalChecked()->Int32Value(); } } } else { Nan::ThrowTypeError("Third argument must be an object"); } //info.GetReturnValue().SetUndefined(); } // Base // PROTECTED class CompressWorker : public Nan::AsyncWorker { public: CompressWorker(Nan::Callback *callback, ZopfliFormat& format, ZopfliOptions& zopfli_options, Handle<Object> buffer) : Nan::AsyncWorker(callback), format(format), zopfli_options(zopfli_options) { Nan::HandleScope scope; // Handle<Object> object = args[0]->ToObject(); size_t length = node::Buffer::Length(buffer); const char *data = node::Buffer::Data(buffer); input = std::string(data, length); resultdata = 0; resultsize = 0; } ~CompressWorker() {} // Executed inside the worker-thread. // It is not safe to access V8, or V8 data structures // here, so everything we need for input and output // should go on `this`. void Execute() { std::string* input = &this->input; ZopfliCompress(&zopfli_options, format, (const unsigned char*)input->data(), input->length(), (unsigned char **)&resultdata, &resultsize); } // Executed when the async work is complete // this function will be run inside the main event loop // so it is safe to use V8 again void HandleOKCallback() { Nan::HandleScope(); Local<Value> argv[] = { Nan::Null(), Nan::NewBuffer((char*)resultdata, resultsize).ToLocalChecked() }; callback->Call(2, argv); } private: ZopfliFormat format; ZopfliOptions zopfli_options; std::string input; char* resultdata; size_t resultsize; }; // CompressBinding // PUBLIC NAN_METHOD(CompressBinding::Async) { ZopfliFormat format; ZopfliOptions zopfli_options; if(info.Length() == 0 || (info.Length() >= 1 && !info[info.Length()-1]->IsFunction())) { Nan::ThrowTypeError("Last argument must be a callback function"); } ParseArgs(info, format, zopfli_options); Nan::Callback *callback = new Nan::Callback(info[info.Length()-1].As<v8::Function>()); Nan::AsyncQueueWorker(new CompressWorker(callback, format, zopfli_options, info[0]->ToObject())); info.GetReturnValue().SetUndefined(); } NAN_METHOD(CompressBinding::Sync) { ZopfliFormat format; ZopfliOptions zopfli_options; ParseArgs(info, format, zopfli_options); Local<Object> inbuffer = info[0]->ToObject(); size_t inbuffersize = Buffer::Length(inbuffer); const unsigned char * inbufferdata = (const unsigned char*)Buffer::Data(inbuffer); unsigned char* out = 0; size_t outsize = 0; ZopfliCompress(&zopfli_options, format, inbufferdata, inbuffersize, &out, &outsize); info.GetReturnValue().Set(Nan::NewBuffer((char*)out, outsize).ToLocalChecked()); } unsigned updateAdler32(unsigned int adler, const unsigned char* data, size_t size) { unsigned sums_overflow = 5550; unsigned s1 = adler; unsigned s2 = 1 >> 16; while (size > 0) { size_t amount = size > sums_overflow ? sums_overflow : size; size -= amount; while (amount > 0) { s1 += (*data++); s2 += s1; amount--; } s1 %= 65521; s2 %= 65521; } return (s2 << 16) | s1; } NAN_METHOD(Adler32) { if(info.Length() >= 1 && !info[0]->IsUint32() && !info[0]->IsInt32()) { return Nan::ThrowTypeError("adler must be an unsigned integer"); } unsigned int adler = info[0]->Uint32Value(); if(info.Length() < 1 || !Buffer::HasInstance(info[1])) { return Nan::ThrowTypeError("data must be a buffer"); } Local<Value> inbuffer = info[1]; size_t inbuffersize = Buffer::Length(inbuffer->ToObject()); const unsigned char * data = (const unsigned char*)Buffer::Data(inbuffer->ToObject()); adler = updateAdler32(adler, data, inbuffersize); info.GetReturnValue().Set(Nan::New<Uint32>(adler)); } // NAN_MODULE_INIT(Init) { // NAN_EXPORT(target, Foo); // } NAN_MODULE_INIT(Init) { Nan::SetMethod(target, "deflate", CompressBinding::Async); Nan::SetMethod(target, "deflateSync", CompressBinding::Sync); Nan::SetMethod(target, "adler32", Adler32); Nan::SetMethod(target, "pngcompress", PNGDeflate); } NODE_MODULE(zopfli, Init) }
shikun2014010800/manga
web/console/node_modules/node-zopfli/src/zopfli-binding.cc
C++
mit
7,865
<div id="login" class="login-container" data-ng-controller="LoginCtrl"> <div class="bg-danger text-danger login-error" data-ng-repeat="error in errors"><p>{{ error }}</p></div> <form class="form-signin" role="form" data-ng-submit="logIn(formdata)" novalidate> <h2 class="form-signin-heading">TaskBoard - Sign in</h2> <fieldset data-ng-disabled="isSaving"> <input type="text" class="form-control" placeholder="Username" required autofocus data-ng-model="formdata.username"> <input type="password" class="form-control" placeholder="Password" required data-ng-model="formdata.password"> <label class="checkbox"> <input type="checkbox" data-ng-model="formdata.rememberme"> Remember me </label> <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> </fieldset> <p class="small text-center version">{{ version }}</p> </form> </div> <div data-on-load-callback="clear"></div>
ZM-git/TaskBoard
partials/login.html
HTML
mit
990
// -*- mode: java; c-basic-offset: 2; -*- // Copyright 2009-2011 Google, All Rights reserved // Copyright 2011-2012 MIT, All rights reserved // Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt // TODO(user): reconsider visibilities of the abstract base classes in this package package com.google.appinventor.client.editor.simple.components; import com.google.appinventor.client.editor.simple.SimpleEditor; import com.google.appinventor.client.output.OdeLog; import com.google.gwt.event.dom.client.ErrorEvent; import com.google.gwt.event.dom.client.ErrorHandler; import com.google.gwt.event.dom.client.LoadEvent; import com.google.gwt.event.dom.client.LoadHandler; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.SimplePanel; /** * Abstract superclass for MockImage and MockImageSprite. * * @author lizlooney@google.com (Liz Looney) */ abstract class MockImageBase extends MockVisibleComponent { // Property names private static final String PROPERTY_NAME_PICTURE = "Picture"; // Widget for showing the image. private final Image image; private String picturePropValue; MockImageBase(SimpleEditor editor, String type, ImageResource icon) { super(editor, type, icon); // Initialize mock image UI image = new Image(); image.addErrorHandler(new ErrorHandler() { @Override public void onError(ErrorEvent event) { if (picturePropValue != null && !picturePropValue.isEmpty()) { OdeLog.elog("Error occurred while loading image " + picturePropValue); } refreshForm(); } }); image.addLoadHandler(new LoadHandler() { @Override public void onLoad(LoadEvent event) { // Resize to outer container, fixes issue with setting precise size in designer image.setSize("100%", "100%"); refreshForm(); } }); SimplePanel simplePanel = new SimplePanel(); simplePanel.setStylePrimaryName("ode-SimpleMockComponent"); simplePanel.setWidget(image); initComponent(simplePanel); } /* * Sets the image's url to a new value. */ private void setPictureProperty(String text) { picturePropValue = text; String url = convertImagePropertyValueToUrl(text); if (url == null) { // text was not recognized as an asset. Just display the icon for this type of component. Image iconImage = getIconImage(); image.setUrlAndVisibleRect(iconImage.getUrl(), iconImage.getOriginLeft(), iconImage.getOriginTop(), iconImage.getWidth(), iconImage.getHeight()); } else { image.setUrl(url); } } @Override public int getPreferredWidth() { // The superclass uses getOffsetWidth, which won't work for us. // Hide away the current 100% size so we can get at the actual size, otherwise automatic size doesn't work String[] style = MockComponentsUtil.clearSizeStyle(image); int width = image.getWidth(); MockComponentsUtil.restoreSizeStyle(image, style); return width; } @Override public int getPreferredHeight() { // The superclass uses getOffsetHeight, which won't work for us. // Hide away the current 100% size so we can get at the actual size, otherwise automatic size doesn't work String[] style = MockComponentsUtil.clearSizeStyle(image); int height = image.getHeight(); MockComponentsUtil.restoreSizeStyle(image, style); return height; } // PropertyChangeListener implementation @Override public void onPropertyChange(String propertyName, String newValue) { super.onPropertyChange(propertyName, newValue); // Apply changed properties to the mock component if (propertyName.equals(PROPERTY_NAME_PICTURE)) { setPictureProperty(newValue); refreshForm(); } } }
AppScale/appinventor
src/com/google/appinventor/client/editor/simple/components/MockImageBase.java
Java
mit
3,879
'use strict'; /* Services */ // Demonstrate how to register services // In this case it is a simple value service. angular.module('blog.services', []). value('version', '0.1');
emidiocroci/angular-workshop
app/04-advanced/js/services.js
JavaScript
mit
182
h1 { font-size: 30px; color: blue; font-weight: bold; text-align:center; } h2 { text-align:center; } button { margin-left: auto; margin-right: auto; display: block; margin-top: 50px; font-size: 30px; } /* Loader from http://projects.lukehaas.me/css-loaders/#load1 */ .loader, .loader:before, .loader:after { background: #aaaaff; -webkit-animation: load1 1s infinite ease-in-out; animation: load1 1s infinite ease-in-out; width: 1em; height: 4em; } .loader:before, .loader:after { position: absolute; top: 0; content: ''; } .loader:before { left: -1.5em; } .loader { text-indent: -9999em; margin: 8em auto; position: relative; font-size: 11px; -webkit-animation-delay: -0.16s; animation-delay: -0.16s; } .loader:after { left: 1.5em; -webkit-animation-delay: -0.32s; animation-delay: -0.32s; } @-webkit-keyframes load1 { 0%, 80%, 100% { box-shadow: 0 0 #aaaaff; height: 4em; } 40% { box-shadow: 0 -2em #aaaaff; height: 5em; } } @keyframes load1 { 0%, 80%, 100% { box-shadow: 0 0 #aaaaff; height: 4em; } 40% { box-shadow: 0 -2em #aaaaff; height: 5em; } }
kived/python-for-android
testapps/testapp_flask/static/style.css
CSS
mit
1,282
--- title: 'Reminder: OpenStack Networking hangout TODAY' date: 2013-10-29 17:23:20 author: rbowen --- A reminder that the OpenStack Networking (Part II) hangout will be on Thursday. Brent Eagles (beagles) will be picking up where Dave left off last month, and talking about GRE tunneling, VLANs, and other more advanced techniques. Details and signup at https://plus.google.com/u/1/events/cfgnq5t8it7uvksrtpd00s2fcmg If you can help answer questions, please be on the #rdo channel on Freenode. If you're not real familiar with IRC, you can join at https://webchat.freenode.net/?channels=rdo
coolsvap/website
source/blog/2013-10-29-reminder-openstack-networking-hangout-today.html.md
Markdown
mit
594
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class RemoveKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterEvent() { await VerifyKeywordAsync( @"class C { event Goo Bar { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAttribute() { await VerifyKeywordAsync( @"class C { event Goo Bar { [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAdd() { await VerifyKeywordAsync( @"class C { event Goo Bar { add { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAddAndAttribute() { await VerifyKeywordAsync( @"class C { event Goo Bar { add { } [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAddBlock() { await VerifyKeywordAsync( @"class C { event Goo Bar { add { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRemoveKeyword() { await VerifyAbsenceAsync( @"class C { event Goo Bar { remove $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRemoveAccessor() { await VerifyAbsenceAsync( @"class C { event Goo Bar { remove { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInProperty() { await VerifyAbsenceAsync( @"class C { int Goo { $$"); } } }
mavasani/roslyn
src/EditorFeatures/CSharpTest2/Recommendations/RemoveKeywordRecommenderTests.cs
C#
mit
3,870
<?php namespace Concrete\Core\Updater\Migrations\Migrations; use Concrete\Core\Entity\OAuth\RefreshToken; use Concrete\Core\Updater\Migrations\AbstractMigration; use Concrete\Core\Updater\Migrations\RepeatableMigrationInterface; class Version20200203000000 extends AbstractMigration implements RepeatableMigrationInterface { public function upgradeDatabase() { $this->refreshEntities([ RefreshToken::class, ]); } }
biplobice/concrete5
concrete/src/Updater/Migrations/Migrations/Version20200203000000.php
PHP
mit
457
// // DGActivityIndicatorTripleRingsPulseAnimation.h // DGActivityIndicatorExample // // Created by tripleCC on 15/6/28. // Copyright (c) 2015年 Danil Gontovnik. All rights reserved. // #import "DGActivityIndicatorAnimation.h" @interface DGActivityIndicatorTripleRingsAnimation: DGActivityIndicatorAnimation @end
YahyaBagia/YBHud
YBHud/DGActivityIndicatorView/Animations/DGActivityIndicatorTripleRingsAnimation.h
C
mit
320
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2015 Google Inc. http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BASIC_EXAMPLE_H #define BASIC_EXAMPLE_H class CommonExampleInterface* BasicExampleCreateFunc(struct CommonExampleOptions& options); #endif //BASIC_DEMO_PHYSICS_SETUP_H
blackspotbear/MMDViewer
third-party/bullet3-2.83.7/examples/BasicDemo/BasicExample.h
C
mit
1,111
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Versioning; #if BIT64 using nint = System.Int64; #else using nint = System.Int32; #endif namespace System { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct IntPtr : IEquatable<IntPtr>, ISerializable { // WARNING: We allow diagnostic tools to directly inspect this member (_value). // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. // Get in touch with the diagnostics team if you have questions. unsafe private void* _value; // Do not rename (binary serialization) [Intrinsic] public static readonly IntPtr Zero; [Intrinsic] [NonVersionable] public unsafe IntPtr(int value) { _value = (void*)value; } [Intrinsic] [NonVersionable] public unsafe IntPtr(long value) { #if BIT64 _value = (void*)value; #else _value = (void*)checked((int)value); #endif } [CLSCompliant(false)] [Intrinsic] [NonVersionable] public unsafe IntPtr(void* value) { _value = value; } private unsafe IntPtr(SerializationInfo info, StreamingContext context) { long l = info.GetInt64("value"); if (Size == 4 && (l > int.MaxValue || l < int.MinValue)) throw new ArgumentException(SR.Serialization_InvalidPtrValue); _value = (void*)l; } unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); info.AddValue("value", ToInt64()); } public unsafe override bool Equals(Object obj) { if (obj is IntPtr) { return (_value == ((IntPtr)obj)._value); } return false; } unsafe bool IEquatable<IntPtr>.Equals(IntPtr value) { return _value == value._value; } public unsafe override int GetHashCode() { #if BIT64 long l = (long)_value; return (unchecked((int)l) ^ (int)(l >> 32)); #else return unchecked((int)_value); #endif } [Intrinsic] [NonVersionable] public unsafe int ToInt32() { #if BIT64 long l = (long)_value; return checked((int)l); #else return (int)_value; #endif } [Intrinsic] [NonVersionable] public unsafe long ToInt64() { return (nint)_value; } [Intrinsic] [NonVersionable] public static unsafe explicit operator IntPtr(int value) { return new IntPtr(value); } [Intrinsic] [NonVersionable] public static unsafe explicit operator IntPtr(long value) { return new IntPtr(value); } [CLSCompliant(false)] [Intrinsic] [NonVersionable] public static unsafe explicit operator IntPtr(void* value) { return new IntPtr(value); } [CLSCompliant(false)] [Intrinsic] [NonVersionable] public static unsafe explicit operator void* (IntPtr value) { return value._value; } [Intrinsic] [NonVersionable] public static unsafe explicit operator int(IntPtr value) { #if BIT64 long l = (long)value._value; return checked((int)l); #else return (int)value._value; #endif } [Intrinsic] [NonVersionable] public static unsafe explicit operator long(IntPtr value) { return (nint)value._value; } [Intrinsic] [NonVersionable] public static unsafe bool operator ==(IntPtr value1, IntPtr value2) { return value1._value == value2._value; } [Intrinsic] [NonVersionable] public static unsafe bool operator !=(IntPtr value1, IntPtr value2) { return value1._value != value2._value; } [NonVersionable] public static IntPtr Add(IntPtr pointer, int offset) { return pointer + offset; } [Intrinsic] [NonVersionable] public static unsafe IntPtr operator +(IntPtr pointer, int offset) { return new IntPtr((nint)pointer._value + offset); } [NonVersionable] public static IntPtr Subtract(IntPtr pointer, int offset) { return pointer - offset; } [Intrinsic] [NonVersionable] public static unsafe IntPtr operator -(IntPtr pointer, int offset) { return new IntPtr((nint)pointer._value - offset); } public static int Size { [Intrinsic] [NonVersionable] get { return sizeof(nint); } } [CLSCompliant(false)] [Intrinsic] [NonVersionable] public unsafe void* ToPointer() { return _value; } public unsafe override string ToString() { return ((nint)_value).ToString(CultureInfo.InvariantCulture); } public unsafe string ToString(string format) { return ((nint)_value).ToString(format, CultureInfo.InvariantCulture); } } }
ruben-ayrapetyan/coreclr
src/mscorlib/shared/System/IntPtr.cs
C#
mit
6,210
/** * videojs-flash * @version 1.0.0-RC.1 * @copyright 2017 Brightcove, Inc. * @license Apache-2.0 */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.videojsFlash = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ 'use strict'; exports.__esModule = true; /** * @file flash-rtmp.js * @module flash-rtmp */ /** * Add RTMP properties to the {@link Flash} Tech. * * @param {Flash} Flash * The flash tech class. * * @mixin FlashRtmpDecorator */ function FlashRtmpDecorator(Flash) { Flash.streamingFormats = { 'rtmp/mp4': 'MP4', 'rtmp/flv': 'FLV' }; /** * Join connection and stream with an ampersand. * * @param {string} connection * The connection string. * * @param {string} stream * The stream string. */ Flash.streamFromParts = function (connection, stream) { return connection + '&' + stream; }; /** * The flash parts object that contains connection and stream info. * * @typedef {Object} Flash~PartsObject * * @property {string} connection * The connection string of a source, defaults to an empty string. * * @property {string} stream * The stream string of the source, defaults to an empty string. */ /** * Convert a source url into a stream and connection parts. * * @param {string} src * the source url * * @return {Flash~PartsObject} * The parts object that contains a connection and a stream */ Flash.streamToParts = function (src) { var parts = { connection: '', stream: '' }; if (!src) { return parts; } // Look for the normal URL separator we expect, '&'. // If found, we split the URL into two pieces around the // first '&'. var connEnd = src.search(/&(?!\w+=)/); var streamBegin = void 0; if (connEnd !== -1) { streamBegin = connEnd + 1; } else { // If there's not a '&', we use the last '/' as the delimiter. connEnd = streamBegin = src.lastIndexOf('/') + 1; if (connEnd === 0) { // really, there's not a '/'? connEnd = streamBegin = src.length; } } parts.connection = src.substring(0, connEnd); parts.stream = src.substring(streamBegin, src.length); return parts; }; /** * Check if the source type is a streaming type. * * @param {string} srcType * The mime type to check. * * @return {boolean} * - True if the source type is a streaming type. * - False if the source type is not a streaming type. */ Flash.isStreamingType = function (srcType) { return srcType in Flash.streamingFormats; }; // RTMP has four variations, any string starting // with one of these protocols should be valid /** * Regular expression used to check if the source is an rtmp source. * * @property {RegExp} Flash.RTMP_RE */ Flash.RTMP_RE = /^rtmp[set]?:\/\//i; /** * Check if the source itself is a streaming type. * * @param {string} src * The url to the source. * * @return {boolean} * - True if the source url indicates that the source is streaming. * - False if the shource url indicates that the source url is not streaming. */ Flash.isStreamingSrc = function (src) { return Flash.RTMP_RE.test(src); }; /** * A source handler for RTMP urls * @type {Object} */ Flash.rtmpSourceHandler = {}; /** * Check if Flash can play the given mime type. * * @param {string} type * The mime type to check * * @return {string} * 'maybe', or '' (empty string) */ Flash.rtmpSourceHandler.canPlayType = function (type) { if (Flash.isStreamingType(type)) { return 'maybe'; } return ''; }; /** * Check if Flash can handle the source natively * * @param {Object} source * The source object * * @param {Object} [options] * The options passed to the tech * * @return {string} * 'maybe', or '' (empty string) */ Flash.rtmpSourceHandler.canHandleSource = function (source, options) { var can = Flash.rtmpSourceHandler.canPlayType(source.type); if (can) { return can; } if (Flash.isStreamingSrc(source.src)) { return 'maybe'; } return ''; }; /** * Pass the source to the flash object. * * @param {Object} source * The source object * * @param {Flash} tech * The instance of the Flash tech * * @param {Object} [options] * The options to pass to the source */ Flash.rtmpSourceHandler.handleSource = function (source, tech, options) { var srcParts = Flash.streamToParts(source.src); tech.setRtmpConnection(srcParts.connection); tech.setRtmpStream(srcParts.stream); }; // Register the native source handler Flash.registerSourceHandler(Flash.rtmpSourceHandler); return Flash; } exports['default'] = FlashRtmpDecorator; },{}],2:[function(require,module,exports){ (function (global){ if (typeof window !== "undefined") { module.exports = window; } else if (typeof global !== "undefined") { module.exports = global; } else if (typeof self !== "undefined"){ module.exports = self; } else { module.exports = {}; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],3:[function(require,module,exports){ module.exports={ "name": "videojs-swf", "description": "The Flash-fallback video player for video.js (http://videojs.com)", "version": "5.2.0", "copyright": "Copyright 2014 Brightcove, Inc. https://github.com/videojs/video-js-swf/blob/master/LICENSE", "keywords": [ "flash", "video", "player" ], "homepage": "http://videojs.com", "author": { "name": "Brightcove" }, "repository": { "type": "git", "url": "git+https://github.com/videojs/video-js-swf.git" }, "devDependencies": { "async": "~0.2.9", "chg": "^0.3.2", "flex-sdk": "4.6.0-0", "grunt": "~0.4.0", "grunt-bumpup": "~0.5.0", "grunt-cli": "~0.1.0", "grunt-connect": "~0.2.0", "grunt-contrib-jshint": "~0.4.3", "grunt-contrib-qunit": "~0.2.1", "grunt-contrib-watch": "~0.1.4", "grunt-npm": "~0.0.2", "grunt-prompt": "~0.1.2", "grunt-shell": "~0.6.1", "grunt-tagrelease": "~0.3.1", "qunitjs": "~1.12.0", "video.js": "^5.9.2" }, "scripts": { "version": "chg release -y && grunt dist && git add -f dist/ && git add CHANGELOG.md" }, "gitHead": "b903e6abdb2a1b1565dee8e550bcbecb655d27c2", "bugs": { "url": "https://github.com/videojs/video-js-swf/issues" }, "_id": "videojs-swf@5.2.0", "_shasum": "ae20a60f8dc7746ce52de845b51dd46798ea5cfa", "_from": "videojs-swf@>=5.2.0 <6.0.0", "_npmVersion": "2.15.6", "_nodeVersion": "4.4.3", "_npmUser": { "name": "gkatsev", "email": "me@gkatsev.com" }, "dist": { "shasum": "ae20a60f8dc7746ce52de845b51dd46798ea5cfa", "tarball": "https://registry.npmjs.org/videojs-swf/-/videojs-swf-5.2.0.tgz" }, "maintainers": [ { "name": "heff", "email": "npm@heff.me" }, { "name": "seniorflexdeveloper", "email": "seniorflexdeveloper@gmail.com" }, { "name": "gkatsev", "email": "me@gkatsev.com" }, { "name": "dmlap", "email": "dlapalomento@gmail.com" }, { "name": "bclwhitaker", "email": "lwhitaker@brightcove.com" } ], "_npmOperationalInternal": { "host": "packages-18-east.internal.npmjs.com", "tmp": "tmp/videojs-swf-5.2.0.tgz_1486496894096_0.4415081855840981" }, "directories": {}, "_resolved": "https://registry.npmjs.org/videojs-swf/-/videojs-swf-5.2.0.tgz", "readme": "ERROR: No README data found!" } },{}],4:[function(require,module,exports){ (function (global){ 'use strict'; exports.__esModule = true; var _video = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null); var _video2 = _interopRequireDefault(_video); var _rtmp = require('./rtmp'); var _rtmp2 = _interopRequireDefault(_rtmp); var _window = require('global/window'); var _window2 = _interopRequireDefault(_window); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file flash.js * VideoJS-SWF - Custom Flash Player with HTML5-ish API * https://github.com/zencoder/video-js-swf * Not using setupTriggers. Using global onEvent func to distribute events */ var Tech = _video2['default'].getComponent('Tech'); var Dom = _video2['default'].dom; var Url = _video2['default'].url; var createTimeRange = _video2['default'].createTimeRange; var mergeOptions = _video2['default'].mergeOptions; var navigator = _window2['default'].navigator; /** * Flash Media Controller - Wrapper for Flash Media API * * @mixes FlashRtmpDecorator * @mixes Tech~SouceHandlerAdditions * @extends Tech */ var Flash = function (_Tech) { _inherits(Flash, _Tech); /** * Create an instance of this Tech. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} ready * Callback function to call when the `Flash` Tech is ready. */ function Flash(options, ready) { _classCallCheck(this, Flash); // Set the source when ready var _this = _possibleConstructorReturn(this, _Tech.call(this, options, ready)); if (options.source) { _this.ready(function () { this.setSource(options.source); }, true); } // Having issues with Flash reloading on certain page actions (hide/resize/fullscreen) in certain browsers // This allows resetting the playhead when we catch the reload if (options.startTime) { _this.ready(function () { this.load(); this.play(); this.currentTime(options.startTime); }, true); } // Add global window functions that the swf expects // A 4.x workflow we weren't able to solve for in 5.0 // because of the need to hard code these functions // into the swf for security reasons _window2['default'].videojs = _window2['default'].videojs || {}; _window2['default'].videojs.Flash = _window2['default'].videojs.Flash || {}; _window2['default'].videojs.Flash.onReady = Flash.onReady; _window2['default'].videojs.Flash.onEvent = Flash.onEvent; _window2['default'].videojs.Flash.onError = Flash.onError; _this.on('seeked', function () { this.lastSeekTarget_ = undefined; }); return _this; } /** * Create the `Flash` Tech's DOM element. * * @return {Element} * The element that gets created. */ Flash.prototype.createEl = function createEl() { var options = this.options_; // If video.js is hosted locally you should also set the location // for the hosted swf, which should be relative to the page (not video.js) // Otherwise this adds a CDN url. // The CDN also auto-adds a swf URL for that specific version. if (!options.swf) { var ver = require('videojs-swf/package.json').version; options.swf = '//vjs.zencdn.net/swf/' + ver + '/video-js.swf'; } // Generate ID for swf object var objId = options.techId; // Merge default flashvars with ones passed in to init var flashVars = mergeOptions({ // SWF Callback Functions readyFunction: 'videojs.Flash.onReady', eventProxyFunction: 'videojs.Flash.onEvent', errorEventProxyFunction: 'videojs.Flash.onError', // Player Settings autoplay: options.autoplay, preload: options.preload, loop: options.loop, muted: options.muted }, options.flashVars); // Merge default parames with ones passed in var params = mergeOptions({ // Opaque is needed to overlay controls, but can affect playback performance wmode: 'opaque', // Using bgcolor prevents a white flash when the object is loading bgcolor: '#000000' }, options.params); // Merge default attributes with ones passed in var attributes = mergeOptions({ // Both ID and Name needed or swf to identify itself id: objId, name: objId, 'class': 'vjs-tech' }, options.attributes); this.el_ = Flash.embed(options.swf, flashVars, params, attributes); this.el_.tech = this; return this.el_; }; /** * Called by {@link Player#play} to play using the `Flash` `Tech`. */ Flash.prototype.play = function play() { if (this.ended()) { this.setCurrentTime(0); } this.el_.vjs_play(); }; /** * Called by {@link Player#pause} to pause using the `Flash` `Tech`. */ Flash.prototype.pause = function pause() { this.el_.vjs_pause(); }; /** * A getter/setter for the `Flash` Tech's source object. * > Note: Please use {@link Flash#setSource} * * @param {Tech~SourceObject} [src] * The source object you want to set on the `Flash` techs. * * @return {Tech~SourceObject|undefined} * - The current source object when a source is not passed in. * - undefined when setting * * @deprecated Since version 5. */ Flash.prototype.src = function src(_src) { if (_src === undefined) { return this.currentSrc(); } // Setting src through `src` not `setSrc` will be deprecated return this.setSrc(_src); }; /** * A getter/setter for the `Flash` Tech's source object. * * @param {Tech~SourceObject} [src] * The source object you want to set on the `Flash` techs. * * @return {Tech~SourceObject|undefined} * - The current source object when a source is not passed in. * - undefined when setting */ Flash.prototype.setSrc = function setSrc(src) { var _this2 = this; // Make sure source URL is absolute. src = Url.getAbsoluteURL(src); this.el_.vjs_src(src); // Currently the SWF doesn't autoplay if you load a source later. // e.g. Load player w/ no source, wait 2s, set src. if (this.autoplay()) { this.setTimeout(function () { return _this2.play(); }, 0); } }; /** * Indicates whether the media is currently seeking to a new position or not. * * @return {boolean} * - True if seeking to a new position * - False otherwise */ Flash.prototype.seeking = function seeking() { return this.lastSeekTarget_ !== undefined; }; /** * Returns the current time in seconds that the media is at in playback. * * @param {number} time * Current playtime of the media in seconds. */ Flash.prototype.setCurrentTime = function setCurrentTime(time) { var seekable = this.seekable(); if (seekable.length) { // clamp to the current seekable range time = time > seekable.start(0) ? time : seekable.start(0); time = time < seekable.end(seekable.length - 1) ? time : seekable.end(seekable.length - 1); this.lastSeekTarget_ = time; this.trigger('seeking'); this.el_.vjs_setProperty('currentTime', time); _Tech.prototype.setCurrentTime.call(this); } }; /** * Get the current playback time in seconds * * @return {number} * The current time of playback in seconds. */ Flash.prototype.currentTime = function currentTime() { // when seeking make the reported time keep up with the requested time // by reading the time we're seeking to if (this.seeking()) { return this.lastSeekTarget_ || 0; } return this.el_.vjs_getProperty('currentTime'); }; /** * Get the current source * * @method currentSrc * @return {Tech~SourceObject} * The current source */ Flash.prototype.currentSrc = function currentSrc() { if (this.currentSource_) { return this.currentSource_.src; } return this.el_.vjs_getProperty('currentSrc'); }; /** * Get the total duration of the current media. * * @return {number} 8 The total duration of the current media. */ Flash.prototype.duration = function duration() { if (this.readyState() === 0) { return NaN; } var duration = this.el_.vjs_getProperty('duration'); return duration >= 0 ? duration : Infinity; }; /** * Load media into Tech. */ Flash.prototype.load = function load() { this.el_.vjs_load(); }; /** * Get the poster image that was set on the tech. */ Flash.prototype.poster = function poster() { this.el_.vjs_getProperty('poster'); }; /** * Poster images are not handled by the Flash tech so make this is a no-op. */ Flash.prototype.setPoster = function setPoster() {}; /** * Determine the time ranges that can be seeked to in the media. * * @return {TimeRange} * Returns the time ranges that can be seeked to. */ Flash.prototype.seekable = function seekable() { var duration = this.duration(); if (duration === 0) { return createTimeRange(); } return createTimeRange(0, duration); }; /** * Get and create a `TimeRange` object for buffering. * * @return {TimeRange} * The time range object that was created. */ Flash.prototype.buffered = function buffered() { var ranges = this.el_.vjs_getProperty('buffered'); if (ranges.length === 0) { return createTimeRange(); } return createTimeRange(ranges[0][0], ranges[0][1]); }; /** * Get fullscreen support - * * Flash does not allow fullscreen through javascript * so this always returns false. * * @return {boolean} * The Flash tech does not support fullscreen, so it will always return false. */ Flash.prototype.supportsFullScreen = function supportsFullScreen() { // Flash does not allow fullscreen through javascript return false; }; /** * Flash does not allow fullscreen through javascript * so this always returns false. * * @return {boolean} * The Flash tech does not support fullscreen, so it will always return false. */ Flash.prototype.enterFullScreen = function enterFullScreen() { return false; }; return Flash; }(Tech); // Create setters and getters for attributes var _readWrite = ['rtmpConnection', 'rtmpStream', 'preload', 'defaultPlaybackRate', 'playbackRate', 'autoplay', 'loop', 'controls', 'volume', 'muted', 'defaultMuted']; var _readOnly = ['networkState', 'readyState', 'initialTime', 'startOffsetTime', 'paused', 'ended', 'videoWidth', 'videoHeight']; var _api = Flash.prototype; function _createSetter(attr) { var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1); _api['set' + attrUpper] = function (val) { return this.el_.vjs_setProperty(attr, val); }; } function _createGetter(attr) { _api[attr] = function () { return this.el_.vjs_getProperty(attr); }; } // Create getter and setters for all read/write attributes for (var i = 0; i < _readWrite.length; i++) { _createGetter(_readWrite[i]); _createSetter(_readWrite[i]); } // Create getters for read-only attributes for (var _i = 0; _i < _readOnly.length; _i++) { _createGetter(_readOnly[_i]); } /** ------------------------------ Getters ------------------------------ **/ /** * Get the value of `rtmpConnection` from the swf. * * @method Flash#rtmpConnection * @return {string} * The current value of `rtmpConnection` on the swf. */ /** * Get the value of `rtmpStream` from the swf. * * @method Flash#rtmpStream * @return {string} * The current value of `rtmpStream` on the swf. */ /** * Get the value of `preload` from the swf. `preload` indicates * what should download before the media is interacted with. It can have the following * values: * - none: nothing should be downloaded * - metadata: poster and the first few frames of the media may be downloaded to get * media dimensions and other metadata * - auto: allow the media and metadata for the media to be downloaded before * interaction * * @method Flash#preload * @return {string} * The value of `preload` from the swf. Will be 'none', 'metadata', * or 'auto'. */ /** * Get the value of `defaultPlaybackRate` from the swf. * * @method Flash#defaultPlaybackRate * @return {number} * The current value of `defaultPlaybackRate` on the swf. */ /** * Get the value of `playbackRate` from the swf. `playbackRate` indicates * the rate at which the media is currently playing back. Examples: * - if playbackRate is set to 2, media will play twice as fast. * - if playbackRate is set to 0.5, media will play half as fast. * * @method Flash#playbackRate * @return {number} * The value of `playbackRate` from the swf. A number indicating * the current playback speed of the media, where 1 is normal speed. */ /** * Get the value of `autoplay` from the swf. `autoplay` indicates * that the media should start to play as soon as the page is ready. * * @method Flash#autoplay * @return {boolean} * - The value of `autoplay` from the swf. * - True indicates that the media ashould start as soon as the page loads. * - False indicates that the media should not start as soon as the page loads. */ /** * Get the value of `loop` from the swf. `loop` indicates * that the media should return to the start of the media and continue playing once * it reaches the end. * * @method Flash#loop * @return {boolean} * - The value of `loop` from the swf. * - True indicates that playback should seek back to start once * the end of a media is reached. * - False indicates that playback should not loop back to the start when the * end of the media is reached. */ /** * Get the value of `mediaGroup` from the swf. * * @method Flash#mediaGroup * @return {string} * The current value of `mediaGroup` on the swf. */ /** * Get the value of `controller` from the swf. * * @method Flash#controller * @return {string} * The current value of `controller` on the swf. */ /** * Get the value of `controls` from the swf. `controls` indicates * whether the native flash controls should be shown or hidden. * * @method Flash#controls * @return {boolean} * - The value of `controls` from the swf. * - True indicates that native controls should be showing. * - False indicates that native controls should be hidden. */ /** * Get the value of the `volume` from the swf. `volume` indicates the current * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and * so on. * * @method Flash#volume * @return {number} * The volume percent as a decimal. Value will be between 0-1. */ /** * Get the value of the `muted` from the swf. `muted` indicates the current * audio level should be silent. * * @method Flash#muted * @return {boolean} * - True if the audio should be set to silent * - False otherwise */ /** * Get the value of `defaultMuted` from the swf. `defaultMuted` indicates * whether the media should start muted or not. Only changes the default state of the * media. `muted` and `defaultMuted` can have different values. `muted` indicates the * current state. * * @method Flash#defaultMuted * @return {boolean} * - The value of `defaultMuted` from the swf. * - True indicates that the media should start muted. * - False indicates that the media should not start muted. */ /** * Get the value of `networkState` from the swf. `networkState` indicates * the current network state. It returns an enumeration from the following list: * - 0: NETWORK_EMPTY * - 1: NEWORK_IDLE * - 2: NETWORK_LOADING * - 3: NETWORK_NO_SOURCE * * @method Flash#networkState * @return {number} * The value of `networkState` from the swf. This will be a number * from the list in the description. */ /** * Get the value of `readyState` from the swf. `readyState` indicates * the current state of the media element. It returns an enumeration from the * following list: * - 0: HAVE_NOTHING * - 1: HAVE_METADATA * - 2: HAVE_CURRENT_DATA * - 3: HAVE_FUTURE_DATA * - 4: HAVE_ENOUGH_DATA * * @method Flash#readyState * @return {number} * The value of `readyState` from the swf. This will be a number * from the list in the description. */ /** * Get the value of `readyState` from the swf. `readyState` indicates * the current state of the media element. It returns an enumeration from the * following list: * - 0: HAVE_NOTHING * - 1: HAVE_METADATA * - 2: HAVE_CURRENT_DATA * - 3: HAVE_FUTURE_DATA * - 4: HAVE_ENOUGH_DATA * * @method Flash#readyState * @return {number} * The value of `readyState` from the swf. This will be a number * from the list in the description. */ /** * Get the value of `initialTime` from the swf. * * @method Flash#initialTime * @return {number} * The `initialTime` proprety on the swf. */ /** * Get the value of `startOffsetTime` from the swf. * * @method Flash#startOffsetTime * @return {number} * The `startOffsetTime` proprety on the swf. */ /** * Get the value of `paused` from the swf. `paused` indicates whether the swf * is current paused or not. * * @method Flash#paused * @return {boolean} * The value of `paused` from the swf. */ /** * Get the value of `ended` from the swf. `ended` indicates whether * the media has reached the end or not. * * @method Flash#ended * @return {boolean} * - True indicates that the media has ended. * - False indicates that the media has not ended. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended} */ /** * Get the value of `videoWidth` from the swf. `videoWidth` indicates * the current width of the media in css pixels. * * @method Flash#videoWidth * @return {number} * The value of `videoWidth` from the swf. This will be a number * in css pixels. */ /** * Get the value of `videoHeight` from the swf. `videoHeigth` indicates * the current height of the media in css pixels. * * @method Flassh.prototype.videoHeight * @return {number} * The value of `videoHeight` from the swf. This will be a number * in css pixels. */ /** ------------------------------ Setters ------------------------------ **/ /** * Set the value of `rtmpConnection` on the swf. * * @method Flash#setRtmpConnection * @param {string} rtmpConnection * New value to set the `rtmpConnection` property to. */ /** * Set the value of `rtmpStream` on the swf. * * @method Flash#setRtmpStream * @param {string} rtmpStream * New value to set the `rtmpStream` property to. */ /** * Set the value of `preload` on the swf. `preload` indicates * what should download before the media is interacted with. It can have the following * values: * - none: nothing should be downloaded * - metadata: poster and the first few frames of the media may be downloaded to get * media dimensions and other metadata * - auto: allow the media and metadata for the media to be downloaded before * interaction * * @method Flash#setPreload * @param {string} preload * The value of `preload` to set on the swf. Should be 'none', 'metadata', * or 'auto'. */ /** * Set the value of `defaultPlaybackRate` on the swf. * * @method Flash#setDefaultPlaybackRate * @param {number} defaultPlaybackRate * New value to set the `defaultPlaybackRate` property to. */ /** * Set the value of `playbackRate` on the swf. `playbackRate` indicates * the rate at which the media is currently playing back. Examples: * - if playbackRate is set to 2, media will play twice as fast. * - if playbackRate is set to 0.5, media will play half as fast. * * @method Flash#setPlaybackRate * @param {number} playbackRate * New value of `playbackRate` on the swf. A number indicating * the current playback speed of the media, where 1 is normal speed. */ /** * Set the value of `autoplay` on the swf. `autoplay` indicates * that the media should start to play as soon as the page is ready. * * @method Flash#setAutoplay * @param {boolean} autoplay * - The value of `autoplay` from the swf. * - True indicates that the media ashould start as soon as the page loads. * - False indicates that the media should not start as soon as the page loads. */ /** * Set the value of `loop` on the swf. `loop` indicates * that the media should return to the start of the media and continue playing once * it reaches the end. * * @method Flash#setLoop * @param {boolean} loop * - True indicates that playback should seek back to start once * the end of a media is reached. * - False indicates that playback should not loop back to the start when the * end of the media is reached. */ /** * Set the value of `mediaGroup` on the swf. * * @method Flash#setMediaGroup * @param {string} mediaGroup * New value of `mediaGroup` to set on the swf. */ /** * Set the value of `controller` on the swf. * * @method Flash#setController * @param {string} controller * New value the current value of `controller` on the swf. */ /** * Get the value of `controls` from the swf. `controls` indicates * whether the native flash controls should be shown or hidden. * * @method Flash#controls * @return {boolean} * - The value of `controls` from the swf. * - True indicates that native controls should be showing. * - False indicates that native controls should be hidden. */ /** * Set the value of the `volume` on the swf. `volume` indicates the current * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and * so on. * * @method Flash#setVolume * @param {number} percentAsDecimal * The volume percent as a decimal. Value will be between 0-1. */ /** * Set the value of the `muted` on the swf. `muted` indicates that the current * audio level should be silent. * * @method Flash#setMuted * @param {boolean} muted * - True if the audio should be set to silent * - False otherwise */ /** * Set the value of `defaultMuted` on the swf. `defaultMuted` indicates * whether the media should start muted or not. Only changes the default state of the * media. `muted` and `defaultMuted` can have different values. `muted` indicates the * current state. * * @method Flash#setDefaultMuted * @param {boolean} defaultMuted * - True indicates that the media should start muted. * - False indicates that the media should not start muted. */ /* Flash Support Testing -------------------------------------------------------- */ /** * Check if the Flash tech is currently supported. * * @return {boolean} * - True if the flash tech is supported. * - False otherwise. */ Flash.isSupported = function () { return Flash.version()[0] >= 10; // return swfobject.hasFlashPlayerVersion('10'); }; // Add Source Handler pattern functions to this tech Tech.withSourceHandlers(Flash); /* * Native source handler for flash, simply passes the source to the swf element. * * @property {Tech~SourceObject} source * The source object * * @property {Flash} tech * The instance of the Flash tech */ Flash.nativeSourceHandler = {}; /** * Check if the Flash can play the given mime type. * * @param {string} type * The mimetype to check * * @return {string} * 'maybe', or '' (empty string) */ Flash.nativeSourceHandler.canPlayType = function (type) { if (type in Flash.formats) { return 'maybe'; } return ''; }; /** * Check if the media element can handle a source natively. * * @param {Tech~SourceObject} source * The source object * * @param {Object} [options] * Options to be passed to the tech. * * @return {string} * 'maybe', or '' (empty string). */ Flash.nativeSourceHandler.canHandleSource = function (source, options) { var type = void 0; function guessMimeType(src) { var ext = Url.getFileExtension(src); if (ext) { return 'video/' + ext; } return ''; } if (!source.type) { type = guessMimeType(source.src); } else { // Strip code information from the type because we don't get that specific type = source.type.replace(/;.*/, '').toLowerCase(); } return Flash.nativeSourceHandler.canPlayType(type); }; /** * Pass the source to the swf. * * @param {Tech~SourceObject} source * The source object * * @param {Flash} tech * The instance of the Flash tech * * @param {Object} [options] * The options to pass to the source */ Flash.nativeSourceHandler.handleSource = function (source, tech, options) { tech.setSrc(source.src); }; /** * noop for native source handler dispose, as cleanup will happen automatically. */ Flash.nativeSourceHandler.dispose = function () {}; // Register the native source handler Flash.registerSourceHandler(Flash.nativeSourceHandler); /** * Flash supported mime types. * * @constant {Object} */ Flash.formats = { 'video/flv': 'FLV', 'video/x-flv': 'FLV', 'video/mp4': 'MP4', 'video/m4v': 'MP4' }; /** * Called when the the swf is "ready", and makes sure that the swf is really * ready using {@link Flash#checkReady} */ Flash.onReady = function (currSwf) { var el = Dom.$('#' + currSwf); var tech = el && el.tech; // if there is no el then the tech has been disposed // and the tech element was removed from the player div if (tech && tech.el()) { // check that the flash object is really ready Flash.checkReady(tech); } }; /** * The SWF isn't always ready when it says it is. Sometimes the API functions still * need to be added to the object. If it's not ready, we set a timeout to check again * shortly. * * @param {Flash} tech * The instance of the flash tech to check. */ Flash.checkReady = function (tech) { // stop worrying if the tech has been disposed if (!tech.el()) { return; } // check if API property exists if (tech.el().vjs_getProperty) { // tell tech it's ready tech.triggerReady(); } else { // wait longer this.setTimeout(function () { Flash.checkReady(tech); }, 50); } }; /** * Trigger events from the swf on the Flash Tech. * * @param {number} swfID * The id of the swf that had the event * * @param {string} eventName * The name of the event to trigger */ Flash.onEvent = function (swfID, eventName) { var tech = Dom.$('#' + swfID).tech; var args = Array.prototype.slice.call(arguments, 2); // dispatch Flash events asynchronously for two reasons: // - Flash swallows any exceptions generated by javascript it // invokes // - Flash is suspended until the javascript returns which may cause // playback performance issues tech.setTimeout(function () { tech.trigger(eventName, args); }, 1); }; /** * Log errors from the swf on the Flash tech. * * @param {number} swfID * The id of the swf that had an error. * * @param {string} The error string * The error to set on the Flash Tech. * * @return {MediaError|undefined} * - Returns a MediaError when err is 'srcnotfound' * - Returns undefined otherwise. */ Flash.onError = function (swfID, err) { var tech = Dom.$('#' + swfID).tech; // trigger MEDIA_ERR_SRC_NOT_SUPPORTED if (err === 'srcnotfound') { return tech.error(4); } // trigger a custom error tech.error('FLASH: ' + err); }; /** * Get the current version of Flash that is in use on the page. * * @return {Array} * an array of versions that are available. */ Flash.version = function () { var version = '0,0,0'; // IE try { version = new _window2['default'].ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; // other browsers } catch (e) { try { if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) { version = (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; } } catch (err) { // satisfy linter } } return version.split(','); }; /** * Only use for non-iframe embeds. * * @param {Object} swf * The videojs-swf object. * * @param {Object} flashVars * Names and values to use as flash option variables. * * @param {Object} params * Style parameters to set on the object. * * @param {Object} attributes * Attributes to set on the element. * * @return {Element} * The embeded Flash DOM element. */ Flash.embed = function (swf, flashVars, params, attributes) { var code = Flash.getEmbedCode(swf, flashVars, params, attributes); // Get element by embedding code and retrieving created element var obj = Dom.createEl('div', { innerHTML: code }).childNodes[0]; return obj; }; /** * Only use for non-iframe embeds. * * @param {Object} swf * The videojs-swf object. * * @param {Object} flashVars * Names and values to use as flash option variables. * * @param {Object} params * Style parameters to set on the object. * * @param {Object} attributes * Attributes to set on the element. * * @return {Element} * The embeded Flash DOM element. */ Flash.getEmbedCode = function (swf, flashVars, params, attributes) { var objTag = '<object type="application/x-shockwave-flash" '; var flashVarsString = ''; var paramsString = ''; var attrsString = ''; // Convert flash vars to string if (flashVars) { Object.getOwnPropertyNames(flashVars).forEach(function (key) { flashVarsString += key + '=' + flashVars[key] + '&amp;'; }); } // Add swf, flashVars, and other default params params = mergeOptions({ movie: swf, flashvars: flashVarsString, // Required to talk to swf allowScriptAccess: 'always', // All should be default, but having security issues. allowNetworking: 'all' }, params); // Create param tags string Object.getOwnPropertyNames(params).forEach(function (key) { paramsString += '<param name="' + key + '" value="' + params[key] + '" />'; }); attributes = mergeOptions({ // Add swf to attributes (need both for IE and Others to work) data: swf, // Default to 100% width/height width: '100%', height: '100%' }, attributes); // Create Attributes string Object.getOwnPropertyNames(attributes).forEach(function (key) { attrsString += key + '="' + attributes[key] + '" '; }); return '' + objTag + attrsString + '>' + paramsString + '</object>'; }; // Run Flash through the RTMP decorator (0, _rtmp2['default'])(Flash); if (Tech.getTech('Flash')) { _video2['default'].log.warn('Not using videojs-flash as it appears to already be registered'); _video2['default'].log.warn('videojs-flash should only be used with video.js@6 and above'); } else { _video2['default'].registerTech('Flash', Flash); } exports['default'] = Flash; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./rtmp":1,"global/window":2,"videojs-swf/package.json":3}]},{},[4])(4) });
joeyparrish/cdnjs
ajax/libs/videojs-flash/1.0.0-RC.1/videojs-flash.js
JavaScript
mit
43,823
/* Copyright (c) 2006-2007 Christopher J. W. Lloyd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #import <Foundation/Foundation.h> @class NSFont, NSFontDescriptor, NSFontPanel; typedef unsigned NSFontTraitMask; typedef enum { NSNoFontChangeAction = 0, NSViaPanelFontAction = 1, NSAddTraitFontAction = 2, NSSizeUpFontAction = 3, NSSizeDownFontAction = 4, NSHeavierFontAction = 5, NSLighterFontAction = 6, NSRemoveTraitFontAction = 7, } NSFontAction; enum { NSItalicFontMask = 0x00000001, NSBoldFontMask = 0x00000002, NSUnboldFontMask = 0x00000004, NSNonStandardCharacterSetFontMask = 0x00000008, NSNarrowFontMask = 0x00000010, NSExpandedFontMask = 0x00000020, NSCondensedFontMask = 0x00000040, NSSmallCapsFontMask = 0x00000080, NSPosterFontMask = 0x00000100, NSCompressedFontMask = 0x00000200, NSFixedPitchFontMask = 0x00000400, NSUnitalicFontMask = 0x01000000, }; @interface NSFontManager : NSObject { NSFontPanel *_panel; id _delegate; SEL _action; NSFont *_selectedFont; BOOL _isMultiple; NSFontAction _currentFontAction; int _currentTrait; } + (NSFontManager *)sharedFontManager; + (void)setFontManagerFactory:(Class)value; + (void)setFontPanelFactory:(Class)value; - delegate; - (SEL)action; - (void)setDelegate:delegate; - (void)setAction:(SEL)value; - (NSFontAction)currentFontAction; - (NSArray *)collectionNames; - (BOOL)addCollection:(NSString *)name options:(int)options; - (void)addFontDescriptors:(NSArray *)descriptors toCollection:(NSString *)name; - (BOOL)removeCollection:(NSString *)name; - (NSArray *)fontDescriptorsInCollection:(NSString *)name; - (NSArray *)availableFonts; - (NSArray *)availableFontFamilies; - (NSArray *)availableMembersOfFontFamily:(NSString *)name; - (NSArray *)availableFontNamesMatchingFontDescriptor:(NSFontDescriptor *)descriptor; - (NSArray *)availableFontNamesWithTraits:(NSFontTraitMask)traits; - (BOOL)fontNamed:(NSString *)name hasTraits:(NSFontTraitMask)traits; - (NSFont *)fontWithFamily:(NSString *)family traits:(NSFontTraitMask)traits weight:(int)weight size:(float)size; - (int)weightOfFont:(NSFont *)font; - (NSFontTraitMask)traitsOfFont:(NSFont *)font; - (NSString *)localizedNameForFamily:(NSString *)family face:(NSString *)face; - (NSFontPanel *)fontPanel:(BOOL)create; - (BOOL)sendAction; - (BOOL)isEnabled; - (BOOL)isMultiple; - (NSFont *)selectedFont; - (void)setSelectedFont:(NSFont *)font isMultiple:(BOOL)isMultiple; - (NSFont *)convertFont:(NSFont *)font; - (NSFont *)convertFont:(NSFont *)font toSize:(float)size; - (NSFont *)convertFont:(NSFont *)font toHaveTrait:(NSFontTraitMask)trait; - (NSFont *)convertFont:(NSFont *)font toNotHaveTrait:(NSFontTraitMask)trait; - (NSFont *)convertFont:(NSFont *)font toFace:(NSString *)typeface; - (NSFont *)convertFont:(NSFont *)font toFamily:(NSString *)family; - (NSFont *)convertWeight:(BOOL)heavierNotLighter ofFont:(NSFont *)font; - (NSDictionary *)convertAttributes:(NSDictionary *)attributes; - (void)addFontTrait:sender; - (void)modifyFont:sender; - (void)modifyFontViaPanel:sender; - (void)removeFontTrait:sender; - (void)orderFrontFontPanel:sender; - (void)orderFrontStylesPanel:sender; @end @interface NSObject (NSFontManager_delegate) - (BOOL)fontManager:sender willIncludeFont:(NSString *)fontName; @end
yuhangwang/cocotron
AppKit/NSFontManager.h
C
mit
4,343