repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
scala-js/scala-js | javalib/src/main/scala/java/nio/DataViewDoubleBuffer.scala | 3428 | /*
* Scala.js (https://www.scala-js.org/)
*
* Copyright EPFL.
*
* Licensed under Apache License 2.0
* (https://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package java.nio
import scala.scalajs.js.typedarray._
private[nio] final class DataViewDoubleBuffer private (
override private[nio] val _dataView: DataView,
_initialPosition: Int, _initialLimit: Int, _readOnly: Boolean,
override private[nio] val isBigEndian: Boolean)
extends DoubleBuffer(_dataView.byteLength / 8, null, -1) {
position(_initialPosition)
limit(_initialLimit)
private[this] implicit def newDataViewDoubleBuffer =
DataViewDoubleBuffer.NewDataViewDoubleBuffer
def isReadOnly(): Boolean = _readOnly
def isDirect(): Boolean = true
@noinline
def slice(): DoubleBuffer =
GenDataViewBuffer(this).generic_slice()
@noinline
def duplicate(): DoubleBuffer =
GenDataViewBuffer(this).generic_duplicate()
@noinline
def asReadOnlyBuffer(): DoubleBuffer =
GenDataViewBuffer(this).generic_asReadOnlyBuffer()
@noinline
def get(): Double =
GenBuffer(this).generic_get()
@noinline
def put(d: Double): DoubleBuffer =
GenBuffer(this).generic_put(d)
@noinline
def get(index: Int): Double =
GenBuffer(this).generic_get(index)
@noinline
def put(index: Int, d: Double): DoubleBuffer =
GenBuffer(this).generic_put(index, d)
@noinline
override def get(dst: Array[Double], offset: Int, length: Int): DoubleBuffer =
GenBuffer(this).generic_get(dst, offset, length)
@noinline
override def put(src: Array[Double], offset: Int, length: Int): DoubleBuffer =
GenBuffer(this).generic_put(src, offset, length)
@noinline
def compact(): DoubleBuffer =
GenDataViewBuffer(this).generic_compact()
def order(): ByteOrder =
GenDataViewBuffer(this).generic_order()
// Internal API
@inline
override private[nio] def _arrayBuffer: ArrayBuffer =
GenDataViewBuffer(this).generic_arrayBuffer
@inline
override private[nio] def _arrayBufferOffset: Int =
GenDataViewBuffer(this).generic_arrayBufferOffset
@inline
private[nio] def load(index: Int): Double =
_dataView.getFloat64(8 * index, !isBigEndian)
@inline
private[nio] def store(index: Int, elem: Double): Unit =
_dataView.setFloat64(8 * index, elem, !isBigEndian)
@inline
override private[nio] def load(startIndex: Int,
dst: Array[Double], offset: Int, length: Int): Unit =
GenBuffer(this).generic_load(startIndex, dst, offset, length)
@inline
override private[nio] def store(startIndex: Int,
src: Array[Double], offset: Int, length: Int): Unit =
GenBuffer(this).generic_store(startIndex, src, offset, length)
}
private[nio] object DataViewDoubleBuffer {
private[nio] implicit object NewDataViewDoubleBuffer
extends GenDataViewBuffer.NewDataViewBuffer[DoubleBuffer] {
def bytesPerElem: Int = 8
def apply(dataView: DataView,
initialPosition: Int, initialLimit: Int,
readOnly: Boolean, isBigEndian: Boolean): DoubleBuffer = {
new DataViewDoubleBuffer(dataView,
initialPosition, initialLimit, readOnly, isBigEndian)
}
}
@inline
def fromTypedArrayByteBuffer(byteBuffer: TypedArrayByteBuffer): DoubleBuffer =
GenDataViewBuffer.generic_fromTypedArrayByteBuffer(byteBuffer)
}
| apache-2.0 |
meteorcloudy/bazel | src/test/java/com/google/devtools/build/lib/skyframe/FileStateValueTest.java | 2503 | // Copyright 2018 The Bazel 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.
package com.google.devtools.build.lib.skyframe;
import static org.mockito.Mockito.when;
import com.google.devtools.build.lib.actions.FileContentsProxy;
import com.google.devtools.build.lib.actions.FileStateValue;
import com.google.devtools.build.lib.skyframe.serialization.testutils.SerializationTester;
import com.google.devtools.build.lib.vfs.FileStatus;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mockito;
/** Tests for {@link FileStateValue}. */
@RunWith(JUnit4.class)
public class FileStateValueTest {
@Test
public void testCodec() throws Exception {
new SerializationTester(
new FileStateValue.RegularFileStateValue(
/*size=*/ 1, /*digest=*/ new byte[] {1, 2, 3}, /*contentsProxy=*/ null),
new FileStateValue.RegularFileStateValue(
/*size=*/ 1, /*digest=*/ new byte[0], /*contentsProxy=*/ null),
new FileStateValue.RegularFileStateValue(
/*size=*/ 1,
/*digest=*/ null,
makeFileContentsProxy(/* ctime= */ 2, /* nodeId= */ 42)),
new FileStateValue.SpecialFileStateValue(
makeFileContentsProxy(/* ctime= */ 4, /* nodeId= */ 84)),
FileStateValue.DIRECTORY_FILE_STATE_NODE,
new FileStateValue.SymlinkFileStateValue(PathFragment.create("somewhere/elses")),
FileStateValue.NONEXISTENT_FILE_STATE_NODE)
.runTests();
}
private static FileContentsProxy makeFileContentsProxy(long ctime, long nodeId)
throws IOException {
FileStatus status = Mockito.mock(FileStatus.class);
when(status.getLastChangeTime()).thenReturn(ctime);
when(status.getNodeId()).thenReturn(nodeId);
return FileContentsProxy.create(status);
}
}
| apache-2.0 |
wooga/airflow | airflow/contrib/operators/gcs_delete_operator.py | 1634 | #
# 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.
"""
This module is deprecated. Please use `airflow.providers.google.cloud.operators.gcs`.
"""
import warnings
from airflow.providers.google.cloud.operators.gcs import GCSDeleteObjectsOperator
warnings.warn(
"This module is deprecated. Please use `airflow.providers.google.cloud.operators.gcs`.",
DeprecationWarning, stacklevel=2
)
class GoogleCloudStorageDeleteOperator(GCSDeleteObjectsOperator):
"""
This class is deprecated.
Please use `airflow.providers.google.cloud.operators.gcs.GCSDeleteObjectsOperator`.
"""
def __init__(self, *args, **kwargs):
warnings.warn(
"""This class is deprecated.
Please use `airflow.providers.google.cloud.operators.gcs.GCSDeleteObjectsOperator`.""",
DeprecationWarning, stacklevel=2
)
super().__init__(*args, **kwargs)
| apache-2.0 |
mbebenita/shumway.ts | tests/Fidelity/test262/suite/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-7.js | 804 | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
* @path ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-7.js
* @description Array.prototype.every - return value of callbackfn is a nunmber (value is -0)
*/
function testcase() {
var accessed = false;
function callbackfn(val, idx, obj) {
accessed = true;
return -0;
}
return ![11].every(callbackfn) && accessed;
}
runTestCase(testcase);
| apache-2.0 |
shakuzen/spring-boot | spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/springbootfeatures/websockets/package-info.java | 765 | /*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.
*/
/**
* Examples for the "Spring Boot Features - WebSockets" section.
*/
package org.springframework.boot.docs.springbootfeatures.websockets;
| apache-2.0 |
richdougherty/playframework | documentation/manual/working/javaGuide/main/logging/code/javaguide/logging/Application.java | 1307 | /*
* Copyright (C) 2009-2017 Lightbend Inc. <https://www.lightbend.com>
*/
package javaguide.logging;
//#logging-pattern-mix
import play.Logger;
import play.Logger.ALogger;
import play.mvc.Action;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Http.Request;
import play.mvc.Result;
import play.mvc.With;
import java.util.concurrent.CompletionStage;
public class Application extends Controller {
private static final ALogger logger = Logger.of(Application.class);
@With(AccessLoggingAction.class)
public Result index() {
try {
final int result = riskyCalculation();
return ok("Result=" + result);
} catch (Throwable t) {
logger.error("Exception with riskyCalculation", t);
return internalServerError("Error in calculation: " + t.getMessage());
}
}
private static int riskyCalculation() {
return 10 / (new java.util.Random()).nextInt(2);
}
}
class AccessLoggingAction extends Action.Simple {
private ALogger accessLogger = Logger.of("access");
public CompletionStage<Result> call(Http.Context ctx) {
final Request request = ctx.request();
accessLogger.info("method={} uri={} remote-address={}", request.method(), request.uri(), request.remoteAddress());
return delegate.call(ctx);
}
}
//#logging-pattern-mix
| apache-2.0 |
langfr/camunda-bpm-platform | engine-dmn/engine/src/main/java/org/camunda/bpm/dmn/engine/impl/spi/type/DmnDataTypeTransformer.java | 1326 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.dmn.engine.impl.spi.type;
import org.camunda.bpm.engine.variable.value.TypedValue;
/**
* Transform a value into a specific type.
*
* @author Philipp Ossler
*/
public interface DmnDataTypeTransformer {
/**
* Transform the given value.
*
* @param value of any type
* @return value of the specific type
*
* @throws IllegalArgumentException
* if the value can not be transformed
*/
TypedValue transform(Object value) throws IllegalArgumentException;
}
| apache-2.0 |
RossLieberman/NEST | src/Tests/QueryDsl/Compound/Filtered/FilteredQueryUsageTests.cs | 1354 | using Nest;
using Tests.Framework.Integration;
using Tests.Framework.MockData;
#pragma warning disable 618 //Testing an obsolete method
namespace Tests.QueryDsl.Compound.Filtered
{
public class FilteredQueryUsageTests : QueryDslUsageTestsBase
{
public FilteredQueryUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { }
protected override object QueryJson => new
{
filtered = new
{
_name = "named_query",
boost = 1.1,
filter = new { match_all = new { _name = "filter" } },
query = new { match_all = new { _name = "query" } }
}
};
protected override QueryContainer QueryInitializer => new FilteredQuery()
{
Name = "named_query",
Boost = 1.1,
Filter = new MatchAllQuery { Name ="filter" },
Query = new MatchAllQuery() { Name = "query" },
};
protected override QueryContainer QueryFluent(QueryContainerDescriptor<Project> q) => q
.Filtered(c => c
.Name("named_query")
.Boost(1.1)
.Filter(qq => qq.MatchAll(m => m.Name("filter")))
.Query(qq => qq.MatchAll(m => m.Name("query")))
);
protected override ConditionlessWhen ConditionlessWhen => new ConditionlessWhen<IFilteredQuery>(a => a.Filtered)
{
q=> {
q.Filter = null;
q.Query = null;
},
q => {
q.Filter = ConditionlessQuery;
q.Query = ConditionlessQuery;
},
};
}
}
| apache-2.0 |
j-coll/java-common-libs | bioformats/src/main/java/org/opencb/commons/bioformats/protein/uniprot/v135jaxb/EvidencedStringType.java | 2876 | //
// This path was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this path will be lost upon recompilation of the source schema.
// Generated on: 2010.06.14 at 12:38:27 PM CEST
//
package org.opencb.commons.bioformats.protein.uniprot.v135jaxb;
import javax.xml.bind.annotation.*;
/**
* <p>Java class for evidencedStringType complex type.
* <p/>
* <p>The following schema fragment specifies the expected content contained within this class.
* <p/>
* <pre>
* <complexType name="evidencedStringType">
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="evidence" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="status">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="by similarity"/>
* <enumeration value="probable"/>
* <enumeration value="potential"/>
* </restriction>
* </simpleType>
* </attribute>
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "evidencedStringType", propOrder = {
"value"
})
public class EvidencedStringType {
@XmlValue
protected String value;
@XmlAttribute
protected String evidence;
@XmlAttribute
protected String status;
/**
* Gets the value of the value property.
*
* @return possible object is
* {@link String }
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value allowed object is
* {@link String }
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the evidence property.
*
* @return possible object is
* {@link String }
*/
public String getEvidence() {
return evidence;
}
/**
* Sets the value of the evidence property.
*
* @param value allowed object is
* {@link String }
*/
public void setEvidence(String value) {
this.evidence = value;
}
/**
* Gets the value of the status property.
*
* @return possible object is
* {@link String }
*/
public String getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value allowed object is
* {@link String }
*/
public void setStatus(String value) {
this.status = value;
}
}
| apache-2.0 |
andreagenso/java2scala | test/J2s/java/openjdk-6-src-b27/jdk/src/share/classes/sun/misc/resources/Messages_fr.java | 2204 | /*
* Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.misc.resources;
/**
* <p> This class represents the <code>ResourceBundle</code>
* for sun.misc.
*
* @author Michael Colburn
*/
public class Messages_fr extends java.util.ListResourceBundle {
/**
* Returns the contents of this <code>ResourceBundle</code>.
* <p>
* @return the contents of this <code>ResourceBundle</code>.
*/
public Object[][] getContents() {
return contents;
}
private static final Object[][] contents = {
{ "optpkg.versionerror", "ERREUR\u00a0: Format de version utilis\u00e9 pour le fichier JAR {0} non valide. Consultez la documentation pour voir le format de version pris en charge." },
{ "optpkg.attributeerror", "ERREUR\u00a0: L''attribut manifeste JAR {0} n\u00e9cessaire n''est pas d\u00e9fini pour le fichier {1}. " },
{ "optpkg.attributeserror", "ERREUR\u00a0: Certains attributs manifeste JAR {0} n\u00e9cessaires ne sont pas d\u00e9finis pour le fichier {1}. " }
};
}
| apache-2.0 |
cs-education/jor1k | js/worker/riscv/dynamiccpu.js | 86814 | // -------------------------------------------------
// -------------------- CPU ------------------------
// -------------------------------------------------
var message = require('../messagehandler');
var utils = require('../utils');
var DebugIns = require('./disassemble');
// constructor
function DynamicCPU(stdlib, foreign, heap) {
"use asm";
var DebugMessage = foreign.DebugMessage;
var abort = foreign.abort;
var Read32 = foreign.Read32;
var Write32 = foreign.Write32;
var Read16 = foreign.Read16;
var Write16 = foreign.Write16;
var Read8 = foreign.Read8;
var Write8 = foreign.Write8;
var ReadDEVCMDToHost = foreign.ReadDEVCMDToHost;
var ReadDEVCMDFromHost = foreign.ReadDEVCMDFromHost;
var WriteDEVCMDToHost = foreign.WriteDEVCMDToHost;
var WriteDEVCMDFromHost = foreign.WriteDEVCMDFromHost;
var ReadToHost = foreign.ReadToHost;
var ReadFromHost = foreign.ReadFromHost;
var WriteToHost = foreign.WriteToHost;
var WriteFromHost = foreign.WriteFromHost;
var IsQueueEmpty = foreign.IsQueueEmpty;
var mul = foreign.mul;
var MathAbs = stdlib.Math.abs;
var ERROR_INCOMPLETE_VMPRIVILEGE = 0;
var ERROR_VMPRIVILEGE = 1;
var ERROR_VMMODE = 2;
var ERROR_SETCSR = 3;
var ERROR_GETCSR = 4;
var ERROR_LOAD_WORD = 5;
var ERROR_STORE_WORD = 6;
var ERROR_INSTRUCTION_NOT_FOUND = 7;
var ERROR_ECALL = 8;
var ERROR_ERET = 9;
var ERROR_ERET_PRIV = 10;
var ERROR_MRTS = 11;
var ERROR_ATOMIC_INSTRUCTION = 12;
var PRV_U = 0x00;
var PRV_S = 0x01;
var PRV_H = 0x02;
var PRV_M = 0x03;
var VM_READ = 0;
var VM_WRITE = 1;
var VM_FETCH = 2;
var CAUSE_TIMER_INTERRUPT = 0x80000001;
var CAUSE_HOST_INTERRUPT = 0x80000002;
var CAUSE_SOFTWARE_INTERRUPT = 0x80000000;
var CAUSE_INSTRUCTION_ACCESS_FAULT = 0x01;
var CAUSE_ILLEGAL_INSTRUCTION = 0x02;
var CAUSE_BREAKPOINT = 0x03;
var CAUSE_LOAD_ACCESS_FAULT = 0x05;
var CAUSE_STORE_ACCESS_FAULT = 0x07;
var CAUSE_ENVCALL_UMODE = 0x08;
var CAUSE_ENVCALL_SMODE = 0x09;
var CAUSE_ENVCALL_HMODE = 0x0A;
var CAUSE_ENVCALL_MMODE = 0x0B;
var CSR_CYCLES = 0x3000;
var CSR_CYCLEW = 0x2400;
var CSR_FFLAGS = 0x4;
var CSR_FRM = 0x8;
var CSR_FCSR = 0xC;
var CSR_SSTATUS = 0x400;
var CSR_STVEC = 0x404;
var CSR_SIE = 0x410;
var CSR_STIMECMP = 0x484;
var CSR_SSCRATCH = 0x500;
var CSR_SEPC = 0x504;
var CSR_SIP = 0x510;
var CSR_SPTBR = 0x600;
var CSR_SASID = 0x604;
var CSR_HEPC = 0x904;
var CSR_MSTATUS = 0xC00;
var CSR_MTVEC = 0xC04;
var CSR_MTDELEG = 0xC08;
var CSR_MIE = 0xC10;
var CSR_MTIMECMP = 0xC84;
var CSR_MTIMECMPH = 0xD84;
var CSR_MEPC = 0xD04;
var CSR_MSCRATCH = 0xD00;
var CSR_MCAUSE = 0xD08;
var CSR_MBADADDR = 0xD0C;
var CSR_MIP = 0xD10;
var CSR_MTOHOST_TEMP = 0xD14; // terminal output, temporary for the patched pk.
var CSR_MTIME = 0x1C04;
var CSR_MTIMEH = 0x1D04;
var CSR_MRESET = 0x1E08;
var CSR_SEND_IPI = 0x1E0C;
var CSR_MTOHOST = 0x1E00;
var CSR_MFROMHOST = 0x1E04;
var CSR_MDEVCMDTOHOST = 0x1E40; // special
var CSR_MDEVCMDFROMHOST = 0x1E44; // special
var CSR_TIMEW = 0x2404;
var CSR_INSTRETW = 0x2408;
var CSR_CYCLEHW = 0x2600;
var CSR_TIMEHW = 0x2604;
var CSR_INSTRETHW = 0x2608;
var CSR_STIMEW = 0x2804;
var CSR_STIMEH = 0x3604;
var CSR_STIMEHW = 0x2A04;
var CSR_STIME = 0x3404;
var CSR_SCAUSE = 0x3508;
var CSR_SBADADDR = 0x350C;
var CSR_MCPUID = 0x3C00;
var CSR_MIMPID = 0x3C04;
var CSR_MHARTID = 0x3C40;
var CSR_CYCLEH = 0x3200;
var CSR_TIMEH = 0x3204;
var CSR_INSTRETH = 0x3208;
var CSR_TIME = 0x3004;
var CSR_INSTRET = 0x3008;
var CSR_STATS = 0x300;
var CSR_UARCH0 = 0x3300;
var CSR_UARCH1 = 0x3304;
var CSR_UARCH2 = 0x3008;
var CSR_UARCH3 = 0x330C;
var CSR_UARCH4 = 0x3310;
var CSR_UARCH5 = 0x3314;
var CSR_UARCH6 = 0x3318;
var CSR_UARCH7 = 0x331C;
var CSR_UARCH8 = 0x3320;
var CSR_UARCH9 = 0x3324;
var CSR_UARCH10 = 0x3328;
var CSR_UARCH11 = 0x332C;
var CSR_UARCH12 = 0x3330;
var CSR_UARCH13 = 0x33334;
var CSR_UARCH14 = 0x33338;
var CSR_UARCH15 = 0x3333C;
var r = new stdlib.Int32Array(heap); // registers
var rp = 0x00; //Never used
var f = new stdlib.Float64Array(heap); // registers
var fp = 0x80;
var fi = new stdlib.Int32Array(heap); // for copying operations
var fip = 0x80;
var ff = new stdlib.Float32Array(heap); // the zero register is used to convert to single precision
var ffp = 0x00; //Never used
var csr = new stdlib.Int32Array(heap);
var csrp = 0x2000;
var ram = new stdlib.Int32Array(heap);
var ramp = 0x100000;
var ram8 = new stdlib.Int8Array(heap);
var ram16 = new stdlib.Int16Array(heap);
var pc = 0x200;
var pcorigin = 0x200;
var pc_change = 1; //1 implies pc has been changed by an instruction
var ticks = 0;
var amoaddr = 0,amovalue = 0;
var fence = 0x200;
var ppc = 0x200;
var ppcorigin = 0x200;
var instlb_index = -1; //tlb index for pc
var instlb_entry = -1;
var read8tlb_index = -1; //tlb index for lb ins
var read8tlb_entry = -1;
var read8utlb_index = -1; //tlb index for lbu ins
var read8utlb_entry = -1;
var read16tlb_index = -1; //tlb index for lh ins
var read16tlb_entry = -1;
var read16utlb_index = -1; //tlb index for lhu ins
var read16utlb_entry = -1;
var read32tlb_index = -1; //tlb index for lw ins
var read32tlb_entry = -1;
var store8tlb_index = -1; //tlb index for sb ins
var store8tlb_entry = -1;
var store16tlb_index = -1; //tlb index for sh ins
var store16tlb_entry = -1;
var store32tlb_index = -1; //tlb index for sw ins
var store32tlb_entry = -1;
var float_read32tlb_index = -1; //tlb index for flw ins
var float_read32tlb_entry = -1;
var float_read64tlb_index = -1; //tlb index for fld ins
var float_read64tlb_entry = -1;
var float_store32tlb_index = -1; //tlb index for fsw ins
var float_store32tlb_entry = -1;
var float_store64tlb_index = -1; //tlb index for fsd ins
var float_store64tlb_entry = -1;
var queue_status = 0; // 1 means queue is full
function Init() {
Reset();
}
function Reset() {
ticks = 0;
csr[(csrp + CSR_MSTATUS)>>2] = 0x96; // 1001 0110 - All Interrupts Disabled, FPU disabled
csr[(csrp + CSR_MTOHOST)>>2] = 0x780;
csr[(csrp + CSR_MCPUID)>>2] = 0x4112D;
csr[(csrp + CSR_MIMPID)>>2] = 0x01;
csr[(csrp + CSR_MHARTID)>>2] = 0x00;
csr[(csrp + CSR_MTVEC)>>2] = 0x100;
csr[(csrp + CSR_MIE)>>2] = 0x00;
csr[(csrp + CSR_MEPC)>>2] = 0x00;
csr[(csrp + CSR_MCAUSE)>>2] = 0x00;
csr[(csrp + CSR_MBADADDR)>>2] = 0x00;
csr[(csrp + CSR_SSTATUS)>>2] = 0x3010;
csr[(csrp + CSR_STVEC)>>2] = 0x00;
csr[(csrp + CSR_SIE)>>2] = 0x00;
csr[(csrp + CSR_TIME)>>2] = 0x0;
csr[(csrp + CSR_SPTBR)>>2] = 0x40000;
// for atomic load & store instructions
amoaddr = 0x00;
amovalue = 0x00;
}
function GetTimeToNextInterrupt() {
return 10;
}
function GetTicks() {
return ticks|0;
}
function ProgressTime(delta) {
delta = delta|0;
ticks = ticks + delta|0;
}
function AnalyzeImage() // we haveto define these to copy the cpus
{
}
function CheckForInterrupt() {
};
function RaiseInterrupt(line, cpuid) {
line = line|0;
cpuid = cpuid|0;
//DebugMessage("raise int " + line);
queue_status = 1;
};
function ClearInterrupt(line, cpuid) {
line = line|0;
cpuid = cpuid|0;
};
function Trap(cause, current_pc) {
cause = cause|0;
current_pc = current_pc|0;
var current_privilege_level = 0;
var offset = 0x100;
current_privilege_level = (csr[(csrp + CSR_MSTATUS)>>2] & 0x06) >> 1;
PushPrivilegeStack();
csr[(csrp + CSR_MEPC)>>2] = current_pc;
csr[(csrp + CSR_MCAUSE)>>2] = cause;
pc = (offset + (current_privilege_level << 6))|0;
fence = ppc;
pc_change = 1;
InvalidateTLB();
};
function MemTrap(addr, op) {
addr = addr|0;
op = op|0;
if((op|0) != (VM_FETCH|0)) pc = pcorigin + (ppc-ppcorigin)|0;
csr[(csrp + CSR_MBADADDR)>>2] = addr;
switch(op|0) {
case 0: //VM_READ
Trap(CAUSE_LOAD_ACCESS_FAULT, pc - 4|0);
break;
case 1: //VM_WRITE
Trap(CAUSE_STORE_ACCESS_FAULT, pc - 4|0);
break;
case 2: //VM_FETCH
Trap(CAUSE_INSTRUCTION_ACCESS_FAULT, pc);
break;
}
}
function CheckVMPrivilege(type, op) {
type = type|0;
op = op|0;
var priv = 0;
priv = (csr[(csrp + CSR_MSTATUS)>>2] & 0x06) >> 1;
switch(type|0) {
case 2:
if ((op|0) == (VM_READ|0)) return 1;
if (((priv|0) == (PRV_U|0)) & ((op|0) == (VM_FETCH|0))) return 1;
return 0;
break;
case 3:
if (!( ((priv|0) == (PRV_S|0)) & ((op|0) == (VM_FETCH|0)) ) ) return 1;
break;
case 4:
if ((op|0) == (VM_READ|0)) return 1;
return 0;
break;
case 5:
if ((op|0) != (VM_FETCH|0)) return 1;
break;
case 6:
if ((op|0) != (VM_WRITE|0)) return 1;
break;
case 7:
return 1;
break;
case 13:
if (((priv|0) == (PRV_S|0)) & ((op|0) != (VM_FETCH|0))) return 1;
break;
case 14:
if (((priv|0) == (PRV_S|0)) & ((op|0) != (VM_WRITE|0))) return 1;
break;
case 15:
if ((priv|0) == (PRV_S|0)) return 1;
break;
}
DebugMessage(ERROR_INCOMPLETE_VMPRIVILEGE|0);
abort();
return 0;
}
function TranslateVM(addr, op) {
addr = addr|0;
op = op|0;
var vm = 0;
var current_privilege_level = 0;
var i = 1; //i = LEVELS -1 and LEVELS = 2 in a 32 bit System
var offset = 0;
var page_num = 0;
var frame_num = 0;
var type = 0;
var valid = 0;
//For Level 2
var new_sptbr = 0;
var new_page_num = 0;
var new_frame_num = 0;
var new_type = 0;
var new_valid = 0;
var ram_index = 0;
vm = (csr[(csrp + CSR_MSTATUS)>>2] >> 17) & 0x1F;
current_privilege_level = (csr[(csrp + CSR_MSTATUS)>>2] & 0x06) >> 1;
// vm bare mode
if(((vm|0) == 0) | ((current_privilege_level|0) == (PRV_M|0))) return addr|0;
// hack, open mmio by direct mapping
//if ((addr>>>28) == 0x9) return addr;
// only RV32 supported
if((vm|0) != 8) {
DebugMessage(ERROR_VMMODE|0);
abort();
}
// LEVEL 1
offset = addr & 0xFFF;
page_num = (addr >>> 22)|0;
ram_index = (csr[(csrp + CSR_SPTBR)>>2]|0) + (page_num << 2)|0
frame_num = ram[(ramp + ram_index) >> 2]|0;
type = ((frame_num >> 1) & 0xF);
valid = (frame_num & 0x01);
if ((valid|0) == 0) {
//DebugMessage("Unsupported valid field " + valid + " or invalid entry in PTE at PC "+utils.ToHex(pc) + " pl:" + current_privilege_level + " addr:" + utils.ToHex(addr) + " op:"+op);
//abort();
MemTrap(addr, op);
return -1;
}
if ((type|0) >= 2) {
if (!(CheckVMPrivilege(type,op)|0)) {
DebugMessage(ERROR_VMPRIVILEGE|0);
abort();
}
/*
var updated_frame_num = frame_num;
if(op == VM_READ)
updated_frame_num = (frame_num | 0x20);
else if(op == VM_WRITE)
updated_frame_num = (frame_num | 0x60);
Write32(csr[CSR_SPTBR] + (page_num << 2),updated_frame_num);
*/
return (((frame_num >> 10) | ((addr >> 12) & 0x3FF)) << 12) | offset;
}
// LEVEL 2
//DebugMessage("Second level MMU");
offset = addr & 0xFFF;
new_sptbr = (frame_num & 0xFFFFFC00) << 2;
new_page_num = (addr >> 12) & 0x3FF;
ram_index = (new_sptbr|0) + (new_page_num << 2)|0;
new_frame_num = ram[(ramp + ram_index) >> 2]|0;
new_type = ((new_frame_num >> 1) & 0xF);
new_valid = (new_frame_num & 0x01);
i = (i - 1)|0;
if ((new_valid|0) == 0) {
MemTrap(addr, op);
return -1;
}
if (!(CheckVMPrivilege(new_type, op)|0)) {
//DebugMessage("Error in TranslateVM: Unhandled trap");
//abort();
MemTrap(addr, op);
return -1;
}
/*
var updated_frame_num = new_frame_num;
if(op == VM_READ)
updated_frame_num = (new_frame_num | 0x20);
else if(op == VM_WRITE)
updated_frame_num = (new_frame_num | 0x60);
Write32(new_sptbr + (new_page_num << 2),updated_frame_num);
*/
return ((new_frame_num >> 10) << 12) | offset | 0;
};
function SetCSR(addr,value) {
addr = addr|0;
value = value|0;
var mask = 0;
var ram_index = 0;
addr = addr << 2;
switch(addr|0)
{
case 0xC: //CSR_FCSR
csr[(csrp + addr)>>2] = value;
break;
case 0x1E40: //CSR_MDEVCMDTOHOST
csr[(csrp + addr)>>2] = value;
WriteDEVCMDToHost(value|0);
break;
case 0x1E44: //CSR_MDEVCMDFROMHOST
csr[(csrp + addr)>>2] = value;
WriteDEVCMDFromHost(value|0);
break;
case 0x1E00: //CSR_MTOHOST
csr[(csrp + addr)>>2] = value;
WriteToHost(value|0);
break;
case 0xD14: //CSR_MTOHOST_TEMP only temporary for the patched pk.
ram_index = 0x90000000 >> 0;
ram8[(ramp + ram_index) >> 0] = value|0;
if ((value|0) == 0xA) ram8[(ramp + ram_index) >> 0] = 0xD;
break;
case 0x1E04: //CSR_MFROMHOST
csr[(csrp + addr)>>2] = value;
WriteFromHost(value|0);
break;
case 0xC00: //CSR_MSTATUS
csr[(csrp + addr)>>2] = value;
break;
case 0x3C00: //CSR_MCPUID
//csr[addr] = value;
break;
case 0x3C04: //CSR_MIMPID
csr[(csrp + addr)>>2] = value;
break;
case 0x3C40: //CSR_MHARTID
csr[(csrp + addr)>>2] = value;
break;
case 0xC04: //CSR_MTVEC
csr[(csrp + addr)>>2] = value;
break;
case 0xD10: //CSR_MIP
//csr[addr] = value;
mask = 0x2 | 0x08; //mask = MIP_SSIP | MIP_MSIP
csr[(csrp + addr)>>2] = (csr[(csrp + addr)>>2] & ~mask) | (value & mask);
break;
case 0xC10: //CSR_MIE
//csr[addr] = value;
mask = 0x2 | 0x08 | 0x20; //mask = MIP_SSIP | MIP_MSIP | MIP_STIP
csr[(csrp + addr)>>2] = (csr[(csrp + addr)>>2] & ~mask) | (value & mask);
break;
case 0x504: //CSR_SEPC
case 0xD04: //CSR_MEPC
csr[(csrp + addr)>>2] = value;
break;
case 0xD08: //CSR_MCAUSE
csr[(csrp + addr)>>2] = value;
break;
case 0x3508: //CSR_SCAUSE
csr[(csrp + addr)>>2] = value;
break;
case 0xD0C: //CSR_MBADADDR
csr[(csrp + addr)>>2] = value;
break;
case 0x350C: //CSR_SBADADDR
csr[(csrp + addr)>>2] = value;
break;
case 0x400: //CSR_SSTATUS
csr[(csrp + CSR_SSTATUS)>>2] = value;
csr[(csrp + CSR_MSTATUS)>>2] = csr[(csrp + CSR_MSTATUS)>>2] & (~0x1F039);
csr[(csrp + CSR_MSTATUS)>>2] = csr[(csrp + CSR_MSTATUS)>>2] | (csr[(csrp + CSR_SSTATUS)>>2] & 0x01); //IE0
csr[(csrp + CSR_MSTATUS)>>2] = csr[(csrp + CSR_MSTATUS)>>2] | (csr[(csrp + CSR_SSTATUS)>>2] & 0x08); //IE1
csr[(csrp + CSR_MSTATUS)>>2] = csr[(csrp + CSR_MSTATUS)>>2] | (csr[(csrp + CSR_SSTATUS)>>2] & 0x10); //PRV1
csr[(csrp + CSR_MSTATUS)>>2] = csr[(csrp + CSR_MSTATUS)>>2] | (csr[(csrp + CSR_SSTATUS)>>2] & 0xF000); //FS,XS
csr[(csrp + CSR_MSTATUS)>>2] = csr[(csrp + CSR_MSTATUS)>>2] | (csr[(csrp + CSR_SSTATUS)>>2] & 0x10000); //MPRV
break;
case 0x404: //CSR_STVEC
csr[(csrp + addr)>>2] = value;
break;
case 0x510: //CSR_SIP
//csr[addr] = value;
mask = 0x2; //mask = MIP_SSIP
csr[(csrp + CSR_MIP)>>2] = (csr[(csrp + CSR_MIP)>>2] & ~mask) | (value & mask);
break;
case 0x410: //CSR_SIE
//csr[addr] = value;
mask = 0x2 | 0x20; //mask = MIP_SSIP | MIP_STIP
csr[(csrp + CSR_MIE)>>2] = (csr[(csrp + CSR_MIE)>>2] & ~mask) | (value & mask);
break;
case 0xD00: //CSR_MSCRATCH
csr[(csrp + addr)>>2] = value;
break;
case 0x500: //CSR_SSCRATCH
csr[(csrp + addr)>>2] = value;
break;
case 0x2400: //CSR_CYCLEW
csr[(csrp + addr)>>2] = value;
break;
case 0x3000: //CSR_CYCLES
ticks = value;
csr[(csrp + addr)>>2] = value;
break;
case 0x1C04: //CSR_MTIME
case 0x3404: //CSR_STIME
case 0x2804: //CSR_STIMEW
csr[(csrp + addr)>>2] = value;
break;
case 0x1D04: //CSR_MTIMEH
case 0x3604: //CSR_STIMEH
case 0x2A04: //CSR_STIMEHW
csr[(csrp + addr)>>2] = value;
break;
case 0x3004: //CSR_TIME
case 0x2404: //CSR_TIMEW
csr[(csrp + addr)>>2] = value;
break;
case 0xC84: //CSR_MTIMECMP
case 0x484: //CSR_STIMECMP
csr[(csrp + CSR_MIP)>>2] = csr[(csrp + CSR_MIP)>>2] & (~(0x20)); //csr[CSR_MIP] &= ~MIP_STIP
csr[(csrp + addr)>>2] = value;
break;
case 0xD84: //CSR_MTIMECMPH
case 0x600: //CSR_SPTBR
csr[(csrp + addr)>>2] = value;
break;
case 0x04: //CSR_FRM
case 0x08: //CSR_FFLAGS
csr[(csrp + addr)>>2] = value;
break;
default:
csr[(csrp + addr)>>2] = value;
DebugMessage(ERROR_SETCSR|0);
abort();
break;
}
};
function GetCSR(addr) {
addr = addr|0;
var current_privilege_level = 0;
current_privilege_level = (csr[(csrp + CSR_MSTATUS)>>2] & 0x06) >> 1;
addr = (addr << 2)|0;
switch(addr|0)
{
case 0xC: //CSR_FCSR
return 0x0;
break;
case 0x1E40: //CSR_MDEVCMDTOHOST
return ReadDEVCMDToHost()|0;
break;
case 0x1E44: //CSR_MDEVCMDFROMHOST
return ReadDEVCMDFromHost()|0;
break;
case 0x1E00: //CSR_MTOHOST
return ReadToHost()|0;
break;
case 0xD14: //CSR_MTOHOST_TEMP only temporary for the patched pk.
return 0x0;
break;
case 0x1E04: //CSR_MFROMHOST
return ReadFromHost()|0;
break;
case 0xC00: //CSR_MSTATUS
return csr[(csrp + addr)>>2]|0;
break;
case 0x3C00: //CSR_MCPUID
return csr[(csrp + addr)>>2]|0;
break;
case 0x3C04: //CSR_MIMPID
return csr[(csrp + addr)>>2]|0;
break;
case 0x3C40: //CSR_MHARTID
return csr[(csrp + addr)>>2]|0;
break;
case 0xC04: //CSR_MTVEC
return csr[(csrp + addr)>>2]|0;
break;
case 0xC10: //CSR_MIE
return csr[(csrp + addr)>>2]|0;
break;
case 0x504: //CSR_SEPC
case 0xD04: //CSR_MEPC
return csr[(csrp + addr)>>2]|0;
break;
case 0xD08: //CSR_MCAUSE
return csr[(csrp + addr)>>2]|0;
break;
case 0x3508: //CSR_SCAUSE
return csr[(csrp + addr)>>2]|0;
break;
case 0xD0C: //CSR_MBADADDR
return csr[(csrp + addr)>>2]|0;
break;
case 0x350C: //CSR_SBADADDR
return csr[(csrp + addr)>>2]|0;
break;
case 0x400: //CSR_SSTATUS
//if (current_privilege_level == 0) Trap(CAUSE_ILLEGAL_INSTRUCTION);
csr[(csrp + CSR_SSTATUS)>>2] = 0x00;
csr[(csrp + CSR_SSTATUS)>>2] = csr[(csrp + CSR_SSTATUS)>>2] | (csr[(csrp + CSR_MSTATUS)>>2] & 0x01); //IE0
csr[(csrp + CSR_SSTATUS)>>2] = csr[(csrp + CSR_SSTATUS)>>2] | (csr[(csrp + CSR_MSTATUS)>>2] & 0x08); //IE1
csr[(csrp + CSR_SSTATUS)>>2] = csr[(csrp + CSR_SSTATUS)>>2] | (csr[(csrp + CSR_MSTATUS)>>2] & 0x10); //PRV1
csr[(csrp + CSR_SSTATUS)>>2] = csr[(csrp + CSR_SSTATUS)>>2] | (csr[(csrp + CSR_MSTATUS)>>2] & 0xF000); //FS,XS
csr[(csrp + CSR_SSTATUS)>>2] = csr[(csrp + CSR_SSTATUS)>>2] | (csr[(csrp + CSR_MSTATUS)>>2] & 0x10000); //MPRV
return csr[(csrp + CSR_SSTATUS)>>2]|0;
break;
case 0x404: //CSR_STVEC
return csr[(csrp + addr)>>2]|0;
break;
case 0xD10: //CSR_MIP
return csr[(csrp + addr)>>2]|0;
break;
case 0x510: //CSR_SIP
return (csr[(csrp + CSR_MIP)>>2] & (0x2 | 0x20))|0;//(MIP_SSIP | MIP_STIP)
break;
case 0x410: //CSR_SIE
return (csr[(csrp + CSR_MIE)>>2] & (0x2 | 0x20))|0;//(MIP_SSIP | MIP_STIP)
break;
case 0xD00: //CSR_MSCRATCH
return csr[(csrp + addr)>>2]|0;
break;
case 0x500: //CSR_SSCRATCH
return csr[(csrp + addr)>>2]|0;
break;
case 0x2400: //CSR_CYCLEW
return ticks|0;
break;
case 0x3000: //CSR_CYCLES
return ticks|0;
break;
case 0x1C04: //CSR_MTIME
case 0x3404: //CSR_STIME
case 0x2804: //CSR_STIMEW
return ticks|0;
break;
case 0x1D04: //CSR_MTIMEH
case 0x3604: //CSR_STIMEH
case 0x2A04: //CSR_STIMEHW
return ((ticks) >> 32)|0;
break;
case 0x3004: //CSR_TIME
case 0x2404: //CSR_TIMEW
return ticks|0;
break;
case 0xC84: //CSR_MTIMECMP
case 0x484: //CSR_STIMECMP
return csr[(csrp + addr)>>2]|0;
break;
case 0xD84: //CSR_MTIMECMPH
case 0x600: //CSR_SPTBR
return csr[(csrp + addr)>>2]|0;
break;
case 0x04: //CSR_FRM
case 0x08: //CSR_FFLAGS
return csr[(csrp + addr)>>2]|0;
break;
default:
DebugMessage(ERROR_GETCSR|0);
abort();
return csr[(csrp + addr)>>2]|0;
break;
}
return 0;
};
function IMul(a,b,index) {
a = a|0;
b = b|0;
index = index|0;
var result0 = 0,result1 = 0;
var a00 = 0, a16 = 0;
var b00 = 0, b16 = 0;
var c00 = 0;
var c16 = 0;
var c32 = 0;
var c48 = 0;
if (((a >>> 0) < 32767) & ((b >>> 0) < 65536)) {
result0 = mul(a|0,b|0)|0;
result1 = ((result0|0) < 0) ? -1 : 0;
if((index|0) == 0) return result0|0;
else return result1|0;
}
a00 = a & 0xFFFF;
a16 = a >>> 16;
b00 = b & 0xFFFF;
b16 = b >>> 16;
c00 = mul(a00|0,b00|0)|0;
c16 = ((c00 >>> 16) + (mul(a16|0,b00|0)|0))|0;
c32 = c16 >>> 16;
c16 = ((c16 & 0xFFFF) + (mul(a00|0,b16|0)|0))|0;
c32 = (c32 + (c16 >>> 16))|0;
c48 = c32 >>> 16;
c32 = ((c32 & 0xFFFF) + (mul(a16|0,b16|0)|0))|0;
c48 = (c48 + (c32 >>> 16))|0;
result0 = ((c16 & 0xFFFF) << 16) | (c00 & 0xFFFF);
result1 = ((c48 & 0xFFFF) << 16) | (c32 & 0xFFFF);
if((index|0) == 0) return result0|0;
return result1|0;
};
function UMul(a,b,index) {
a = a|0;
b = b|0;
index = index|0;
var result0 = 0,result1 = 0;
var doNegate = 0;
if ((a|0) == 0) return 0;
if ((b|0) == 0) return 0;
if ((((a|0) >= -32768) & ((a|0) <= 32767)) & (((b|0) >= -32768) & ((b|0) <= 32767))) {
result0 = mul(a|0,b|0)|0;
result1 = ((result0|0) < 0) ? -1 : 0;
if((index|0) == 0) return result0|0;
else return result1|0;
}
doNegate = ((a|0) < 0) ^ ((b|0) < 0);
a = MathAbs(a|0)|0;
b = MathAbs(b|0)|0;
result0 = IMul(a, b, 0)|0;
result1 = IMul(a, b, 1)|0;
if (doNegate) {
result0 = ~result0;
result1 = ~result1;
result0 = (result0 + 1) | 0;
if ((result0|0) == 0) result1 = (result1 + 1) | 0;
}
if((index|0) == 0) return result0|0;
return result1|0;
};
function SUMul(a,b,index) {
a = a|0;
b = b|0;
index = index|0;
var result0 = 0,result1 = 0;
var doNegate = 0;
if ((a|0) == 0) return 0;
if ((b|0) == 0) return 0;
if ((((a|0) >= -32768) & ((a|0) <= 32767)) & (((b|0) >= -32768) & ((b >>> 0) <= 32767))) {
result0 = mul(a|0,b|0)|0;
result1 = ((result0|0) < 0) ? -1 : 0;
if((index|0) == 0) return result0|0;
else return result1|0;
}
doNegate = ((a|0) < 0) ^ ((b|0) < 0);
a = MathAbs(a|0)|0;
b = MathAbs(b|0)|0;
result0 = IMul(a, b, 0)|0;
result1 = IMul(a, b, 1)|0;
if (doNegate) {
result0 = ~result0;
result1 = ~result1;
result0 = (result0 + 1) | 0;
if ((result0|0) == 0) result1 = (result1 + 1) | 0;
}
if((index|0) == 0) return result0|0;
return result1|0;
};
function InvalidateTLB(){
read8tlb_index = -1;
read8tlb_entry = -1;
read8utlb_index = -1;
read8utlb_entry = -1;
read16tlb_index = -1;
read16tlb_entry = -1;
read16utlb_index = -1;
read16utlb_entry = -1;
read32tlb_index = -1;
read32tlb_entry = -1;
store8tlb_index = -1;
store8tlb_entry = -1;
store16tlb_index = -1;
store16tlb_entry = -1;
store32tlb_index = -1;
store32tlb_entry = -1;
float_read32tlb_index = -1;
float_read32tlb_entry = -1;
float_read64tlb_index = -1;
float_read64tlb_entry = -1;
float_store32tlb_index = -1;
float_store32tlb_entry = -1;
float_store64tlb_index = -1;
float_store64tlb_entry = -1;
}
function PushPrivilegeStack(){
var mstatus = 0,privilege_level_stack = 0, new_privilege_level_stack = 0;
mstatus = csr[(csrp + CSR_MSTATUS)>>2]|0;
privilege_level_stack = (mstatus & 0xFFF);
new_privilege_level_stack = (((privilege_level_stack << 2) | PRV_M) << 1) & 0xFFF;
csr[(csrp + CSR_MSTATUS)>>2] = (((mstatus >> 12) << 12) + new_privilege_level_stack) & 0xFFFEFFFF; //Last "and" to set mprv(bit 16) to zero
};
function PopPrivilegeStack(){
var mstatus = 0,privilege_level_stack = 0, new_privilege_level_stack = 0;
mstatus = csr[(csrp + CSR_MSTATUS)>>2]|0;
privilege_level_stack = (mstatus & 0xFFF);
new_privilege_level_stack = ((privilege_level_stack >>> 3) | ((PRV_U << 1) | 0x1) << 9);
csr[(csrp + CSR_MSTATUS)>>2] = ((mstatus >> 12) << 12) + new_privilege_level_stack;
};
function Step(steps, clockspeed) {
steps = steps|0;
clockspeed = clockspeed|0;
var imm = 0x00;
var zimm = 0x00;
var mult = 0x00;
var quo = 0x00;
var rem = 0x00;
var result = 0x00;
var rs1 = 0x0;
var rs2 = 0x0;
var fs1 = 0.0;
var fs2 = 0.0;
var fs3 = 0.0;
var delta = 0;
var paddr = 0;
var current_privilege_level = 0;
var interrupts = 0;
var ie = 0;
var ins = 0;
var dsteps = 64;
for(;;) {
if ((fence|0) != (ppc|0)) {
ins = ram[ppc >> 2]|0;
ppc = ppc + 4|0;
switch(ins&0x7F) {
case 0x03:
//lb, lh, lw, lbu, lhu
switch((ins >> 12)&0x7) {
case 0x00:
//lb
imm = (ins >> 20);
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if(!((read8tlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (read8tlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_READ)|0;
if((paddr|0) == -1) continue;
read8tlb_index = paddr;
read8tlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
r[((ins >> 5) & 0x7C) >> 2] = ((ram8[(ramp + paddr) >> 0]) << 24) >> 24;
ram[(ppc - 4) >> 2] = ((ins >> 7) << 7) | 0x74; //If this ins comes again, it will take the faster route at opcode 0x74
continue;
case 0x01:
//lh
imm = (ins >> 20);
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if(!((read16tlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (read16tlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_READ)|0;
if((paddr|0) == -1) continue;
read16tlb_index = paddr;
read16tlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
r[((ins >> 5) & 0x7C) >> 2] = ((ram16[(ramp + paddr) >> 1]) << 16) >> 16;
ram[(ppc - 4) >> 2] = ((ins >> 7) << 7) | 0x75;
continue;
case 0x02:
//lw
imm = (ins >> 20);
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if ((rs1+imm) & 3) {
DebugMessage(ERROR_LOAD_WORD|0);
abort();
}
if(!((read32tlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (read32tlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_READ)|0;
if((paddr|0) == -1) continue;
read32tlb_index = paddr;
read32tlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
r[((ins >> 5) & 0x7C) >> 2] = ram[(ramp + paddr) >> 2]|0;
ram[(ppc - 4) >> 2] = ((ins >> 7) << 7) | 0x76;
continue;
case 0x04:
//lbu
imm = (ins >> 20);
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if(!((read8utlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (read8utlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_READ)|0;
if((paddr|0) == -1) continue;
read8utlb_index = paddr;
read8utlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
r[((ins >> 5) & 0x7C) >> 2] = (ram8[(ramp + paddr) >> 0]) & 0xFF;
ram[(ppc - 4) >> 2] = ((ins >> 7) << 7) | 0x77;
continue;
case 0x05:
//lhu
imm = (ins >> 20);
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if(!((read16utlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (read16utlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_READ)|0;
if((paddr|0) == -1) continue;
read16utlb_index = paddr;
read16utlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
r[((ins >> 5) & 0x7C) >> 2] = (ram16[(ramp + paddr) >> 1]) & 0xFFFF;
ram[(ppc - 4) >> 2] = ((ins >> 7) << 7) | 0x78;
continue;
default:
DebugMessage(ERROR_INSTRUCTION_NOT_FOUND|0);
abort();
break;
}
continue;
case 0x23:
//sb, sh, sw
imm = ((ins >> 25) << 5) | ((ins >> 7) & 0x1F);
switch((ins >> 12)&0x7) {
case 0x00:
//sb
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if(!((store8tlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (store8tlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_WRITE)|0;
if((paddr|0) == -1) continue;
store8tlb_index = paddr;
store8tlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
ram8[(ramp + paddr) >> 0] = (r[((ins >> 18) & 0x7C) >> 2] & 0xFF);
ram[(ppc - 4) >> 2] = ((ins >> 7) << 7) | 0x79;
continue;
case 0x01:
//sh
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if(!((store16tlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (store16tlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_WRITE)|0;
if((paddr|0) == -1) continue;
store16tlb_index = paddr;
store16tlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
ram16[(ramp + paddr) >> 1] = (r[((ins >> 18) & 0x7C) >> 2] & 0xFFFF);
ram[(ppc - 4) >> 2] = ((ins >> 7) << 7) | 0x7A;
continue;
case 0x02:
//sw
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if ((rs1+imm) & 3) {
DebugMessage(ERROR_STORE_WORD|0);
abort();
}
if(!((store32tlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (store32tlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_WRITE)|0;
if((paddr|0) == -1) continue;
store32tlb_index = paddr;
store32tlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
ram[(ramp + paddr) >> 2] = r[((ins >> 18) & 0x7C) >> 2]|0;
ram[(ppc - 4) >> 2] = ((ins >> 7) << 7) | 0x7B;
continue;
default:
DebugMessage(ERROR_INSTRUCTION_NOT_FOUND|0);
abort();
break;
}
continue;
case 0x13:
//addi,slti,sltiu,xori,ori,andi,slli,srli,srai
switch((ins >> 12)&0x7) {
case 0x00:
//addi
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
r[((ins >> 5) & 0x7C) >> 2] = rs1 + (ins >> 20)|0;
continue;
case 0x02:
//slti
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if((rs1|0) < (ins >> 20)) r[((ins >> 5) & 0x7C) >> 2] = 0x01;
else r[((ins >> 5) & 0x7C) >> 2] = 0x00;
continue;
case 0x03:
//sltiu
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if((rs1 >>> 0) < ((ins >> 20) >>> 0)) r[((ins >> 5) & 0x7C) >> 2] = 0x01;
else r[((ins >> 5) & 0x7C) >> 2] = 0x00;
continue;
case 0x04:
//xori
imm = (ins >> 20);
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
r[((ins >> 5) & 0x7C) >> 2] = rs1 ^ (ins >> 20);
continue;
case 0x06:
//ori
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
r[((ins >> 5) & 0x7C) >> 2] = rs1 | (ins >> 20);
continue;
case 0x07:
//andi
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
r[((ins >> 5) & 0x7C) >> 2] = rs1 & (ins >> 20);
continue;
case 0x01:
//slli
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
r[((ins >> 5) & 0x7C) >> 2] = rs1 << ((ins >> 20) & 0x1F);
continue;
case 0x05:
if(((ins >> 25) & 0x7F) == 0x00){
//srli
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
r[((ins >> 5) & 0x7C) >> 2] = rs1 >>> ((ins >> 20) & 0x1F);
}
else if(((ins >> 25) & 0x7F) == 0x20){
//srai
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
r[((ins >> 5) & 0x7C) >> 2] = rs1 >> ((ins >> 20) & 0x1F);
}
continue;
default:
DebugMessage(ERROR_INSTRUCTION_NOT_FOUND|0);
abort();
break;
}
continue;
case 0x33:
//add,sub,sll,slt,sltu,xor,srl,sra,or,and
switch((ins >> 25)&0x7F) {
case 0x00:
//add,slt,sltu,add,or,xor,sll,srl
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
rs2 = r[((ins >> 18) & 0x7C) >> 2]|0;
switch((ins >> 12)&0x7) {
case 0x00:
//add
r[((ins >> 5) & 0x7C) >> 2] = rs1 + rs2;
continue;
case 0x02:
//slt
if((rs1|0) < (rs2|0)) r[((ins >> 5) & 0x7C) >> 2] = 0x01;
else r[((ins >> 5) & 0x7C) >> 2] = 0x00;
continue;
case 0x03:
//sltu
if((rs1 >>> 0) < (rs2 >>> 0)) r[((ins >> 5) & 0x7C) >> 2] = 0x01;
else r[((ins >> 5) & 0x7C) >> 2] = 0x00;
continue;
case 0x07:
//and
r[((ins >> 5) & 0x7C) >> 2] = rs1 & rs2;
continue;
case 0x06:
//or
r[((ins >> 5) & 0x7C) >> 2] = rs1 | rs2;
continue;
case 0x04:
//xor
r[((ins >> 5) & 0x7C) >> 2] = rs1 ^ rs2;
continue;
case 0x01:
//sll
r[((ins >> 5) & 0x7C) >> 2] = rs1 << (rs2 & 0x1F);
continue;
case 0x05:
//srl
r[((ins >> 5) & 0x7C) >> 2] = rs1 >>> (rs2 & 0x1F);
continue;
}
continue;
case 0x20:
//sub, sra
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
rs2 = r[((ins >> 18) & 0x7C) >> 2]|0;
switch((ins >> 12)&0x7) {
case 0x00:
//sub
r[((ins >> 5) & 0x7C) >> 2] = rs1 - rs2;
continue;
case 0x05:
//sra
r[((ins >> 5) & 0x7C) >> 2] = rs1 >> (rs2 & 0x1F);
continue;
}
continue;
case 0x01:
//mul,mulh,mulhsu,mulhu,div,divu,rem,remu
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
rs2 = r[((ins >> 18) & 0x7C) >> 2]|0;
switch((ins >> 12)&0x7) {
case 0x00:
//mul
mult = mul(rs1|0,rs2|0)|0;
r[((ins >> 5) & 0x7C) >> 2] = mult & 0xFFFFFFFF;
continue;
case 0x01:
//mulh
result = UMul(rs1,rs2, 1)|0;
r[((ins >> 5) & 0x7C) >> 2] = result;
continue;
case 0x02:
//mulhsu
result = SUMul(rs1,rs2>>>0, 1)|0;
r[((ins >> 5) & 0x7C) >> 2] = result;
continue;
case 0x03:
//mulhu
result = IMul(rs1>>>0, rs2>>>0, 1)|0;
r[((ins >> 5) & 0x7C) >> 2] = result;
continue;
case 0x04:
//div
if((rs2|0) == 0)
quo = -1;
else
quo = ((rs1|0) / (rs2|0))|0;
r[((ins >> 5) & 0x7C) >> 2] = quo;
continue;
case 0x05:
//divu
if((rs2|0) == 0)
quo = 0xFFFFFFFF;
else
quo = ((rs1 >>> 0) / (rs2 >>> 0))|0;
r[((ins >> 5) & 0x7C) >> 2] = quo;
continue;
case 0x06:
//rem
if((rs2|0) == 0)
rem = rs1;
else
rem = ((rs1|0) % (rs2|0))|0;
r[((ins >> 5) & 0x7C) >> 2] = rem;
continue;
case 0x07:
//remu
if((rs2|0) == 0)
rem = (rs1 >>> 0);
else
rem = ((rs1 >>> 0) % (rs2 >>> 0))|0;
r[((ins >> 5) & 0x7C) >> 2] = rem;
continue;
}
continue;
default:
DebugMessage(ERROR_INSTRUCTION_NOT_FOUND|0);
abort();
break;
}
continue;
case 0x37:
//lui
r[((ins >> 5) & 0x7C) >> 2] = (ins & 0xFFFFF000);
continue;
case 0x17:
//auipc
pc = pcorigin + (ppc-ppcorigin)|0;
imm = (ins & 0xFFFFF000);
r[((ins >> 5) & 0x7C) >> 2] = (imm + pc - 4)|0;
fence = ppc;
pc_change = 1;
continue;
case 0x6F:
//jal
pc = pcorigin + (ppc-ppcorigin)|0;
imm = (((ins >> 21) & 0x3FF) | (((ins >> 20) & 0x1) << 10) | (((ins >> 12) & 0xFF) << 11) | ((ins >> 31) << 19) ) << 1;
r[((ins >> 5) & 0x7C) >> 2] = pc;
pc = pc + imm - 4|0;
fence = ppc;
pc_change = 1;
r[0] = 0;
continue;
case 0x67:
//jalr
pc = pcorigin + (ppc-ppcorigin)|0;
imm = (ins >> 20);
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
r[((ins >> 5) & 0x7C) >> 2] = pc;
pc = ((rs1 + imm) & 0xFFFFFFFE)|0;
fence = ppc;
pc_change = 1;
r[0] = 0;
continue;
case 0x63:
//beq, bne, blt, bge, bltu, bgeu
pc = pcorigin + (ppc-ppcorigin)|0;
fence = ppc;
pc_change = 1;
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
rs2 = r[((ins >> 18) & 0x7C) >> 2]|0;
switch((ins >> 12)&0x7) {
case 0x00:
//beq
if((rs1|0) == (rs2|0)){
imm = ((((ins >> 31) << 11) | (((ins >> 25) & 0x3F) << 4) | ((ins >> 8) & 0x0F) | (((ins >> 7) & 0x01) << 10)) << 1 );
pc = pc + imm - 4|0;
}
ram[(ppc - 4) >> 2] = ((ins >> 7) << 7) | 0x68;
continue;
case 0x01:
//bne
if((rs1|0) != (rs2|0)){
imm = ((((ins >> 31) << 11) | (((ins >> 25) & 0x3F) << 4) | ((ins >> 8) & 0x0F) | (((ins >> 7) & 0x01) << 10)) << 1 );
pc = pc + imm - 4|0;
}
ram[(ppc - 4) >> 2] = ((ins >> 7) << 7) | 0x69;
continue;
case 0x04:
//blt
if((rs1|0) < (rs2|0)){
imm = ((((ins >> 31) << 11) | (((ins >> 25) & 0x3F) << 4) | ((ins >> 8) & 0x0F) | (((ins >> 7) & 0x01) << 10)) << 1 );
pc = pc + imm - 4|0;
}
ram[(ppc - 4) >> 2] = ((ins >> 7) << 7) | 0x6A;
continue;
case 0x05:
//bge
if((rs1|0) >= (rs2|0)){
imm = ((((ins >> 31) << 11) | (((ins >> 25) & 0x3F) << 4) | ((ins >> 8) & 0x0F) | (((ins >> 7) & 0x01) << 10)) << 1 );
pc = pc + imm - 4|0;
}
ram[(ppc - 4) >> 2] = ((ins >> 7) << 7) | 0x6B;
continue;
case 0x06:
//bltu
if((rs1 >>> 0) < (rs2 >>> 0)){
imm = ((((ins >> 31) << 11) | (((ins >> 25) & 0x3F) << 4) | ((ins >> 8) & 0x0F) | (((ins >> 7) & 0x01) << 10)) << 1 );
pc = pc + imm - 4|0;
}
ram[(ppc - 4) >> 2] = ((ins >> 7) << 7) | 0x6C;
continue;
case 0x07:
//bgeu
if((rs1 >>> 0) >= (rs2 >>> 0)){
imm = ((((ins >> 31) << 11) | (((ins >> 25) & 0x3F) << 4) | ((ins >> 8) & 0x0F) | (((ins >> 7) & 0x01) << 10)) << 1 );
pc = pc + imm - 4|0;
}
ram[(ppc - 4) >> 2] = ((ins >> 7) << 7) | 0x6D;
continue;
default:
DebugMessage(ERROR_INSTRUCTION_NOT_FOUND|0);
abort();
break;
}
continue;
case 0x73:
//csrrw, csrrs, csrrc, csrrwi, csrrsi, csrrci, ecall, eret, ebreak, mrts, wfi
imm = (ins >>> 20);
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
switch((ins >> 12)&0x7) {
case 0x01:
//csrrw
r[((ins >> 5) & 0x7C) >> 2] = GetCSR(imm)|0;
//if (rindex != ((ins >> 15) & 0x1F))
SetCSR(imm, rs1);
r[0] = 0;
continue;
case 0x02:
//csrrs
r[((ins >> 5) & 0x7C) >> 2] = GetCSR(imm)|0;
SetCSR(imm, (GetCSR(imm)|0) | rs1);
r[0] = 0;
continue;
case 0x03:
//csrrc
r[((ins >> 5) & 0x7C) >> 2] = GetCSR(imm)|0;
SetCSR(imm, (GetCSR(imm)|0) & (~rs1));
r[0] = 0;
continue;
case 0x05:
//csrrwi
r[((ins >> 5) & 0x7C) >> 2] = GetCSR(imm)|0;
zimm = (ins >> 15) & 0x1F;
if((zimm|0) != 0) SetCSR(imm, (zimm >> 0));
r[0] = 0;
continue;
case 0x06:
//csrrsi
r[((ins >> 5) & 0x7C) >> 2] = GetCSR(imm)|0;
zimm = (ins >> 15) & 0x1F;
if((zimm|0) != 0) SetCSR(imm, (GetCSR(imm)|0) | (zimm >> 0));
r[0] = 0;
continue;
case 0x07:
//csrrci
r[((ins >> 5) & 0x7C) >> 2] = GetCSR(imm)|0;
zimm = (ins >> 15) & 0x1F;
if((zimm|0) != 0) SetCSR(imm, (GetCSR(imm)|0) & ~(zimm >> 0));
r[0] = 0;
continue;
case 0x00:
//ecall, eret, ebreak, mrts, wfi
current_privilege_level = (csr[(csrp + CSR_MSTATUS)>>2] & 0x06) >> 1;
fence = ppc;
switch((ins >> 20)&0xFFF) {
case 0x00:
//ecall
pc = pcorigin + (ppc-ppcorigin)|0;
switch(current_privilege_level|0)
{
case 0x00: //PRV_U
Trap(CAUSE_ENVCALL_UMODE, pc - 4|0);
break;
case 0x01: //PRV_S
Trap(CAUSE_ENVCALL_SMODE, pc - 4|0);
break;
case 0x02: //PRV_H
Trap(CAUSE_ENVCALL_HMODE, pc - 4|0);
abort();
break;
case 0x03: //PRV_M
Trap(CAUSE_ENVCALL_MMODE, pc - 4|0);
break;
default:
DebugMessage(ERROR_ECALL|0);
abort();
break;
}
continue;
case 0x001:
//ebreak
pc = pcorigin + (ppc-ppcorigin)|0;
Trap(CAUSE_BREAKPOINT, pc - 4|0);
continue;
case 0x100:
//eret
current_privilege_level = (csr[(csrp + CSR_MSTATUS)>>2] & 0x06) >> 1;
pc = pcorigin + (ppc-ppcorigin)|0;
if((current_privilege_level|0) < (PRV_S|0)) {
DebugMessage(ERROR_ERET_PRIV|0);
abort();
break;
}
PopPrivilegeStack();
switch(current_privilege_level|0)
{
case 0x01: //PRV_S
//DebugMessage("eret PRV_S -"+ utils.ToHex(ins));
pc = csr[(csrp + CSR_SEPC)>>2]|0;
break;
case 0x02: //PRV_H
//DebugMessage("Not supported eret PRV_H -"+ utils.ToHex(ins));
pc = csr[(csrp + CSR_HEPC)>>2]|0;
abort();
break;
case 0x03: //PRV_M
//DebugMessage("eret PRV_M -"+ utils.ToHex(ins));
pc = csr[(csrp + CSR_MEPC)>>2]|0;
break;
default:
DebugMessage(ERROR_ERET|0);
abort();
break;
}
pc_change = 1;
InvalidateTLB();
continue;
case 0x102:
// wfi
continue;
case 0x305:
//mrts
pc = pcorigin + (ppc-ppcorigin)|0;
if((current_privilege_level|0) != (PRV_M|0)) {
DebugMessage(ERROR_MRTS|0);
abort();
break;
}
csr[(csrp + CSR_MSTATUS)>>2] = (csr[(csrp + CSR_MSTATUS)>>2] & ~0x6) | 0x02; //Setting the Privilage level to Supervisor
csr[(csrp + CSR_SBADADDR)>>2] = csr[(csrp + CSR_MBADADDR)>>2];
csr[(csrp + CSR_SCAUSE)>>2] = csr[(csrp + CSR_MCAUSE)>>2];
csr[(csrp + CSR_SEPC)>>2] = csr[(csrp + CSR_MEPC)>>2];
pc = csr[(csrp + CSR_STVEC)>>2]|0;
pc_change = 1;
continue;
case 0x101:
//sfence.vm
InvalidateTLB();
continue;
default:
DebugMessage(ERROR_INSTRUCTION_NOT_FOUND|0);
abort();
break;
}
continue;
default:
DebugMessage(ERROR_INSTRUCTION_NOT_FOUND|0);
abort();
break;
}
continue;
case 0x07:
//flw,fld
switch((ins >> 12)&0x7) {
case 0x02:
//flw
imm = (ins >> 20);
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if(!((float_read32tlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (float_read32tlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_READ)|0;
if((paddr|0) == -1) break;
float_read32tlb_index = paddr;
float_read32tlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
r[0] = ram[(ramp + paddr) >> 2]|0;
f[(fp + (((ins >> 7) & 0x1F) << 3)) >> 3] = +ff[0];
r[0] = 0;
continue;
case 0x03:
//fld
imm = (ins >> 20);
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if(!((float_read64tlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (float_read64tlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_READ)|0;
if((paddr|0) == -1) continue;
float_read64tlb_index = paddr;
float_read64tlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
fi[(fip + ((((ins >> 7) & 0x1F) + 0) << 2)) >> 2] = ram[(ramp + paddr + 0) >> 2]|0;
fi[(fip + ((((ins >> 7) & 0x1F) + 1) << 2)) >> 2] = ram[(ramp + paddr + 4) >> 2]|0;
continue;
default:
DebugMessage(ERROR_INSTRUCTION_NOT_FOUND|0);
DebugMessage(ins|0);
abort();
break;
}
continue;
case 0x27:
//fsw, fsd
switch((ins >> 12)&0x7) {
case 0x02:
//fsw
imm = (((ins >> 25) << 5) + ((ins >> 7) & 0x1F))|0;
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
ff[0] = f[(fp + (((ins >> 20) & 0x1F) << 3)) >> 3];
if(!((float_store32tlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (float_store32tlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_READ)|0;
if((paddr|0) == -1) continue;
float_store32tlb_index = paddr;
float_store32tlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
ram[(ramp + paddr) >> 2] = r[0]|0;
r[0] = 0;
continue;
case 0x03:
//fsd
imm = (((ins >> 25) << 5) + ((ins >> 7) & 0x1F))|0;
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if(!((float_store64tlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (float_store64tlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_READ)|0;
if((paddr|0) == -1) continue;
float_store64tlb_index = paddr;
float_store64tlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
ram[(ramp + paddr + 0) >> 2] = fi[(fip + ((((ins >> 20) & 0x1F) + 0) << 2)) >> 2]|0;
ram[(ramp + paddr + 4) >> 2] = fi[(fip + ((((ins >> 20) & 0x1F) + 1) << 2)) >> 2]|0;
continue;
default:
DebugMessage(ERROR_INSTRUCTION_NOT_FOUND|0);
DebugMessage(ins|0);
abort();
break;
}
continue;
case 0x53:
//fadd.s, fsub.s
switch((ins >> 25)&0x7F) {
case 0x00: //fadd.s
case 0x01: //fadd.d
fs1 = (+f[(fp + (((ins >> 15) & 0x1F) << 3)) >> 3]);
fs2 = (+f[(fp + (((ins >> 20) & 0x1F) << 3)) >> 3]);
f[(fp + (((ins >> 7) & 0x1F) << 3)) >> 3] = fs1 + fs2;
continue;
case 0x04: //fsub.s
case 0x05: //fsub.d
fs1 = (+f[(fp + (((ins >> 15) & 0x1F) << 3)) >> 3]);
fs2 = (+f[(fp + (((ins >> 20) & 0x1F) << 3)) >> 3]);
f[(fp + (((ins >> 7) & 0x1F) << 3)) >> 3] = fs1 - fs2;
continue;
case 0x50:
case 0x51:
//fcmp.s, fcmp.d
fs1 = (+f[(fp + (((ins >> 15) & 0x1F) << 3)) >> 3]);
fs2 = (+f[(fp + (((ins >> 20) & 0x1F) << 3)) >> 3]);
switch((ins >> 12) & 0x7) {
case 0x0:
//fle
if((+fs1) <= (+fs2)) r[((ins >> 5) & 0x7C) >> 2] = 1;
else r[((ins >> 5) & 0x7C) >> 2] = 0;
continue;
case 0x1:
//flt
if((+fs1) < (+fs2)) r[((ins >> 5) & 0x7C) >> 2] = 1;
else r[((ins >> 5) & 0x7C) >> 2] = 0;
continue;
case 0x2:
//fle
if((+fs1) == (+fs2)) r[((ins >> 5) & 0x7C) >> 2] = 1;
else r[((ins >> 5) & 0x7C) >> 2] = 0;
continue;
default:
DebugMessage(ERROR_INSTRUCTION_NOT_FOUND|0);
DebugMessage(ins|0);
abort();
break;
}
continue;
case 0x60:
//fcvt.w.s
r[((ins >> 5) & 0x7C) >> 2] = (~~+f[(fp + (((ins >> 15) & 0x1F) << 3)) >> 3]);
continue;
case 0x68: //fcvt.s.w
case 0x69:
//fcvt.d.w
f[(fp + (((ins >> 7) & 0x1F) << 3)) >> 3] = (+~~r[(((ins >> 15) & 0x1F) << 2) >> 2]);
continue;
case 0x08: //fmul.s
case 0x09: //fmul.d
fs1 = (+f[(fp + (((ins >> 15) & 0x1F) << 3)) >> 3]);
fs2 = (+f[(fp + (((ins >> 20) & 0x1F) << 3)) >> 3]);
f[(fp + (((ins >> 7) & 0x1F) << 3)) >> 3] = (+mul(fs1,fs2));
continue;
case 0x10: // single precision
case 0x11: // double precision
//fsgnj
fs1 = (+f[(fp + (((ins >> 15) & 0x1F) << 3)) >> 3]);
fs2 = (+f[(fp + (((ins >> 20) & 0x1F) << 3)) >> 3]);
switch((ins >> 12) & 7) {
case 0:
//fsgnj.d, also used for fmv.d
f[(fp + (((ins >> 7) & 0x1F) << 3)) >> 3] = ((+fs2)<(+0))?-(+MathAbs(+fs1)):(+MathAbs(+fs1));
continue;
case 1:
//fsgnjn.d
f[(fp + (((ins >> 7) & 0x1F) << 3)) >> 3] = ((+fs2)<(+0))?+MathAbs(+fs1):-(+MathAbs(+fs1));
continue;
case 3:
//fsgnjx.d
f[(fp + (((ins >> 7) & 0x1F) << 3)) >> 3] =
(
(((+fs2)<(+0)) & ((+fs1)<(+0)) ) |
(((+fs2)>(+0)) & ((+fs1)>(+0)) )
)?-(+MathAbs(+fs1)):+MathAbs(+fs1);
continue;
default:
DebugMessage(ERROR_INSTRUCTION_NOT_FOUND|0);
DebugMessage(ins|0);
abort();
}
continue;
case 0x61:
//fcvt.w.d
r[((ins >> 5) & 0x7C) >> 2] = (~~+f[(fp + (((ins >> 15) & 0x1F) << 3)) >> 3]);
continue;
case 0x78:
//fmv.s.x
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
r[0] = rs1;
f[(fp + (((ins >> 7) & 0x1F) << 3)) >> 3] = +ff[0];
r[0] = 0;
continue;
default:
DebugMessage(ERROR_INSTRUCTION_NOT_FOUND|0);
DebugMessage(ins|0);
abort();
break;
}
continue;
case 0x43:
//fmadd.d,fmadd.s
fs1 = (+f[(fp + (((ins >> 15) & 0x1F) << 3)) >> 3]);
fs2 = (+f[(fp + (((ins >> 20) & 0x1F) << 3)) >> 3]);
fs3 = (+f[(fp + (((ins >> 27) & 0x1F) << 3)) >> 3]);
f[(fp + (((ins >> 7) & 0x1F) << 3)) >> 3] = fs1 * fs2 + fs3;
continue;
case 0x47:
//fmsub.d,fmsub.s
fs1 = (+f[(fp + (((ins >> 15) & 0x1F) << 3)) >> 3]);
fs2 = (+f[(fp + (((ins >> 20) & 0x1F) << 3)) >> 3]);
fs3 = (+f[(fp + (((ins >> 27) & 0x1F) << 3)) >> 3]);
f[(fp + (((ins >> 7) & 0x1F) << 3)) >> 3] = fs1 * fs2 - fs3;
continue;
case 0x4B:
//fnmadd.d,fnmadd.s
fs1 = (+f[(fp + (((ins >> 15) & 0x1F) << 3)) >> 3]);
fs2 = (+f[(fp + (((ins >> 20) & 0x1F) << 3)) >> 3]);
fs3 = (+f[(fp + (((ins >> 27) & 0x1F) << 3)) >> 3]);
f[(fp + (((ins >> 7) & 0x1F) << 3)) >> 3] = -(fs1 * fs2 + fs3);
continue;
case 0x4F:
//fnmsub.d,fnmsub.s
fs1 = (+f[(fp + (((ins >> 15) & 0x1F) << 3)) >> 3]);
fs2 = (+f[(fp + (((ins >> 20) & 0x1F) << 3)) >> 3]);
fs3 = (+f[(fp + (((ins >> 27) & 0x1F) << 3)) >> 3]);
f[(fp + (((ins >> 7) & 0x1F) << 3)) >> 3] = -(fs1 * fs2 - fs3);
continue;
case 0x2F:
//amoswap, amoadd, amoxor, amoand, amoor, amomin, amomax, amominu, amomaxu
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
rs2 = r[((ins >> 18) & 0x7C) >> 2]|0;
switch((ins >> 27)&0x1F) {
case 0x01:
//amoswap
paddr = TranslateVM(rs1|0, VM_READ)|0;
if((paddr|0) == -1) break;
r[((ins >> 5) & 0x7C) >> 2] = ram[(ramp + paddr) >> 2]|0;
paddr = TranslateVM(rs1|0, VM_WRITE)|0;
if((paddr|0) == -1) break;
ram[(ramp + paddr) >> 2] = rs2|0;
r[0] = 0;
continue;
case 0x00:
//amoadd
paddr = TranslateVM(rs1|0, VM_READ)|0;
if((paddr|0) == -1) break;
r[((ins >> 5) & 0x7C) >> 2] = ram[(ramp + paddr) >> 2]|0;
paddr = TranslateVM(rs1|0,VM_WRITE)|0;
if((paddr|0) == -1) break;
ram[(ramp + paddr) >> 2] = ((r[((ins >> 5) & 0x7C) >> 2]|0) + (rs2|0))|0;
r[0] = 0;
continue;
case 0x04:
//amoxor
paddr = TranslateVM(rs1|0, VM_READ)|0;
if((paddr|0) == -1) break;
r[((ins >> 5) & 0x7C) >> 2] = ram[(ramp + paddr) >> 2]|0;
paddr = TranslateVM(rs1|0,VM_WRITE)|0;
if((paddr|0) == -1) break;
ram[(ramp + paddr) >> 2] = ((r[((ins >> 5) & 0x7C) >> 2]|0) ^ (rs2|0))|0;
r[0] = 0;
continue;
case 0x0C:
//amoand
paddr = TranslateVM(rs1|0, VM_READ)|0;
if((paddr|0) == -1) break;
r[((ins >> 5) & 0x7C) >> 2] = ram[(ramp + paddr) >> 2]|0;
paddr = TranslateVM(rs1|0,VM_WRITE)|0;
if((paddr|0) == -1) break;
ram[(ramp + paddr) >> 2] = ((r[((ins >> 5) & 0x7C) >> 2]|0) & (rs2|0))|0;
r[0] = 0;
continue;
case 0x08:
//amoor
paddr = TranslateVM(rs1|0, VM_READ)|0;
if((paddr|0) == -1) break;
r[((ins >> 5) & 0x7C) >> 2] = ram[(ramp + paddr) >> 2]|0;
paddr = TranslateVM(rs1|0,VM_WRITE)|0;
if((paddr|0) == -1) break;
ram[(ramp + paddr) >> 2] = ((r[((ins >> 5) & 0x7C) >> 2]|0) | (rs2|0))|0;
r[0] = 0;
continue;
case 0x10:
//amomin
paddr = TranslateVM(rs1|0, VM_READ)|0;
if((paddr|0) == -1) break;
r[((ins >> 5) & 0x7C) >> 2] = ram[(ramp + paddr) >> 2]|0;
if((rs2 >> 0) > (r[((ins >> 5) & 0x7C) >> 2] >> 0)) r[0] = r[((ins >> 5) & 0x7C) >> 2];
else r[0] = rs2;
paddr = TranslateVM(rs1|0,VM_WRITE)|0;
if((paddr|0) == -1) break;
ram[(ramp + paddr) >> 2] = r[0]|0;
r[0] = 0;
continue;
case 0x14:
//amomax
paddr = TranslateVM(rs1|0,VM_READ)|0;
if((paddr|0) == -1) break;
r[((ins >> 5) & 0x7C) >> 2] = ram[(ramp + paddr) >> 2]|0;
if((rs2 >> 0) < (r[((ins >> 5) & 0x7C) >> 2] >> 0)) r[0] = r[((ins >> 5) & 0x7C) >> 2];
else r[0] = rs2;
paddr = TranslateVM(rs1|0,VM_WRITE)|0;
if((paddr|0) == -1) break;
ram[(ramp + paddr) >> 2] = r[0]|0;
r[0] = 0;
continue;
case 0x18:
//amominu
paddr = TranslateVM(rs1|0,VM_READ)|0;
if((paddr|0) == -1) break;
r[((ins >> 5) & 0x7C) >> 2] = ram[(ramp + paddr) >> 2]|0;
if((rs2 >>> 0) > (r[((ins >> 5) & 0x7C) >> 2] >>> 0)) r[0] = r[((ins >> 5) & 0x7C) >> 2];
else r[0] = rs2;
paddr = TranslateVM(rs1|0,VM_WRITE)|0;
if((paddr|0) == -1) break;
ram[(ramp + paddr) >> 2] = r[0]|0;
r[0] = 0;
continue;
case 0x1C:
//amomaxu
paddr = TranslateVM(rs1|0,VM_READ)|0;
if((paddr|0) == -1) break;
r[((ins >> 5) & 0x7C) >> 2] = ram[(ramp + paddr) >> 2]|0;
if((rs2 >>> 0) < (r[((ins >> 5) & 0x7C) >> 2] >>> 0)) r[0] = r[((ins >> 5) & 0x7C) >> 2];
else r[0] = rs2;
paddr = TranslateVM(rs1|0,VM_WRITE)|0;
if((paddr|0) == -1) break;
ram[(ramp + paddr) >> 2] = r[0]|0;
r[0] = 0;
continue;
case 0x02:
//lr.d
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
paddr = TranslateVM(rs1|0,VM_READ)|0;
if((paddr|0) == -1) break;
r[((ins >> 5) & 0x7C) >> 2] = ram[(ramp + paddr) >> 2]|0;
amoaddr = rs1;
amovalue = r[((ins >> 5) & 0x7C) >> 2]|0;
r[0] = 0;
continue;
case 0x03:
//sc.d
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
rs2 = r[((ins >> 18) & 0x7C) >> 2]|0;
if((rs1|0) != (amoaddr|0)) {
r[((ins >> 5) & 0x7C) >> 2] = 0x01;
continue;
}
paddr = TranslateVM(rs1, VM_READ)|0;
if((paddr|0) == -1) break;
if((ram[(ramp + paddr) >> 2]|0) != (amovalue|0)) {
r[((ins >> 5) & 0x7C) >> 2] = 0x01;
continue;
}
r[((ins >> 5) & 0x7C) >> 2] = 0x00;
paddr = TranslateVM(rs1, VM_WRITE)|0;
if ((paddr|0) == -1) break;
ram[(ramp + paddr) >> 2] = rs2|0;
r[0] = 0;
continue;
default:
DebugMessage(ERROR_ATOMIC_INSTRUCTION|0);
abort();
break;
}
continue;
case 0x0F:
//fence
continue;
//custom opcodes defined to make instructions take the faster route
case 0x74:
//lb
imm = (ins >> 20);
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if(!((read8tlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (read8tlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_READ)|0;
if((paddr|0) == -1) continue;
read8tlb_index = paddr;
read8tlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
r[((ins >> 5) & 0x7C) >> 2] = ((ram8[(ramp + paddr) >> 0]) << 24) >> 24;
continue;
case 0x75:
//lh
imm = (ins >> 20);
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if(!((read16tlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (read16tlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_READ)|0;
if((paddr|0) == -1) continue;
read16tlb_index = paddr;
read16tlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
r[((ins >> 5) & 0x7C) >> 2] = ((ram16[(ramp + paddr) >> 1]) << 16) >> 16;
continue;
case 0x76:
//lw
imm = (ins >> 20);
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if ((rs1+imm) & 3) {
DebugMessage(ERROR_LOAD_WORD|0);
abort();
}
if(!((read32tlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (read32tlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_READ)|0;
if((paddr|0) == -1) continue;
read32tlb_index = paddr;
read32tlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
r[((ins >> 5) & 0x7C) >> 2] = ram[(ramp + paddr) >> 2]|0;
continue;
case 0x77:
//lbu
imm = (ins >> 20);
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if(!((read8utlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (read8utlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_READ)|0;
if((paddr|0) == -1) continue;
read8utlb_index = paddr;
read8utlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
r[((ins >> 5) & 0x7C) >> 2] = (ram8[(ramp + paddr) >> 0]) & 0xFF;
continue;
case 0x78:
//lhu
imm = (ins >> 20);
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if(!((read16utlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (read16utlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_READ)|0;
if((paddr|0) == -1) continue;
read16utlb_index = paddr;
read16utlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
r[((ins >> 5) & 0x7C) >> 2] = (ram16[(ramp + paddr) >> 1]) & 0xFFFF;
continue;
case 0x79:
//sb
imm = ((ins >> 25) << 5) | ((ins >> 7) & 0x1F);
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if(!((store8tlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (store8tlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_WRITE)|0;
if((paddr|0) == -1) continue;
store8tlb_index = paddr;
store8tlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
ram8[(ramp + paddr) >> 0] = (r[((ins >> 18) & 0x7C) >> 2] & 0xFF);
continue;
case 0x7A:
//sh
imm = ((ins >> 25) << 5) | ((ins >> 7) & 0x1F);
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if(!((store16tlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (store16tlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_WRITE)|0;
if((paddr|0) == -1) continue;
store16tlb_index = paddr;
store16tlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
ram16[(ramp + paddr) >> 1] = (r[((ins >> 18) & 0x7C) >> 2] & 0xFFFF);
continue;
case 0x7B:
//sw
imm = ((ins >> 25) << 5) | ((ins >> 7) & 0x1F);
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
if ((rs1+imm) & 3) {
DebugMessage(ERROR_STORE_WORD|0);
abort();
}
if(!((store32tlb_index ^ (rs1 + imm|0)) & 0xFFFFF000)) paddr = (store32tlb_entry ^ (rs1 + imm|0));
else{
paddr = TranslateVM(rs1 + imm|0, VM_WRITE)|0;
if((paddr|0) == -1) continue;
store32tlb_index = paddr;
store32tlb_entry = ((paddr ^ (rs1 + imm|0)) & 0xFFFFF000);
}
ram[(ramp + paddr) >> 2] = r[((ins >> 18) & 0x7C) >> 2]|0;
continue;
case 0x68:
//beq
pc = pcorigin + (ppc-ppcorigin)|0;
fence = ppc;
pc_change = 1;
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
rs2 = r[((ins >> 18) & 0x7C) >> 2]|0;
if((rs1|0) == (rs2|0)){
imm = ((((ins >> 31) << 11) | (((ins >> 25) & 0x3F) << 4) | ((ins >> 8) & 0x0F) | (((ins >> 7) & 0x01) << 10)) << 1 );
pc = pc + imm - 4|0;
}
continue;
case 0x69:
//bne
pc = pcorigin + (ppc-ppcorigin)|0;
fence = ppc;
pc_change = 1;
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
rs2 = r[((ins >> 18) & 0x7C) >> 2]|0;
if((rs1|0) != (rs2|0)){
imm = ((((ins >> 31) << 11) | (((ins >> 25) & 0x3F) << 4) | ((ins >> 8) & 0x0F) | (((ins >> 7) & 0x01) << 10)) << 1 );
pc = pc + imm - 4|0;
}
continue;
case 0x6A:
//blt
pc = pcorigin + (ppc-ppcorigin)|0;
fence = ppc;
pc_change = 1;
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
rs2 = r[((ins >> 18) & 0x7C) >> 2]|0;
if((rs1|0) < (rs2|0)){
imm = ((((ins >> 31) << 11) | (((ins >> 25) & 0x3F) << 4) | ((ins >> 8) & 0x0F) | (((ins >> 7) & 0x01) << 10)) << 1 );
pc = pc + imm - 4|0;
}
continue;
case 0x6B:
//bge
pc = pcorigin + (ppc-ppcorigin)|0;
fence = ppc;
pc_change = 1;
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
rs2 = r[((ins >> 18) & 0x7C) >> 2]|0;
if((rs1|0) >= (rs2|0)){
imm = ((((ins >> 31) << 11) | (((ins >> 25) & 0x3F) << 4) | ((ins >> 8) & 0x0F) | (((ins >> 7) & 0x01) << 10)) << 1 );
pc = pc + imm - 4|0;
}
continue;
case 0x6C:
//bltu
pc = pcorigin + (ppc-ppcorigin)|0;
fence = ppc;
pc_change = 1;
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
rs2 = r[((ins >> 18) & 0x7C) >> 2]|0;
if((rs1 >>> 0) < (rs2 >>> 0)){
imm = ((((ins >> 31) << 11) | (((ins >> 25) & 0x3F) << 4) | ((ins >> 8) & 0x0F) | (((ins >> 7) & 0x01) << 10)) << 1 );
pc = pc + imm - 4|0;
}
continue;
case 0x6D:
//bgeu
pc = pcorigin + (ppc-ppcorigin)|0;
fence = ppc;
pc_change = 1;
rs1 = r[(((ins >> 15) & 0x1F) << 2) >> 2]|0;
rs2 = r[((ins >> 18) & 0x7C) >> 2]|0;
if((rs1 >>> 0) >= (rs2 >>> 0)){
imm = ((((ins >> 31) << 11) | (((ins >> 25) & 0x3F) << 4) | ((ins >> 8) & 0x0F) | (((ins >> 7) & 0x01) << 10)) << 1 );
pc = pc + imm - 4|0;
}
continue;
default:
DebugMessage(ERROR_INSTRUCTION_NOT_FOUND|0);
DebugMessage(ins|0);
abort();
break;
} // end of switch
} else // fence
{
if(!(pc_change|0)) pc = pcorigin + (ppc-ppcorigin)|0;
dsteps = dsteps - ((ppc-ppcorigin) >> 2)|0;
if ((dsteps|0) < 0) {
dsteps = dsteps + 64|0;
steps = steps - 64|0;
if((steps|0) < 0) return 0;
delta = (csr[(csrp + CSR_MTIMECMP)>>2]|0) - ticks | 0;
delta = delta + ((delta|0)<0?0xFFFFFFFF:0x0) | 0;
ticks = ticks + clockspeed| 0;
if ((delta|0) < (clockspeed|0)) {
csr[(csrp + CSR_MIP)>>2] = csr[(csrp + CSR_MIP)>>2] | 0x20;
}
// check for interrupts
current_privilege_level = (csr[(csrp + CSR_MSTATUS)>>2] & 0x06) >> 1;
interrupts = csr[(csrp + CSR_MIE)>>2] & csr[(csrp + CSR_MIP)>>2];
ie = csr[(csrp + CSR_MSTATUS)>>2] & 0x01;
if (((current_privilege_level|0) < 3) | (((current_privilege_level|0) == 3) & (ie|0))) {
if (((interrupts|0) & 0x8)) {
Trap(CAUSE_SOFTWARE_INTERRUPT, pc);
continue;
} else
if (queue_status|0) {
Trap(CAUSE_HOST_INTERRUPT, pc);
queue_status = 0;
continue;
}
}
if (((current_privilege_level|0) < 1) | (((current_privilege_level|0) == 1) & (ie|0))) {
if (((interrupts|0) & 0x2)) {
Trap(CAUSE_SOFTWARE_INTERRUPT, pc);
continue;
} else
if (((interrupts|0) & 0x20)) {
Trap(CAUSE_TIMER_INTERRUPT, pc);
continue;
}
}
} // dsteps
// get new instruction pointer
if ((instlb_index ^ pc) & 0xFFFFF000) {
ppc = TranslateVM(pc,VM_FETCH)|0;
if((ppc|0) == -1) {
ppc = fence;
continue;
}
instlb_index = pc;
instlb_entry = ((ppc ^ pc) & 0xFFFFF000);
}
ppc = ramp + (instlb_entry ^ pc)| 0;
ppcorigin = ppc;
pcorigin = pc;
fence = ((ppc >> 12) + 1) << 12; // next page
pc_change = 0;
} // end of fence
} // main loop
return 0;
};
return {
Reset: Reset,
Init: Init,
InvalidateTLB: InvalidateTLB,
Step: Step,
TranslateVM: TranslateVM,
GetCSR: GetCSR,
SetCSR: SetCSR,
Trap: Trap,
MemTrap: MemTrap,
PopPrivilegeStack: PopPrivilegeStack,
PushPrivilegeStack: PushPrivilegeStack,
IMul: IMul,
UMul: UMul,
SUMul: SUMul,
CheckVMPrivilege: CheckVMPrivilege,
GetTimeToNextInterrupt: GetTimeToNextInterrupt,
ProgressTime: ProgressTime,
GetTicks: GetTicks,
AnalyzeImage: AnalyzeImage,
CheckForInterrupt: CheckForInterrupt,
RaiseInterrupt: RaiseInterrupt,
ClearInterrupt: ClearInterrupt
};
}
module.exports = DynamicCPU;
| bsd-2-clause |
jeffmo/homebrew | Library/Formula/flow.rb | 889 | require "formula"
class Flow < Formula
homepage "http://flowtype.org/"
url "https://github.com/facebook/flow/archive/v0.6.0.tar.gz"
sha1 "8185edc3598f4261b25cc4300f3f7cee12312240"
head "https://github.com/facebook/flow.git"
bottle do
cellar :any
sha256 "b18ff22833c0bb393e67bcbf815b0bdf5ed75f2390898f8e6ace342a5d8f79f9" => :yosemite
sha256 "d438368253344540c8af406725cf8514f579ec9e7ea41fb1faa700214b131d44" => :mavericks
sha256 "72f6f76de95e9629a7907f2531adad486419c5c452189ca7cc4baae545d82174" => :mountain_lion
end
depends_on "objective-caml" => :build
def install
system "make"
bin.install "bin/flow"
(share/"flow").install "bin/examples"
end
test do
output = `#{bin}/flow single #{share}/flow/examples/01_HelloWorld`
assert_match(/This type is incompatible with/, output)
assert_match(/Found 1 error/, output)
end
end
| bsd-2-clause |
reitermarkus/homebrew-cask | Casks/plover.rb | 533 | cask "plover" do
version "3.1.1"
sha256 "c45c1c6cf797de62923d20e6e46aec0d946027b6b3cca4df2fc2db4e3183516b"
url "https://github.com/openstenoproject/plover/releases/download/v#{version}/plover-#{version}-py2-mac.dmg",
verified: "github.com/openstenoproject/plover/"
appcast "https://github.com/openstenoproject/plover/releases.atom"
name "Plover"
desc "Open-source stenotype engine"
homepage "https://www.openstenoproject.org/plover/"
app "Plover.app"
zap trash: "~/Library/Application Support/plover/"
end
| bsd-2-clause |
donbobka/homebrew-cask | Casks/kismac.rb | 517 | cask :v1 => 'kismac' do
version '0.3.3'
sha256 'd48f307c1c46a1d1a6b4465d653cf417e583bc09b7ea76d21183068066bc49bb'
url "http://update.kismacmirror.com/binaries/KisMAC-#{version}.dmg"
appcast 'http://update.kismac-ng.org/sparkle/profileInfo.php',
:sha256 => '18095f38358d65f5cbaa2a876745c7b1213d56893bc26c182138f51a2d3fa8df'
homepage 'http://kismac-ng.org/'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'KisMAC.app'
end
| bsd-2-clause |
NOAA-ORR-ERD/ol3 | src/ol/renderer/dom/dommaprenderer.js | 6517 | goog.provide('ol.renderer.dom.Map');
goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('ol.events');
goog.require('ol.events.Event');
goog.require('ol.events.EventType');
goog.require('goog.style');
goog.require('goog.vec.Mat4');
goog.require('ol');
goog.require('ol.RendererType');
goog.require('ol.array');
goog.require('ol.css');
goog.require('ol.dom');
goog.require('ol.layer.Image');
goog.require('ol.layer.Layer');
goog.require('ol.layer.Tile');
goog.require('ol.layer.Vector');
goog.require('ol.render.Event');
goog.require('ol.render.EventType');
goog.require('ol.render.canvas.Immediate');
goog.require('ol.renderer.Map');
goog.require('ol.renderer.dom.ImageLayer');
goog.require('ol.renderer.dom.Layer');
goog.require('ol.renderer.dom.TileLayer');
goog.require('ol.renderer.dom.VectorLayer');
goog.require('ol.source.State');
goog.require('ol.vec.Mat4');
/**
* @constructor
* @extends {ol.renderer.Map}
* @param {Element} container Container.
* @param {ol.Map} map Map.
*/
ol.renderer.dom.Map = function(container, map) {
goog.base(this, container, map);
/**
* @private
* @type {CanvasRenderingContext2D}
*/
this.context_ = ol.dom.createCanvasContext2D();
var canvas = this.context_.canvas;
canvas.style.position = 'absolute';
canvas.style.width = '100%';
canvas.style.height = '100%';
canvas.className = ol.css.CLASS_UNSELECTABLE;
goog.dom.insertChildAt(container, canvas, 0);
/**
* @private
* @type {!goog.vec.Mat4.Number}
*/
this.transform_ = goog.vec.Mat4.createNumber();
/**
* @type {!Element}
* @private
*/
this.layersPane_ = document.createElement('DIV');
this.layersPane_.className = ol.css.CLASS_UNSELECTABLE;
var style = this.layersPane_.style;
style.position = 'absolute';
style.width = '100%';
style.height = '100%';
// prevent the img context menu on mobile devices
ol.events.listen(this.layersPane_, ol.events.EventType.TOUCHSTART,
ol.events.Event.preventDefault);
goog.dom.insertChildAt(container, this.layersPane_, 0);
/**
* @private
* @type {boolean}
*/
this.renderedVisible_ = true;
};
goog.inherits(ol.renderer.dom.Map, ol.renderer.Map);
/**
* @inheritDoc
*/
ol.renderer.dom.Map.prototype.disposeInternal = function() {
goog.dom.removeNode(this.layersPane_);
goog.base(this, 'disposeInternal');
};
/**
* @inheritDoc
*/
ol.renderer.dom.Map.prototype.createLayerRenderer = function(layer) {
var layerRenderer;
if (ol.ENABLE_IMAGE && layer instanceof ol.layer.Image) {
layerRenderer = new ol.renderer.dom.ImageLayer(layer);
} else if (ol.ENABLE_TILE && layer instanceof ol.layer.Tile) {
layerRenderer = new ol.renderer.dom.TileLayer(layer);
} else if (ol.ENABLE_VECTOR && layer instanceof ol.layer.Vector) {
layerRenderer = new ol.renderer.dom.VectorLayer(layer);
} else {
goog.asserts.fail('unexpected layer configuration');
return null;
}
return layerRenderer;
};
/**
* @param {ol.render.EventType} type Event type.
* @param {olx.FrameState} frameState Frame state.
* @private
*/
ol.renderer.dom.Map.prototype.dispatchComposeEvent_ = function(type, frameState) {
var map = this.getMap();
if (map.hasListener(type)) {
var extent = frameState.extent;
var pixelRatio = frameState.pixelRatio;
var viewState = frameState.viewState;
var rotation = viewState.rotation;
var context = this.context_;
var canvas = context.canvas;
ol.vec.Mat4.makeTransform2D(this.transform_,
canvas.width / 2,
canvas.height / 2,
pixelRatio / viewState.resolution,
-pixelRatio / viewState.resolution,
-viewState.rotation,
-viewState.center[0], -viewState.center[1]);
var vectorContext = new ol.render.canvas.Immediate(context, pixelRatio,
extent, this.transform_, rotation);
var composeEvent = new ol.render.Event(type, map, vectorContext,
frameState, context, null);
map.dispatchEvent(composeEvent);
}
};
/**
* @inheritDoc
*/
ol.renderer.dom.Map.prototype.getType = function() {
return ol.RendererType.DOM;
};
/**
* @inheritDoc
*/
ol.renderer.dom.Map.prototype.renderFrame = function(frameState) {
if (!frameState) {
if (this.renderedVisible_) {
goog.style.setElementShown(this.layersPane_, false);
this.renderedVisible_ = false;
}
return;
}
var map = this.getMap();
if (map.hasListener(ol.render.EventType.PRECOMPOSE) ||
map.hasListener(ol.render.EventType.POSTCOMPOSE)) {
var canvas = this.context_.canvas;
var pixelRatio = frameState.pixelRatio;
canvas.width = frameState.size[0] * pixelRatio;
canvas.height = frameState.size[1] * pixelRatio;
}
this.dispatchComposeEvent_(ol.render.EventType.PRECOMPOSE, frameState);
var layerStatesArray = frameState.layerStatesArray;
ol.array.stableSort(layerStatesArray, ol.renderer.Map.sortByZIndex);
var viewResolution = frameState.viewState.resolution;
var i, ii, layer, layerRenderer, layerState;
for (i = 0, ii = layerStatesArray.length; i < ii; ++i) {
layerState = layerStatesArray[i];
layer = layerState.layer;
layerRenderer = /** @type {ol.renderer.dom.Layer} */ (
this.getLayerRenderer(layer));
goog.asserts.assertInstanceof(layerRenderer, ol.renderer.dom.Layer,
'renderer is an instance of ol.renderer.dom.Layer');
goog.dom.insertChildAt(this.layersPane_, layerRenderer.getTarget(), i);
if (ol.layer.Layer.visibleAtResolution(layerState, viewResolution) &&
layerState.sourceState == ol.source.State.READY) {
if (layerRenderer.prepareFrame(frameState, layerState)) {
layerRenderer.composeFrame(frameState, layerState);
}
} else {
layerRenderer.clearFrame();
}
}
var layerStates = frameState.layerStates;
var layerKey;
for (layerKey in this.getLayerRenderers()) {
if (!(layerKey in layerStates)) {
layerRenderer = this.getLayerRendererByKey(layerKey);
goog.asserts.assertInstanceof(layerRenderer, ol.renderer.dom.Layer,
'renderer is an instance of ol.renderer.dom.Layer');
goog.dom.removeNode(layerRenderer.getTarget());
}
}
if (!this.renderedVisible_) {
goog.style.setElementShown(this.layersPane_, true);
this.renderedVisible_ = true;
}
this.calculateMatrices2D(frameState);
this.scheduleRemoveUnusedLayerRenderers(frameState);
this.scheduleExpireIconCache(frameState);
this.dispatchComposeEvent_(ol.render.EventType.POSTCOMPOSE, frameState);
};
| bsd-2-clause |
com123/spreemodif | sample/db/sample/spree/preferences.rb | 837 | shipping_method = Spree::ShippingMethod.find_by_name("UPS Ground (USD)")
shipping_method.calculator.preferred_amount = 5
shipping_method.calculator.preferred_currency = 'USD'
shipping_method = Spree::ShippingMethod.find_by_name("UPS Ground (EUR)")
shipping_method.calculator.preferred_amount = 5
shipping_method.calculator.preferred_currency = 'EUR'
shipping_method = Spree::ShippingMethod.find_by_name("UPS One Day (USD)")
shipping_method.calculator.preferred_amount = 15
shipping_method.calculator.preferred_currency = 'USD'
shipping_method = Spree::ShippingMethod.find_by_name("UPS Two Day (USD)")
shipping_method.calculator.preferred_amount = 10
shipping_method.calculator.preferred_currency = 'USD'
# flat_rate_five_dollars:
# name: amount
# owner: flat_rate_coupon_calculator
# owner_type: Spree::Calculator
# value: 5
| bsd-3-clause |
google/skia | tests/DequeTest.cpp | 5068 | /*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/private/SkDeque.h"
#include "tests/Test.h"
static void assert_count(skiatest::Reporter* reporter, const SkDeque& deq, int count) {
if (0 == count) {
REPORTER_ASSERT(reporter, deq.empty());
REPORTER_ASSERT(reporter, 0 == deq.count());
REPORTER_ASSERT(reporter, sizeof(int) == deq.elemSize());
REPORTER_ASSERT(reporter, nullptr == deq.front());
REPORTER_ASSERT(reporter, nullptr == deq.back());
} else {
REPORTER_ASSERT(reporter, !deq.empty());
REPORTER_ASSERT(reporter, count == deq.count());
REPORTER_ASSERT(reporter, sizeof(int) == deq.elemSize());
REPORTER_ASSERT(reporter, deq.front());
REPORTER_ASSERT(reporter, deq.back());
if (1 == count) {
REPORTER_ASSERT(reporter, deq.back() == deq.front());
} else {
REPORTER_ASSERT(reporter, deq.back() != deq.front());
}
}
}
static void assert_iter(skiatest::Reporter* reporter, const SkDeque& deq,
int max, int min) {
// test forward iteration
SkDeque::Iter iter(deq, SkDeque::Iter::kFront_IterStart);
void* ptr;
int value = max;
while ((ptr = iter.next())) {
REPORTER_ASSERT(reporter, value == *(int*)ptr);
value -= 1;
}
REPORTER_ASSERT(reporter, value+1 == min);
// test reverse iteration
iter.reset(deq, SkDeque::Iter::kBack_IterStart);
value = min;
while ((ptr = iter.prev())) {
REPORTER_ASSERT(reporter, value == *(int*)ptr);
value += 1;
}
REPORTER_ASSERT(reporter, value-1 == max);
// test mixed iteration
iter.reset(deq, SkDeque::Iter::kFront_IterStart);
value = max;
// forward iteration half-way
for (int i = 0; i < deq.count()/2 && (ptr = iter.next()); i++) {
REPORTER_ASSERT(reporter, value == *(int*)ptr);
value -= 1;
}
// then back down w/ reverse iteration
while ((ptr = iter.prev())) {
REPORTER_ASSERT(reporter, value == *(int*)ptr);
value += 1;
}
REPORTER_ASSERT(reporter, value-1 == max);
}
// This helper is intended to only give the unit test access to SkDeque's
// private numBlocksAllocated method
class DequeUnitTestHelper {
public:
int fNumBlocksAllocated;
DequeUnitTestHelper(const SkDeque& deq) {
fNumBlocksAllocated = deq.numBlocksAllocated();
}
};
static void assert_blocks(skiatest::Reporter* reporter,
const SkDeque& deq,
int allocCount) {
DequeUnitTestHelper helper(deq);
if (0 == deq.count()) {
REPORTER_ASSERT(reporter, 1 == helper.fNumBlocksAllocated);
} else {
int expected = (deq.count() + allocCount - 1) / allocCount;
// A block isn't freed in the deque when it first becomes empty so
// sometimes an extra block lingers around
REPORTER_ASSERT(reporter,
expected == helper.fNumBlocksAllocated ||
expected+1 == helper.fNumBlocksAllocated);
}
}
static void TestSub(skiatest::Reporter* reporter, int allocCount) {
SkDeque deq(sizeof(int), allocCount);
int i;
// test pushing on the front
assert_count(reporter, deq, 0);
for (i = 1; i <= 10; i++) {
*(int*)deq.push_front() = i;
}
assert_count(reporter, deq, 10);
assert_iter(reporter, deq, 10, 1);
assert_blocks(reporter, deq, allocCount);
for (i = 0; i < 5; i++) {
deq.pop_front();
}
assert_count(reporter, deq, 5);
assert_iter(reporter, deq, 5, 1);
assert_blocks(reporter, deq, allocCount);
for (i = 0; i < 5; i++) {
deq.pop_front();
}
assert_count(reporter, deq, 0);
assert_blocks(reporter, deq, allocCount);
// now test pushing on the back
for (i = 10; i >= 1; --i) {
*(int*)deq.push_back() = i;
}
assert_count(reporter, deq, 10);
assert_iter(reporter, deq, 10, 1);
assert_blocks(reporter, deq, allocCount);
for (i = 0; i < 5; i++) {
deq.pop_back();
}
assert_count(reporter, deq, 5);
assert_iter(reporter, deq, 10, 6);
assert_blocks(reporter, deq, allocCount);
for (i = 0; i < 5; i++) {
deq.pop_back();
}
assert_count(reporter, deq, 0);
assert_blocks(reporter, deq, allocCount);
// now test pushing/popping on both ends
*(int*)deq.push_front() = 5;
*(int*)deq.push_back() = 4;
*(int*)deq.push_front() = 6;
*(int*)deq.push_back() = 3;
*(int*)deq.push_front() = 7;
*(int*)deq.push_back() = 2;
*(int*)deq.push_front() = 8;
*(int*)deq.push_back() = 1;
assert_count(reporter, deq, 8);
assert_iter(reporter, deq, 8, 1);
assert_blocks(reporter, deq, allocCount);
}
DEF_TEST(Deque, reporter) {
// test it once with the default allocation count
TestSub(reporter, 1);
// test it again with a generous allocation count
TestSub(reporter, 10);
}
| bsd-3-clause |
ltilve/ChromiumGStreamerBackend | extensions/browser/load_monitoring_extension_host_queue_unittest.cc | 12338 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <limits>
#include "base/memory/scoped_vector.h"
#include "base/run_loop.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "extensions/browser/deferred_start_render_host.h"
#include "extensions/browser/extensions_test.h"
#include "extensions/browser/load_monitoring_extension_host_queue.h"
#include "extensions/browser/serial_extension_host_queue.h"
namespace extensions {
namespace {
class StubDeferredStartRenderHost : public DeferredStartRenderHost {
public:
// Returns true if this host is being observed by |observer|.
bool IsObservedBy(DeferredStartRenderHostObserver* observer) {
return observers_.count(observer) > 0;
}
private:
// DeferredStartRenderHost:
void AddDeferredStartRenderHostObserver(
DeferredStartRenderHostObserver* observer) override {
observers_.insert(observer);
}
void RemoveDeferredStartRenderHostObserver(
DeferredStartRenderHostObserver* observer) override {
observers_.erase(observer);
}
void CreateRenderViewNow() override {}
std::set<DeferredStartRenderHostObserver*> observers_;
};
const size_t g_invalid_size_t = std::numeric_limits<size_t>::max();
} // namespace
class LoadMonitoringExtensionHostQueueTest : public ExtensionsTest {
public:
LoadMonitoringExtensionHostQueueTest()
: finished_(false),
// Arbitrary choice of an invalid size_t.
num_queued_(g_invalid_size_t),
num_loaded_(g_invalid_size_t),
max_awaiting_loading_(g_invalid_size_t),
max_active_loading_(g_invalid_size_t) {}
void SetUp() override {
queue_.reset(new LoadMonitoringExtensionHostQueue(
// Use a SerialExtensionHostQueue because it's simple.
scoped_ptr<ExtensionHostQueue>(new SerialExtensionHostQueue()),
base::TimeDelta(), // no delay, easier to test
base::Bind(&LoadMonitoringExtensionHostQueueTest::Finished,
base::Unretained(this))));
}
protected:
// Creates a new DeferredStartRenderHost. Ownership is held by this class,
// not passed to caller.
StubDeferredStartRenderHost* CreateHost() {
StubDeferredStartRenderHost* stub = new StubDeferredStartRenderHost();
stubs_.push_back(stub);
return stub;
}
// Our single LoadMonitoringExtensionHostQueue instance.
LoadMonitoringExtensionHostQueue* queue() { return queue_.get(); }
// Returns true if the queue has finished monitoring.
bool finished() const { return finished_; }
// These are available after the queue has finished (in which case finished()
// will return true).
size_t num_queued() { return num_queued_; }
size_t num_loaded() { return num_loaded_; }
size_t max_awaiting_loading() { return max_awaiting_loading_; }
size_t max_active_loading() { return max_active_loading_; }
private:
// Callback when queue has finished monitoring.
void Finished(size_t num_queued,
size_t num_loaded,
size_t max_awaiting_loading,
size_t max_active_loading) {
CHECK(!finished_);
finished_ = true;
num_queued_ = num_queued;
num_loaded_ = num_loaded;
max_awaiting_loading_ = max_awaiting_loading;
max_active_loading_ = max_active_loading;
}
content::TestBrowserThreadBundle thread_bundle_;
scoped_ptr<LoadMonitoringExtensionHostQueue> queue_;
ScopedVector<StubDeferredStartRenderHost> stubs_;
// Set after the queue has finished monitoring.
bool finished_;
size_t num_queued_;
size_t num_loaded_;
size_t max_awaiting_loading_;
size_t max_active_loading_;
};
// Tests that if monitoring is never started, nor any hosts added, nothing is
// recorded.
TEST_F(LoadMonitoringExtensionHostQueueTest, NeverStarted) {
base::RunLoop().RunUntilIdle();
ASSERT_FALSE(finished());
}
// Tests that if monitoring has started but no hosts added, it's recorded as 0.
TEST_F(LoadMonitoringExtensionHostQueueTest, NoHosts) {
queue()->StartMonitoring();
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(finished());
EXPECT_EQ(0u, num_queued());
EXPECT_EQ(0u, num_loaded());
EXPECT_EQ(0u, max_awaiting_loading());
EXPECT_EQ(0u, max_active_loading());
}
// Tests that adding a host starts monitoring.
TEST_F(LoadMonitoringExtensionHostQueueTest, AddOneHost) {
queue()->Add(CreateHost());
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(finished());
EXPECT_EQ(1u, num_queued());
EXPECT_EQ(0u, num_loaded());
EXPECT_EQ(1u, max_awaiting_loading());
EXPECT_EQ(0u, max_active_loading());
}
// Tests that a host added and removed is still recorded, but not as a load
// finished.
TEST_F(LoadMonitoringExtensionHostQueueTest, AddAndRemoveOneHost) {
DeferredStartRenderHost* host = CreateHost();
queue()->Add(host);
queue()->Remove(host);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(finished());
EXPECT_EQ(1u, num_queued());
EXPECT_EQ(0u, num_loaded());
EXPECT_EQ(1u, max_awaiting_loading());
EXPECT_EQ(0u, max_active_loading());
}
// Tests adding and starting a single host.
TEST_F(LoadMonitoringExtensionHostQueueTest, AddAndStartOneHost) {
DeferredStartRenderHost* host = CreateHost();
queue()->Add(host);
queue()->OnDeferredStartRenderHostDidStartFirstLoad(host);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(finished());
EXPECT_EQ(1u, num_queued());
EXPECT_EQ(0u, num_loaded());
EXPECT_EQ(1u, max_awaiting_loading());
EXPECT_EQ(1u, max_active_loading());
}
// Tests adding and destroying a single host without starting it.
TEST_F(LoadMonitoringExtensionHostQueueTest, AddAndDestroyOneHost) {
DeferredStartRenderHost* host = CreateHost();
queue()->Add(host);
queue()->OnDeferredStartRenderHostDestroyed(host);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(finished());
EXPECT_EQ(1u, num_queued());
EXPECT_EQ(0u, num_loaded());
EXPECT_EQ(1u, max_awaiting_loading());
EXPECT_EQ(0u, max_active_loading());
}
// Tests adding, starting, and stopping a single host.
TEST_F(LoadMonitoringExtensionHostQueueTest, AddAndStartAndStopOneHost) {
DeferredStartRenderHost* host = CreateHost();
queue()->Add(host);
queue()->OnDeferredStartRenderHostDidStartFirstLoad(host);
queue()->OnDeferredStartRenderHostDidStopFirstLoad(host);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(finished());
EXPECT_EQ(1u, num_queued());
EXPECT_EQ(1u, num_loaded());
EXPECT_EQ(1u, max_awaiting_loading());
EXPECT_EQ(1u, max_active_loading());
}
// Tests adding, starting, and stopping a single host - twice.
TEST_F(LoadMonitoringExtensionHostQueueTest, AddAndStartAndStopOneHostTwice) {
DeferredStartRenderHost* host = CreateHost();
queue()->Add(host);
queue()->OnDeferredStartRenderHostDidStartFirstLoad(host);
queue()->OnDeferredStartRenderHostDidStopFirstLoad(host);
// Re-starting loading should also be recorded fine (e.g. navigations could
// trigger this).
queue()->OnDeferredStartRenderHostDidStartFirstLoad(host);
queue()->OnDeferredStartRenderHostDidStopFirstLoad(host);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(finished());
EXPECT_EQ(1u, num_queued());
EXPECT_EQ(2u, num_loaded()); // 2 loaded this time, because we ran twice
EXPECT_EQ(1u, max_awaiting_loading());
EXPECT_EQ(1u, max_active_loading());
}
// Tests adding, starting, and destroying (i.e. an implicit stop) a single host.
TEST_F(LoadMonitoringExtensionHostQueueTest, AddAndStartAndDestroyOneHost) {
DeferredStartRenderHost* host = CreateHost();
queue()->Add(host);
queue()->OnDeferredStartRenderHostDidStartFirstLoad(host);
queue()->OnDeferredStartRenderHostDestroyed(host);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(finished());
EXPECT_EQ(1u, num_queued());
EXPECT_EQ(1u, num_loaded());
EXPECT_EQ(1u, max_awaiting_loading());
EXPECT_EQ(1u, max_active_loading());
}
// Tests adding, starting, and removing a single host.
TEST_F(LoadMonitoringExtensionHostQueueTest, AddAndStartAndRemoveOneHost) {
DeferredStartRenderHost* host = CreateHost();
queue()->Add(host);
queue()->OnDeferredStartRenderHostDidStartFirstLoad(host);
queue()->Remove(host);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(finished());
EXPECT_EQ(1u, num_queued());
EXPECT_EQ(0u, num_loaded());
EXPECT_EQ(1u, max_awaiting_loading());
EXPECT_EQ(1u, max_active_loading());
}
// Tests monitoring a sequence of hosts.
TEST_F(LoadMonitoringExtensionHostQueueTest, Sequence) {
// Scenario:
//
// 6 hosts will be added, only 5 will start loading, with a maximum of 4 in
// the queue and 3 loading at any time. Only 2 will finish.
DeferredStartRenderHost* host1 = CreateHost();
DeferredStartRenderHost* host2 = CreateHost();
DeferredStartRenderHost* host3 = CreateHost();
DeferredStartRenderHost* host4 = CreateHost();
DeferredStartRenderHost* host5 = CreateHost();
DeferredStartRenderHost* host6 = CreateHost();
queue()->Add(host1);
queue()->Add(host2);
queue()->Add(host3);
queue()->OnDeferredStartRenderHostDidStartFirstLoad(host1);
queue()->OnDeferredStartRenderHostDidStartFirstLoad(host2);
queue()->OnDeferredStartRenderHostDidStopFirstLoad(host1);
queue()->Add(host4);
queue()->Add(host5);
queue()->Add(host6);
queue()->OnDeferredStartRenderHostDidStartFirstLoad(host3);
queue()->OnDeferredStartRenderHostDidStartFirstLoad(host4);
queue()->OnDeferredStartRenderHostDidStopFirstLoad(host4);
queue()->OnDeferredStartRenderHostDidStartFirstLoad(host5);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(finished());
EXPECT_EQ(6u, num_queued());
EXPECT_EQ(2u, num_loaded());
EXPECT_EQ(4u, max_awaiting_loading());
EXPECT_EQ(3u, max_active_loading());
// Complete a realistic sequence by stopping and/or destroying all hosts.
queue()->OnDeferredStartRenderHostDestroyed(host1);
queue()->OnDeferredStartRenderHostDidStopFirstLoad(host2);
queue()->OnDeferredStartRenderHostDestroyed(host2);
queue()->OnDeferredStartRenderHostDidStopFirstLoad(host3);
queue()->OnDeferredStartRenderHostDestroyed(host3);
queue()->OnDeferredStartRenderHostDestroyed(host4);
queue()->OnDeferredStartRenderHostDestroyed(host5); // never stopped
queue()->OnDeferredStartRenderHostDestroyed(host6); // never started/stopped
}
// Tests that the queue is observing Hosts from adding them through to being
// removed - that the load sequence itself is irrelevant.
//
// This is an unfortunate implementation-style test, but it used to be a bug
// and difficult to catch outside of a proper test framework - one in which we
// don't have to trigger events by hand.
TEST_F(LoadMonitoringExtensionHostQueueTest, ObserverLifetime) {
StubDeferredStartRenderHost* host1 = CreateHost();
StubDeferredStartRenderHost* host2 = CreateHost();
StubDeferredStartRenderHost* host3 = CreateHost();
StubDeferredStartRenderHost* host4 = CreateHost();
EXPECT_FALSE(host1->IsObservedBy(queue()));
EXPECT_FALSE(host2->IsObservedBy(queue()));
EXPECT_FALSE(host3->IsObservedBy(queue()));
EXPECT_FALSE(host4->IsObservedBy(queue()));
queue()->Add(host1);
queue()->Add(host2);
queue()->Add(host3);
queue()->Add(host4);
EXPECT_TRUE(host1->IsObservedBy(queue()));
EXPECT_TRUE(host2->IsObservedBy(queue()));
EXPECT_TRUE(host3->IsObservedBy(queue()));
EXPECT_TRUE(host4->IsObservedBy(queue()));
queue()->OnDeferredStartRenderHostDidStartFirstLoad(host1);
queue()->OnDeferredStartRenderHostDidStartFirstLoad(host2);
queue()->OnDeferredStartRenderHostDidStartFirstLoad(host3);
// host4 will test that we Remove before Starting - so don't start.
EXPECT_TRUE(host1->IsObservedBy(queue()));
EXPECT_TRUE(host2->IsObservedBy(queue()));
EXPECT_TRUE(host3->IsObservedBy(queue()));
EXPECT_TRUE(host4->IsObservedBy(queue()));
queue()->OnDeferredStartRenderHostDidStopFirstLoad(host1);
queue()->OnDeferredStartRenderHostDestroyed(host2);
EXPECT_TRUE(host1->IsObservedBy(queue()));
EXPECT_TRUE(host2->IsObservedBy(queue()));
queue()->Remove(host1);
queue()->Remove(host2);
queue()->Remove(host3);
queue()->Remove(host4);
EXPECT_FALSE(host1->IsObservedBy(queue()));
EXPECT_FALSE(host2->IsObservedBy(queue()));
EXPECT_FALSE(host3->IsObservedBy(queue()));
EXPECT_FALSE(host4->IsObservedBy(queue()));
}
} // namespace extensions
| bsd-3-clause |
noikiy/amfphp-2.0 | BackOffice/Header.inc.php | 2835 | <?php
/**
* This file is part of amfPHP
*
* LICENSE
*
* top link bar
*
* This source file is subject to the license that is bundled
* with this package in the file license.txt.
* @package Amfphp_Backoffice
*
* note: there is a weird rendering error in FF if the news and sign out btns are too near the top. A line of pixels
* goes missing or something. So be vcareful when redimensioning
*/
/**+
* dummy to get rid of phpdocumentor error...
*/
$temp = 0;
?>
<div id="header">
<div id="line1" class="headerLine">
<div class="overFlowAuto middleBound">
<p class="alignLeft" id="titleP">
<span class="titleSpan">Amfphp <span class="backoffice">Back Office</span></span>
</p>
<table class="alignRight" style="overflow: hidden">
<tr>
<td><div onclick="amfphpUpdates.toggleNews()" id="newsLink" class="alignLeft">
<div id="textNewsLink">Show<br/>News</div>
</div></td>
<td><div onclick="window.location='SignOut.php';" id="signOutLink" class="alignLeft">
<div id="textSignOutLink">Sign<br/>Out</div>
</div></td>
</tr>
</table>
</div>
</div>
<div id="line2" class="headerLine">
<div class="overFlowAuto middleBound">
<p class="alignLeft" id="tabNavP">
<a class="important" href="index.php" id="homeLink">Home</a>
<a class="important" href="ServiceBrowser.php" id="serviceBrowserLink">Service Browser</a>
<a class="important" href="ClientGenerator.php" id="clientGeneratorLink">Client Generator</a>
<a class="important" href="Profiler.php" id="profilerLink">Profiler</a>
</p>
<div class="alignRight" id="silexLabsLink" onclick="window.open('http://silexlabs.org','_blank');"></div>
</div>
</div>
<div id="line3" class="overFlowAuto middleBound headerLine">
<p class="alignLeft" id="tabNameP">
<span id="tabName"></span>
</p>
<p class="alignRight">
<span id="currentVersionPre">You are running </span>
<span id="currentVersion"><?php echo AMFPHP_VERSION; ?></span>
<br/>
<span id="latestVersionInfo"> </span>
</p>
<div id="newsPopup">
<div id="newsPopupTitle">
<span class="newsDivTitle" id="newsPopupTitleText">Amfphp News</span>
<p class="alignRight">
<a onclick="amfphpUpdates.toggleNews();"><img src="img/Close.png"></img></a>
</p>
</div>
</div>
</div>
</div> | bsd-3-clause |
Eric89GXL/mnefun | mnefun/tests/test_atlas.py | 419 | import pytest
from mnefun import get_atlas_mapping
@pytest.mark.parametrize('atlas, count, label_21', [
('LBPA40', 56, 'L_superior_frontal_gyrus'),
('IXI', 83, 'Insula_right'),
])
def test_get_atlas_mapping(atlas, count, label_21):
"""Test getting atlas mappings."""
mapping = get_atlas_mapping(atlas)
assert label_21 in mapping
assert mapping[label_21] == 21
assert len(mapping) == count
| bsd-3-clause |
bodepd/consulate | consulate/adapters.py | 3377 | """
HTTP Client Library Adapters
"""
import json
import logging
import requests
try:
import requests_unixsocket
except ImportError:
requests_unixsocket = None
from consulate import api
from consulate import utils
LOGGER = logging.getLogger(__name__)
CONTENT_FORM = 'application/x-www-form-urlencoded; charset=utf-8'
CONTENT_JSON = 'application/json; charset=utf-8'
def prepare_data(fun):
"""Decorator for transforming the data being submitted to Consul
:param function fun: The decorated function
"""
def inner(*args, **kwargs):
"""Inner wrapper function for the decorator
:param list args: positional arguments
:param dict kwargs: keyword arguments
"""
if kwargs.get('data'):
if not utils.is_string(kwargs.get('data')):
kwargs['data'] = json.dumps(kwargs['data'])
elif len(args) == 3 and not utils.is_string(args[2]):
args = args[0], args[1], json.dumps(args[2])
return fun(*args, **kwargs)
return inner
class Request(object):
"""The Request adapter class"""
def __init__(self, timeout=None):
"""
Create a new request adapter instance.
:param int timeout: [optional] timeout to use while sending requests
to consul.
"""
self.session = requests.Session()
self.timeout = timeout
def delete(self, uri):
"""Perform a HTTP delete
:param src uri: The URL to send the DELETE to
:rtype: consulate.api.Response
"""
LOGGER.debug("DELETE %s", uri)
return self._process_response(self.session.delete(uri,
timeout=self.timeout))
def get(self, uri):
"""Perform a HTTP get
:param src uri: The URL to send the DELETE to
:rtype: consulate.api.Response
"""
LOGGER.debug("GET %s", uri)
return self._process_response(self.session.get(uri,
timeout=self.timeout))
@prepare_data
def put(self, uri, data=None):
"""Perform a HTTP put
:param src uri: The URL to send the DELETE to
:param str data: The PUT data
:rtype: consulate.api.Response
"""
LOGGER.debug("PUT %s with %r", uri, data)
headers = {
'Content-Type': CONTENT_FORM
if utils.is_string(data) else CONTENT_JSON
}
return self._process_response(self.session.put(uri,
data=data,
headers=headers,
timeout=self.timeout))
@staticmethod
def _process_response(response):
"""Build an api.Response object based upon the requests response
object.
:param requests.response response: The requests response
:rtype: consulate.api.Response
"""
return api.Response(response.status_code, response.content,
response.headers)
class UnixSocketRequest(Request):
"""Use to communicate with Consul over a Unix socket"""
def __init__(self, timeout=None):
super(UnixSocketRequest, self).__init__(timeout)
self.session = requests_unixsocket.Session()
| bsd-3-clause |
android-ia/platform_external_chromium_org_third_party_libjingle_source_talk | xmpp/presenceouttask.cc | 5014 | /*
* libjingle
* Copyright 2004--2005, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <time.h>
#include <sstream>
#include "talk/xmpp/constants.h"
#include "talk/xmpp/presenceouttask.h"
#include "talk/xmpp/xmppclient.h"
#include "webrtc/base/stringencode.h"
namespace buzz {
XmppReturnStatus
PresenceOutTask::Send(const PresenceStatus & s) {
if (GetState() != STATE_INIT && GetState() != STATE_START)
return XMPP_RETURN_BADSTATE;
XmlElement * presence = TranslateStatus(s);
QueueStanza(presence);
delete presence;
return XMPP_RETURN_OK;
}
XmppReturnStatus
PresenceOutTask::SendDirected(const Jid & j, const PresenceStatus & s) {
if (GetState() != STATE_INIT && GetState() != STATE_START)
return XMPP_RETURN_BADSTATE;
XmlElement * presence = TranslateStatus(s);
presence->AddAttr(QN_TO, j.Str());
QueueStanza(presence);
delete presence;
return XMPP_RETURN_OK;
}
XmppReturnStatus PresenceOutTask::SendProbe(const Jid & jid) {
if (GetState() != STATE_INIT && GetState() != STATE_START)
return XMPP_RETURN_BADSTATE;
XmlElement * presence = new XmlElement(QN_PRESENCE);
presence->AddAttr(QN_TO, jid.Str());
presence->AddAttr(QN_TYPE, "probe");
QueueStanza(presence);
delete presence;
return XMPP_RETURN_OK;
}
int
PresenceOutTask::ProcessStart() {
const XmlElement * stanza = NextStanza();
if (stanza == NULL)
return STATE_BLOCKED;
if (SendStanza(stanza) != XMPP_RETURN_OK)
return STATE_ERROR;
return STATE_START;
}
XmlElement *
PresenceOutTask::TranslateStatus(const PresenceStatus & s) {
XmlElement * result = new XmlElement(QN_PRESENCE);
if (!s.available()) {
result->AddAttr(QN_TYPE, STR_UNAVAILABLE);
}
else {
if (s.show() != PresenceStatus::SHOW_ONLINE &&
s.show() != PresenceStatus::SHOW_OFFLINE) {
result->AddElement(new XmlElement(QN_SHOW));
switch (s.show()) {
default:
result->AddText(STR_SHOW_AWAY, 1);
break;
case PresenceStatus::SHOW_XA:
result->AddText(STR_SHOW_XA, 1);
break;
case PresenceStatus::SHOW_DND:
result->AddText(STR_SHOW_DND, 1);
break;
case PresenceStatus::SHOW_CHAT:
result->AddText(STR_SHOW_CHAT, 1);
break;
}
}
result->AddElement(new XmlElement(QN_STATUS));
result->AddText(s.status(), 1);
if (!s.nick().empty()) {
result->AddElement(new XmlElement(QN_NICKNAME));
result->AddText(s.nick(), 1);
}
std::string pri;
rtc::ToString(s.priority(), &pri);
result->AddElement(new XmlElement(QN_PRIORITY));
result->AddText(pri, 1);
if (s.know_capabilities()) {
result->AddElement(new XmlElement(QN_CAPS_C, true));
result->AddAttr(QN_NODE, s.caps_node(), 1);
result->AddAttr(QN_VER, s.version(), 1);
std::string caps;
caps.append(s.voice_capability() ? "voice-v1" : "");
caps.append(s.pmuc_capability() ? " pmuc-v1" : "");
caps.append(s.video_capability() ? " video-v1" : "");
caps.append(s.camera_capability() ? " camera-v1" : "");
result->AddAttr(QN_EXT, caps, 1);
}
// Put the delay mark on the presence according to JEP-0091
{
result->AddElement(new XmlElement(kQnDelayX, true));
// This here is why we *love* the C runtime
time_t current_time_seconds;
time(¤t_time_seconds);
struct tm* current_time = gmtime(¤t_time_seconds);
char output[256];
strftime(output, ARRAY_SIZE(output), "%Y%m%dT%H:%M:%S", current_time);
result->AddAttr(kQnStamp, output, 1);
}
}
return result;
}
}
| bsd-3-clause |
ltilve/ChromiumGStreamerBackend | chrome/browser/ui/panels/panel.cc | 28836 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/panels/panel.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/devtools/devtools_window.h"
#include "chrome/browser/extensions/api/tabs/tabs_constants.h"
#include "chrome/browser/extensions/api/tabs/tabs_windows_api.h"
#include "chrome/browser/extensions/api/tabs/windows_event_router.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/window_controller.h"
#include "chrome/browser/extensions/window_controller_list.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/session_tab_helper.h"
#include "chrome/browser/task_management/web_contents_tags.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/browser/ui/panels/native_panel.h"
#include "chrome/browser/ui/panels/panel_collection.h"
#include "chrome/browser/ui/panels/panel_host.h"
#include "chrome/browser/ui/panels/panel_manager.h"
#include "chrome/browser/ui/panels/stacked_panel_collection.h"
#include "chrome/browser/web_applications/web_app.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/image_loader.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest_handlers/icons_handler.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/image/image.h"
using base::UserMetricsAction;
using content::RenderViewHost;
namespace panel_internal {
class PanelExtensionWindowController : public extensions::WindowController {
public:
PanelExtensionWindowController(Panel* panel, Profile* profile);
~PanelExtensionWindowController() override;
// Overridden from extensions::WindowController.
int GetWindowId() const override;
std::string GetWindowTypeText() const override;
base::DictionaryValue* CreateWindowValueWithTabs(
const extensions::Extension* extension) const override;
base::DictionaryValue* CreateTabValue(const extensions::Extension* extension,
int tab_index) const override;
bool CanClose(Reason* reason) const override;
void SetFullscreenMode(bool is_fullscreen,
const GURL& extension_url) const override;
bool IsVisibleToExtension(
const extensions::Extension* extension) const override;
private:
Panel* panel_; // Weak pointer. Owns us.
DISALLOW_COPY_AND_ASSIGN(PanelExtensionWindowController);
};
PanelExtensionWindowController::PanelExtensionWindowController(
Panel* panel, Profile* profile)
: extensions::WindowController(panel, profile),
panel_(panel) {
extensions::WindowControllerList::GetInstance()->AddExtensionWindow(this);
}
PanelExtensionWindowController::~PanelExtensionWindowController() {
extensions::WindowControllerList::GetInstance()->RemoveExtensionWindow(this);
}
int PanelExtensionWindowController::GetWindowId() const {
return static_cast<int>(panel_->session_id().id());
}
std::string PanelExtensionWindowController::GetWindowTypeText() const {
return extensions::tabs_constants::kWindowTypeValuePanel;
}
base::DictionaryValue*
PanelExtensionWindowController::CreateWindowValueWithTabs(
const extensions::Extension* extension) const {
base::DictionaryValue* result = CreateWindowValue();
base::DictionaryValue* tab_value = CreateTabValue(extension, 0);
if (tab_value) {
base::ListValue* tab_list = new base::ListValue();
tab_list->Append(tab_value);
result->Set(extensions::tabs_constants::kTabsKey, tab_list);
}
return result;
}
base::DictionaryValue* PanelExtensionWindowController::CreateTabValue(
const extensions::Extension* extension, int tab_index) const {
if (tab_index > 0)
return NULL;
content::WebContents* web_contents = panel_->GetWebContents();
if (!web_contents)
return NULL;
base::DictionaryValue* tab_value = new base::DictionaryValue();
tab_value->SetInteger(extensions::tabs_constants::kIdKey,
SessionTabHelper::IdForTab(web_contents));
tab_value->SetInteger(extensions::tabs_constants::kIndexKey, 0);
tab_value->SetInteger(
extensions::tabs_constants::kWindowIdKey,
SessionTabHelper::IdForWindowContainingTab(web_contents));
tab_value->SetString(
extensions::tabs_constants::kUrlKey, web_contents->GetURL().spec());
tab_value->SetString(extensions::tabs_constants::kStatusKey,
extensions::ExtensionTabUtil::GetTabStatusText(
web_contents->IsLoading()));
tab_value->SetBoolean(
extensions::tabs_constants::kActiveKey, panel_->IsActive());
tab_value->SetBoolean(extensions::tabs_constants::kSelectedKey, true);
tab_value->SetBoolean(extensions::tabs_constants::kHighlightedKey, true);
tab_value->SetBoolean(extensions::tabs_constants::kPinnedKey, false);
tab_value->SetString(
extensions::tabs_constants::kTitleKey, web_contents->GetTitle());
tab_value->SetBoolean(
extensions::tabs_constants::kIncognitoKey,
web_contents->GetBrowserContext()->IsOffTheRecord());
return tab_value;
}
bool PanelExtensionWindowController::CanClose(Reason* reason) const {
return true;
}
void PanelExtensionWindowController::SetFullscreenMode(
bool is_fullscreen, const GURL& extension_url) const {
// Do nothing. Panels cannot be fullscreen.
}
bool PanelExtensionWindowController::IsVisibleToExtension(
const extensions::Extension* extension) const {
DCHECK(extension);
return extension->id() == panel_->extension_id();
}
} // namespace panel_internal
Panel::~Panel() {
DCHECK(!collection_);
#if !defined(USE_AURA)
// Invoked by native panel destructor. Do not access native_panel_ here.
chrome::DecrementKeepAliveCount(); // Remove shutdown prevention.
#endif
}
PanelManager* Panel::manager() const {
return PanelManager::GetInstance();
}
const std::string Panel::extension_id() const {
return web_app::GetExtensionIdFromApplicationName(app_name_);
}
CommandUpdater* Panel::command_updater() {
return &command_updater_;
}
Profile* Panel::profile() const {
return profile_;
}
const extensions::Extension* Panel::GetExtension() const {
ExtensionService* extension_service =
extensions::ExtensionSystem::Get(profile())->extension_service();
if (!extension_service || !extension_service->is_ready())
return NULL;
return extension_service->GetExtensionById(extension_id(), false);
}
content::WebContents* Panel::GetWebContents() const {
return panel_host_.get() ? panel_host_->web_contents() : NULL;
}
void Panel::SetExpansionState(ExpansionState new_state) {
if (expansion_state_ == new_state)
return;
native_panel_->PanelExpansionStateChanging(expansion_state_, new_state);
expansion_state_ = new_state;
manager()->OnPanelExpansionStateChanged(this);
DCHECK(initialized_ && collection_ != NULL);
native_panel_->PreventActivationByOS(collection_->IsPanelMinimized(this));
UpdateMinimizeRestoreButtonVisibility();
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_PANEL_CHANGED_EXPANSION_STATE,
content::Source<Panel>(this),
content::NotificationService::NoDetails());
}
bool Panel::IsDrawingAttention() const {
return native_panel_->IsDrawingAttention();
}
void Panel::FullScreenModeChanged(bool is_full_screen) {
native_panel_->FullScreenModeChanged(is_full_screen);
}
int Panel::TitleOnlyHeight() const {
return native_panel_->TitleOnlyHeight();
}
bool Panel::CanShowMinimizeButton() const {
return collection_ && collection_->CanShowMinimizeButton(this);
}
bool Panel::CanShowRestoreButton() const {
return collection_ && collection_->CanShowRestoreButton(this);
}
bool Panel::IsActive() const {
return native_panel_->IsPanelActive();
}
bool Panel::IsMaximized() const {
// Size of panels is managed by PanelManager, they are never 'zoomed'.
return false;
}
bool Panel::IsMinimized() const {
return !collection_ || collection_->IsPanelMinimized(this);
}
bool Panel::IsFullscreen() const {
return false;
}
gfx::NativeWindow Panel::GetNativeWindow() const {
return native_panel_->GetNativePanelWindow();
}
gfx::Rect Panel::GetRestoredBounds() const {
gfx::Rect bounds = native_panel_->GetPanelBounds();
bounds.set_y(bounds.bottom() - full_size_.height());
bounds.set_x(bounds.right() - full_size_.width());
bounds.set_size(full_size_);
return bounds;
}
ui::WindowShowState Panel::GetRestoredState() const {
return ui::SHOW_STATE_NORMAL;
}
gfx::Rect Panel::GetBounds() const {
return native_panel_->GetPanelBounds();
}
void Panel::Show() {
if (manager()->display_settings_provider()->is_full_screen() || !collection_)
return;
native_panel_->ShowPanel();
}
void Panel::Hide() {
// Not implemented.
}
void Panel::ShowInactive() {
if (manager()->display_settings_provider()->is_full_screen() || !collection_)
return;
native_panel_->ShowPanelInactive();
}
// Close() may be called multiple times if the panel window is not ready to
// close on the first attempt.
void Panel::Close() {
native_panel_->ClosePanel();
}
void Panel::Activate() {
if (!collection_)
return;
collection_->ActivatePanel(this);
native_panel_->ActivatePanel();
}
void Panel::Deactivate() {
native_panel_->DeactivatePanel();
}
void Panel::Maximize() {
Restore();
}
void Panel::Minimize() {
if (collection_)
collection_->MinimizePanel(this);
}
bool Panel::IsMinimizedBySystem() const {
return native_panel_->IsPanelMinimizedBySystem();
}
bool Panel::IsShownOnActiveDesktop() const {
return native_panel_->IsPanelShownOnActiveDesktop();
}
void Panel::ShowShadow(bool show) {
native_panel_->ShowShadow(show);
}
void Panel::Restore() {
if (collection_)
collection_->RestorePanel(this);
}
void Panel::SetBounds(const gfx::Rect& bounds) {
// Ignore bounds position as the panel manager controls all positioning.
if (!collection_)
return;
collection_->ResizePanelWindow(this, bounds.size());
SetAutoResizable(false);
}
void Panel::FlashFrame(bool draw_attention) {
if (IsDrawingAttention() == draw_attention || !collection_)
return;
// Don't draw attention for an active panel.
if (draw_attention && IsActive())
return;
// Invoking native panel to draw attention must be done before informing the
// panel collection because it needs to check internal state of the panel to
// determine if the panel has been drawing attention.
native_panel_->DrawAttention(draw_attention);
collection_->OnPanelAttentionStateChanged(this);
}
bool Panel::IsAlwaysOnTop() const {
return native_panel_->IsPanelAlwaysOnTop();
}
void Panel::SetAlwaysOnTop(bool on_top) {
native_panel_->SetPanelAlwaysOnTop(on_top);
}
void Panel::ExecuteCommandWithDisposition(int id,
WindowOpenDisposition disposition) {
DCHECK(command_updater_.IsCommandEnabled(id)) << "Invalid/disabled command "
<< id;
if (!GetWebContents())
return;
switch (id) {
// Navigation
case IDC_RELOAD:
panel_host_->Reload();
break;
case IDC_RELOAD_IGNORING_CACHE:
panel_host_->ReloadIgnoringCache();
break;
case IDC_STOP:
panel_host_->StopLoading();
break;
// Window management
case IDC_CLOSE_WINDOW:
content::RecordAction(UserMetricsAction("CloseWindow"));
Close();
break;
case IDC_EXIT:
content::RecordAction(UserMetricsAction("Exit"));
chrome::AttemptUserExit();
break;
// Clipboard
case IDC_COPY:
content::RecordAction(UserMetricsAction("Copy"));
native_panel_->PanelCopy();
break;
case IDC_CUT:
content::RecordAction(UserMetricsAction("Cut"));
native_panel_->PanelCut();
break;
case IDC_PASTE:
content::RecordAction(UserMetricsAction("Paste"));
native_panel_->PanelPaste();
break;
// Zoom
case IDC_ZOOM_PLUS:
panel_host_->Zoom(content::PAGE_ZOOM_IN);
break;
case IDC_ZOOM_NORMAL:
panel_host_->Zoom(content::PAGE_ZOOM_RESET);
break;
case IDC_ZOOM_MINUS:
panel_host_->Zoom(content::PAGE_ZOOM_OUT);
break;
// DevTools
case IDC_DEV_TOOLS:
content::RecordAction(UserMetricsAction("DevTools_ToggleWindow"));
DevToolsWindow::OpenDevToolsWindow(GetWebContents(),
DevToolsToggleAction::Show());
break;
case IDC_DEV_TOOLS_CONSOLE:
content::RecordAction(UserMetricsAction("DevTools_ToggleConsole"));
DevToolsWindow::OpenDevToolsWindow(GetWebContents(),
DevToolsToggleAction::ShowConsole());
break;
default:
LOG(WARNING) << "Received unimplemented command: " << id;
break;
}
}
void Panel::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_APP_TERMINATING:
Close();
break;
default:
NOTREACHED() << "Received unexpected notification " << type;
}
}
void Panel::RenderViewHostChanged(content::RenderViewHost* old_host,
content::RenderViewHost* new_host) {
ConfigureAutoResize(web_contents());
}
void Panel::OnExtensionUnloaded(
content::BrowserContext* browser_context,
const extensions::Extension* extension,
extensions::UnloadedExtensionInfo::Reason reason) {
if (extension->id() == extension_id())
Close();
}
void Panel::OnTitlebarClicked(panel::ClickModifier modifier) {
if (collection_)
collection_->OnPanelTitlebarClicked(this, modifier);
// Normally the system activates a window when the titlebar is clicked.
// However, we prevent system activation of minimized panels, thus the
// activation may not have occurred. Also, some OSes (Windows) will
// activate a minimized panel on mouse-down regardless of our attempts to
// prevent system activation. Attention state is not cleared in that case.
// See Panel::OnActiveStateChanged().
// Therefore, we ensure activation and clearing of attention state if the
// panel has been expanded. If the panel is in a stack, the titlebar click
// might minimize the panel and we do not want to activate it to make it
// expand again.
// These are no-ops if no changes are needed.
if (IsMinimized())
return;
Activate();
FlashFrame(false);
}
void Panel::OnMinimizeButtonClicked(panel::ClickModifier modifier) {
if (collection_)
collection_->OnMinimizeButtonClicked(this, modifier);
}
void Panel::OnRestoreButtonClicked(panel::ClickModifier modifier) {
// Clicking the restore button has the same behavior as clicking the titlebar.
OnTitlebarClicked(modifier);
}
void Panel::OnWindowSizeAvailable() {
ConfigureAutoResize(GetWebContents());
}
void Panel::OnNativePanelClosed() {
// Ensure previously enqueued OnImageLoaded callbacks are ignored.
image_loader_ptr_factory_.InvalidateWeakPtrs();
registrar_.RemoveAll();
extension_registry_->RemoveObserver(this);
manager()->OnPanelClosed(this);
DCHECK(!collection_);
}
StackedPanelCollection* Panel::stack() const {
return collection_ && collection_->type() == PanelCollection::STACKED ?
static_cast<StackedPanelCollection*>(collection_) : NULL;
}
panel::Resizability Panel::CanResizeByMouse() const {
if (!collection_)
return panel::NOT_RESIZABLE;
return collection_->GetPanelResizability(this);
}
void Panel::Initialize(const GURL& url,
const gfx::Rect& bounds,
bool always_on_top) {
DCHECK(!initialized_);
DCHECK(!collection_); // Cannot be added to a collection until fully created.
DCHECK_EQ(EXPANDED, expansion_state_);
DCHECK(!bounds.IsEmpty());
initialized_ = true;
full_size_ = bounds.size();
native_panel_ = CreateNativePanel(this, bounds, always_on_top);
extension_window_controller_.reset(
new panel_internal::PanelExtensionWindowController(this, profile_));
InitCommandState();
// Set up hosting for web contents.
panel_host_.reset(new PanelHost(this, profile_));
panel_host_->Init(url);
content::WebContents* web_contents = GetWebContents();
// The contents might be NULL for most of our tests.
if (web_contents) {
native_panel_->AttachWebContents(web_contents);
// Make the panel show up in the task manager.
task_management::WebContentsTags::CreateForPanel(web_contents, this);
}
// Close when the extension is unloaded or the browser is exiting.
extension_registry_->AddObserver(this);
registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
content::NotificationService::AllSources());
registrar_.Add(this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
content::Source<ThemeService>(
ThemeServiceFactory::GetForProfile(profile_)));
#if !defined(USE_AURA)
// Keep alive for AURA has been moved to panel_view.
// Prevent the browser process from shutting down while this window is open.
chrome::IncrementKeepAliveCount();
#endif
UpdateAppIcon();
}
void Panel::SetPanelBounds(const gfx::Rect& bounds) {
if (bounds != native_panel_->GetPanelBounds())
native_panel_->SetPanelBounds(bounds);
}
void Panel::SetPanelBoundsInstantly(const gfx::Rect& bounds) {
native_panel_->SetPanelBoundsInstantly(bounds);
}
void Panel::LimitSizeToWorkArea(const gfx::Rect& work_area) {
int max_width = manager()->GetMaxPanelWidth(work_area);
int max_height = manager()->GetMaxPanelHeight(work_area);
// If the custom max size is used, ensure that it does not exceed the display
// area.
if (max_size_policy_ == CUSTOM_MAX_SIZE) {
int current_max_width = max_size_.width();
if (current_max_width > max_width)
max_width = std::min(current_max_width, work_area.width());
int current_max_height = max_size_.height();
if (current_max_height > max_height)
max_height = std::min(current_max_height, work_area.height());
}
SetSizeRange(min_size_, gfx::Size(max_width, max_height));
// Ensure that full size does not exceed max size.
full_size_ = ClampSize(full_size_);
}
void Panel::SetAutoResizable(bool resizable) {
if (auto_resizable_ == resizable)
return;
auto_resizable_ = resizable;
content::WebContents* web_contents = GetWebContents();
if (auto_resizable_) {
if (web_contents)
EnableWebContentsAutoResize(web_contents);
} else {
if (web_contents) {
content::WebContentsObserver::Observe(nullptr);
// NULL might be returned if the tab has not been added.
RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
if (render_view_host)
render_view_host->DisableAutoResize(full_size_);
}
}
}
void Panel::EnableWebContentsAutoResize(content::WebContents* web_contents) {
DCHECK(web_contents);
ConfigureAutoResize(web_contents);
// We also need to know when the render view host changes in order
// to turn on auto-resize notifications in the new render view host.
content::WebContentsObserver::Observe(web_contents);
}
void Panel::OnContentsAutoResized(const gfx::Size& new_content_size) {
DCHECK(auto_resizable_);
if (!collection_)
return;
gfx::Size new_window_size =
native_panel_->WindowSizeFromContentSize(new_content_size);
// Ignore content auto resizes until window frame size is known.
// This reduces extra resizes when panel is first shown.
// After window frame size is known, it will trigger another content
// auto resize.
if (new_content_size == new_window_size)
return;
collection_->ResizePanelWindow(this, new_window_size);
}
void Panel::OnWindowResizedByMouse(const gfx::Rect& new_bounds) {
if (collection_)
collection_->OnPanelResizedByMouse(this, new_bounds);
}
void Panel::SetSizeRange(const gfx::Size& min_size, const gfx::Size& max_size) {
if (min_size == min_size_ && max_size == max_size_)
return;
DCHECK(min_size.width() <= max_size.width());
DCHECK(min_size.height() <= max_size.height());
min_size_ = min_size;
max_size_ = max_size;
ConfigureAutoResize(GetWebContents());
}
void Panel::IncreaseMaxSize(const gfx::Size& desired_panel_size) {
gfx::Size new_max_size = max_size_;
if (new_max_size.width() < desired_panel_size.width())
new_max_size.set_width(desired_panel_size.width());
if (new_max_size.height() < desired_panel_size.height())
new_max_size.set_height(desired_panel_size.height());
SetSizeRange(min_size_, new_max_size);
}
void Panel::HandleKeyboardEvent(const content::NativeWebKeyboardEvent& event) {
native_panel_->HandlePanelKeyboardEvent(event);
}
void Panel::SetPreviewMode(bool in_preview) {
DCHECK_NE(in_preview_mode_, in_preview);
in_preview_mode_ = in_preview;
}
void Panel::UpdateMinimizeRestoreButtonVisibility() {
native_panel_->UpdatePanelMinimizeRestoreButtonVisibility();
}
gfx::Size Panel::ClampSize(const gfx::Size& size) const {
// The panel width:
// * cannot grow or shrink to go beyond [min_width, max_width]
int new_width = size.width();
if (new_width > max_size_.width())
new_width = max_size_.width();
if (new_width < min_size_.width())
new_width = min_size_.width();
// The panel height:
// * cannot grow or shrink to go beyond [min_height, max_height]
int new_height = size.height();
if (new_height > max_size_.height())
new_height = max_size_.height();
if (new_height < min_size_.height())
new_height = min_size_.height();
return gfx::Size(new_width, new_height);
}
void Panel::OnActiveStateChanged(bool active) {
// Clear attention state when an expanded panel becomes active.
// On some systems (e.g. Win), mouse-down activates a panel regardless of
// its expansion state. However, we don't want to clear draw attention if
// contents are not visible. In that scenario, if the mouse-down results
// in a mouse-click, draw attention will be cleared then.
// See Panel::OnTitlebarClicked().
if (active && IsDrawingAttention() && !IsMinimized())
FlashFrame(false);
if (collection_)
collection_->OnPanelActiveStateChanged(this);
// Send extension event about window changing active state.
extensions::TabsWindowsAPI* tabs_windows_api =
extensions::TabsWindowsAPI::Get(profile());
if (tabs_windows_api) {
tabs_windows_api->windows_event_router()->OnActiveWindowChanged(
active ? extension_window_controller_.get() : NULL);
}
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_PANEL_CHANGED_ACTIVE_STATUS,
content::Source<Panel>(this),
content::NotificationService::NoDetails());
}
void Panel::OnPanelStartUserResizing() {
SetAutoResizable(false);
SetPreviewMode(true);
max_size_policy_ = CUSTOM_MAX_SIZE;
}
void Panel::OnPanelEndUserResizing() {
SetPreviewMode(false);
}
bool Panel::ShouldCloseWindow() {
return true;
}
void Panel::OnWindowClosing() {
if (GetWebContents()) {
native_panel_->DetachWebContents(GetWebContents());
panel_host_->DestroyWebContents();
}
}
bool Panel::ExecuteCommandIfEnabled(int id) {
if (command_updater()->SupportsCommand(id) &&
command_updater()->IsCommandEnabled(id)) {
ExecuteCommandWithDisposition(id, CURRENT_TAB);
return true;
}
return false;
}
base::string16 Panel::GetWindowTitle() const {
content::WebContents* contents = GetWebContents();
base::string16 title;
// |contents| can be NULL during the window's creation.
if (contents) {
title = contents->GetTitle();
FormatTitleForDisplay(&title);
}
if (title.empty())
title = base::UTF8ToUTF16(app_name());
return title;
}
gfx::Image Panel::GetCurrentPageIcon() const {
return panel_host_.get() ? panel_host_->GetPageIcon() : gfx::Image();
}
void Panel::UpdateTitleBar() {
native_panel_->UpdatePanelTitleBar();
}
void Panel::LoadingStateChanged(bool is_loading) {
command_updater_.UpdateCommandEnabled(IDC_STOP, is_loading);
native_panel_->UpdatePanelLoadingAnimations(is_loading);
UpdateTitleBar();
}
void Panel::MoveByInstantly(const gfx::Vector2d& delta_origin) {
gfx::Rect bounds = GetBounds();
bounds.Offset(delta_origin);
SetPanelBoundsInstantly(bounds);
}
void Panel::SetWindowCornerStyle(panel::CornerStyle corner_style) {
native_panel_->SetWindowCornerStyle(corner_style);
}
void Panel::MinimizeBySystem() {
native_panel_->MinimizePanelBySystem();
}
Panel::Panel(Profile* profile,
const std::string& app_name,
const gfx::Size& min_size,
const gfx::Size& max_size)
: app_name_(app_name),
profile_(profile),
collection_(NULL),
initialized_(false),
min_size_(min_size),
max_size_(max_size),
max_size_policy_(DEFAULT_MAX_SIZE),
auto_resizable_(false),
in_preview_mode_(false),
native_panel_(NULL),
attention_mode_(USE_PANEL_ATTENTION),
expansion_state_(EXPANDED),
command_updater_(this),
extension_registry_(extensions::ExtensionRegistry::Get(profile_)),
image_loader_ptr_factory_(this) {
}
void Panel::OnImageLoaded(const gfx::Image& image) {
if (!image.IsEmpty()) {
app_icon_ = image;
native_panel_->UpdatePanelTitleBar();
}
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_PANEL_APP_ICON_LOADED,
content::Source<Panel>(this),
content::NotificationService::NoDetails());
}
void Panel::InitCommandState() {
// All supported commands whose state isn't set automagically some other way
// (like Stop during a page load) must have their state initialized here,
// otherwise they will be forever disabled.
// Navigation commands
command_updater_.UpdateCommandEnabled(IDC_RELOAD, true);
command_updater_.UpdateCommandEnabled(IDC_RELOAD_IGNORING_CACHE, true);
// Window management commands
command_updater_.UpdateCommandEnabled(IDC_CLOSE_WINDOW, true);
command_updater_.UpdateCommandEnabled(IDC_EXIT, true);
// Zoom
command_updater_.UpdateCommandEnabled(IDC_ZOOM_MENU, true);
command_updater_.UpdateCommandEnabled(IDC_ZOOM_PLUS, true);
command_updater_.UpdateCommandEnabled(IDC_ZOOM_NORMAL, true);
command_updater_.UpdateCommandEnabled(IDC_ZOOM_MINUS, true);
// Clipboard
command_updater_.UpdateCommandEnabled(IDC_COPY, true);
command_updater_.UpdateCommandEnabled(IDC_CUT, true);
command_updater_.UpdateCommandEnabled(IDC_PASTE, true);
// DevTools
command_updater_.UpdateCommandEnabled(IDC_DEV_TOOLS, true);
command_updater_.UpdateCommandEnabled(IDC_DEV_TOOLS_CONSOLE, true);
}
void Panel::ConfigureAutoResize(content::WebContents* web_contents) {
if (!auto_resizable_ || !web_contents)
return;
// NULL might be returned if the tab has not been added.
RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
if (!render_view_host)
return;
render_view_host->EnableAutoResize(
min_size_,
native_panel_->ContentSizeFromWindowSize(max_size_));
}
void Panel::UpdateAppIcon() {
const extensions::Extension* extension = GetExtension();
if (!extension)
return;
extensions::ImageLoader* loader = extensions::ImageLoader::Get(profile());
loader->LoadImageAsync(
extension,
extensions::IconsInfo::GetIconResource(
extension,
extension_misc::EXTENSION_ICON_SMALL,
ExtensionIconSet::MATCH_BIGGER),
gfx::Size(extension_misc::EXTENSION_ICON_SMALL,
extension_misc::EXTENSION_ICON_SMALL),
base::Bind(&Panel::OnImageLoaded,
image_loader_ptr_factory_.GetWeakPtr()));
}
// static
void Panel::FormatTitleForDisplay(base::string16* title) {
size_t current_index = 0;
size_t match_index;
while ((match_index = title->find(L'\n', current_index)) !=
base::string16::npos) {
title->replace(match_index, 1, base::string16());
current_index = match_index;
}
}
| bsd-3-clause |
lgierth/rubinius | kernel/common/channel.rb | 257 | # -*- encoding: us-ascii -*-
##
# A communication mechanism based on pi-calculus channels used primarily to
# communicate between ruby and the VM about events.
module Rubinius
class Channel
def inspect
"#<Rubinius::Channel>"
end
end
end
| bsd-3-clause |
elektropay/Cachet | app/Notifications/Subscriber/VerifySubscriptionNotification.php | 1607 | <?php
/*
* This file is part of Cachet.
*
* (c) Alt Three Services Limited
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CachetHQ\Cachet\Notifications\Subscriber;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Config;
/**
* This is the verify subscription notification class.
*
* @author James Brooks <james@alt-three.com>
*/
class VerifySubscriptionNotification extends Notification
{
use Queueable;
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
*
* @return string[]
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
*
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage())
->subject(trans('notifications.subscriber.verify.mail.subject'))
->greeting(trans('notifications.subscriber.verify.mail.title', ['app_name' => Config::get('setting.app_name')]))
->action(trans('notifications.subscriber.verify.mail.action'), cachet_route('subscribe.verify', ['code' => $notifiable->verify_code]))
->line(trans('notifications.subscriber.verify.mail.content', ['app_name' => Config::get('setting.app_name')]));
}
}
| bsd-3-clause |
akatsoulas/remo | remo/base/serializers.py | 5379 | import codecs
import csv
import cStringIO
from django.conf import settings
from django.http import Http404
from django.template.loader import get_template
from django.utils import timezone
from tastypie.serializers import Serializer
def flatten_dict(d, base=None):
"""Converts a dictionary of dictionaries or lists into a simple
dictionary.
For example the following dictionary
foobar = {'key1': 'value1',
'key2': {'skey1': 'svalue1'},
'key3': ['svalue2', 'svalue3']}
gets converted to
foobar = {'key1': 'value1',
'key2.skey1': 'svalue1',
'key3.0': 'svalue2',
'key3.1': 'svalue3'}
"""
new_dict = {}
for key, value in d.iteritems():
if isinstance(value, dict):
new_base = ''
if base:
new_base = '%s.' % base
new_base += key
new_dict.update(flatten_dict(value, base=new_base))
elif isinstance(value, list):
new_base = ''
if base:
new_base += '%s.' % base
new_base += '%s' % key
i = 0
for item in value:
new_base_index = new_base + '.%d' % i
if isinstance(item, dict):
new_dict.update(flatten_dict(item, base=new_base_index))
else:
new_dict.update({new_base_index: item})
i += 1
elif base:
new_dict.update({'%s.%s' % (base, key): value})
else:
new_dict.update({key: value})
return new_dict
class CSVUnicodeWriter(object):
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
Original code from http://docs.python.org/library/csv.html#csv-examples
Altered by Giorgos Logiotatidis <giorgos@mozilla.com>
"""
def __init__(self, f, dialect=csv.excel, encoding='utf-8', **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
newrow = []
for s in row:
newrow.append(unicode(s))
self.writer.writerow([s.encode('utf-8') for s in newrow])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode('utf-8')
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
class CSVSerializer(Serializer):
"""Extend tastypie's serializer to export to CSV format."""
formats = ['json', 'jsonp', 'xml', 'yaml', 'html', 'csv']
content_types = {'json': 'application/json',
'jsonp': 'text/javascript',
'xml': 'application/xml',
'yaml': 'text/yaml',
'html': 'text/html',
'csv': 'text/csv'}
def to_csv(self, data, options=None):
"""Convert data to CSV."""
options = options or {}
data = self.to_simple(data, options)
raw_data = cStringIO.StringIO()
writer = CSVUnicodeWriter(raw_data, delimiter=';', quotechar='"',
quoting=csv.QUOTE_MINIMAL)
for category in data:
if category == 'objects' and len(data[category]) > 0:
items = []
available_keys = []
for item in data[category]:
flatitem = flatten_dict(item)
items.append(flatitem)
available_keys += [key for key in flatitem.keys()
if key not in available_keys]
available_keys = sorted(available_keys)
writer.writerow(available_keys)
for item in data[category]:
flatitem = flatten_dict(item)
writer.writerow(map(lambda x: flatitem.get(x),
available_keys))
raw_data.seek(0)
return raw_data
class iCalSerializer(Serializer):
"""Extend tastypie's serializer to export to iCal format."""
formats = ['json', 'jsonp', 'xml', 'yaml', 'html', 'ical']
content_types = {'json': 'application/json',
'jsonp': 'text/javascript',
'xml': 'application/xml',
'yaml': 'text/yaml',
'html': 'text/html',
'ical': 'text/calendar'}
def to_ical(self, data, options=None):
"""Convert data to iCal."""
options = options or {}
if any(k in data for k in ('error_message', 'error')):
raise Http404
if isinstance(data, dict) and 'objects' in data:
events = [event.obj for event in data['objects']]
else:
events = [data.obj]
date_now = timezone.now()
ical = get_template('multi_event_ical_template.jinja')
return ical.render({'events': events, 'date_now': date_now, 'host': settings.SITE_URL})
| bsd-3-clause |
piaoxuedtian/myrepo | framework/views/he/error503.php | 1174 | <!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>לא פעיל</title>
<style type="text/css">
/*<![CDATA[*/
html { direction:rtl; text-align:right; }
body {font-family:"Verdana";font-weight:normal;color:black;background-color:white;}
h1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
h2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
h3 {font-family:"Verdana";font-weight:bold;font-size:11pt}
p {font-family:"Verdana";font-weight:normal;color:black;font-size:9pt;margin-top: -5px}
.version {color: gray;font-size:8pt;border-top:1px solid #aaaaaa;}
/*]]>*/
</style>
</head>
<body>
<h1>השירות לא פעיל כרגע</h1>
<p>
המערכת שלנו עוברת תהליך שדרוג. אנא נסה שוב מאוחר יותר.
</p>
<p>
תודה.
</p>
<div class="version">
<?php echo date('Y-m-d H:i:s',$data['time']) .' '. $data['version']; ?>
</div>
</body>
</html> | bsd-3-clause |
svn2github/webrtc-Revision-8758 | modules/bitrate_controller/send_side_bandwidth_estimation_unittest.cc | 1417 | /*
* Copyright (c) 2014 The WebRTC 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 <algorithm>
#include <vector>
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/modules/bitrate_controller/send_side_bandwidth_estimation.h"
namespace webrtc {
TEST(SendSideBweTest, InitialRembWithProbing) {
SendSideBandwidthEstimation bwe;
bwe.SetMinMaxBitrate(100000, 1500000);
bwe.SetSendBitrate(200000);
const uint32_t kRemb = 1000000u;
const uint32_t kSecondRemb = kRemb + 500000u;
int64_t now_ms = 0;
bwe.UpdateReceiverBlock(0, 50, 1, now_ms);
// Initial REMB applies immediately.
bwe.UpdateReceiverEstimate(kRemb);
bwe.UpdateEstimate(now_ms);
uint32_t bitrate;
uint8_t fraction_loss;
int64_t rtt;
bwe.CurrentEstimate(&bitrate, &fraction_loss, &rtt);
EXPECT_EQ(kRemb, bitrate);
// Second REMB doesn't apply immediately.
now_ms += 2001;
bwe.UpdateReceiverEstimate(kSecondRemb);
bwe.UpdateEstimate(now_ms);
bitrate = 0;
bwe.CurrentEstimate(&bitrate, &fraction_loss, &rtt);
EXPECT_EQ(kRemb, bitrate);
}
} // namespace webrtc
| bsd-3-clause |
michaelrice/yavijava | src/main/java/com/vmware/vim25/VMOnVirtualIntranet.java | 1833 | /*================================================================================
Copyright (c) 2013 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class VMOnVirtualIntranet extends CannotAccessNetwork {
} | bsd-3-clause |
Igalia/skia | gm/strokefill.cpp | 4601 | /*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkPath.h"
#include "SkTypeface.h"
namespace skiagm {
class StrokeFillGM : public GM {
public:
StrokeFillGM() {
}
protected:
SkString onShortName() SK_OVERRIDE {
return SkString("stroke-fill");
}
SkISize onISize() SK_OVERRIDE {
return SkISize::Make(640, 480);
}
static void show_bold(SkCanvas* canvas, const void* text, int len,
SkScalar x, SkScalar y, const SkPaint& paint) {
SkPaint p(paint);
canvas->drawText(text, len, x, y, p);
p.setFakeBoldText(true);
canvas->drawText(text, len, x, y + SkIntToScalar(120), p);
}
void onDraw(SkCanvas* canvas) SK_OVERRIDE {
SkScalar x = SkIntToScalar(100);
SkScalar y = SkIntToScalar(88);
SkPaint paint;
paint.setAntiAlias(true);
paint.setTextSize(SkIntToScalar(100));
paint.setStrokeWidth(SkIntToScalar(5));
sk_tool_utils::set_portable_typeface(&paint, "Papyrus");
show_bold(canvas, "Hello", 5, x, y, paint);
sk_tool_utils::set_portable_typeface(&paint, "Hiragino Maru Gothic Pro");
const unsigned char hyphen[] = { 0xE3, 0x83, 0xBC };
show_bold(canvas, hyphen, SK_ARRAY_COUNT(hyphen), x + SkIntToScalar(300), y, paint);
paint.setStyle(SkPaint::kStrokeAndFill_Style);
SkPath path;
path.setFillType(SkPath::kWinding_FillType);
path.addCircle(x, y + SkIntToScalar(200), SkIntToScalar(50), SkPath::kCW_Direction);
path.addCircle(x, y + SkIntToScalar(200), SkIntToScalar(40), SkPath::kCCW_Direction);
canvas->drawPath(path, paint);
SkPath path2;
path2.setFillType(SkPath::kWinding_FillType);
path2.addCircle(x + SkIntToScalar(120), y + SkIntToScalar(200), SkIntToScalar(50), SkPath::kCCW_Direction);
path2.addCircle(x + SkIntToScalar(120), y + SkIntToScalar(200), SkIntToScalar(40), SkPath::kCW_Direction);
canvas->drawPath(path2, paint);
path2.reset();
path2.addCircle(x + SkIntToScalar(240), y + SkIntToScalar(200), SkIntToScalar(50), SkPath::kCCW_Direction);
canvas->drawPath(path2, paint);
SkASSERT(path2.cheapIsDirection(SkPath::kCCW_Direction));
path2.reset();
SkASSERT(!path2.cheapComputeDirection(NULL));
path2.addCircle(x + SkIntToScalar(360), y + SkIntToScalar(200), SkIntToScalar(50), SkPath::kCW_Direction);
SkASSERT(path2.cheapIsDirection(SkPath::kCW_Direction));
canvas->drawPath(path2, paint);
SkRect r = SkRect::MakeXYWH(x - SkIntToScalar(50), y + SkIntToScalar(280),
SkIntToScalar(100), SkIntToScalar(100));
SkPath path3;
path3.setFillType(SkPath::kWinding_FillType);
path3.addRect(r, SkPath::kCW_Direction);
r.inset(SkIntToScalar(10), SkIntToScalar(10));
path3.addRect(r, SkPath::kCCW_Direction);
canvas->drawPath(path3, paint);
r = SkRect::MakeXYWH(x + SkIntToScalar(70), y + SkIntToScalar(280),
SkIntToScalar(100), SkIntToScalar(100));
SkPath path4;
path4.setFillType(SkPath::kWinding_FillType);
path4.addRect(r, SkPath::kCCW_Direction);
r.inset(SkIntToScalar(10), SkIntToScalar(10));
path4.addRect(r, SkPath::kCW_Direction);
canvas->drawPath(path4, paint);
r = SkRect::MakeXYWH(x + SkIntToScalar(190), y + SkIntToScalar(280),
SkIntToScalar(100), SkIntToScalar(100));
path4.reset();
SkASSERT(!path4.cheapComputeDirection(NULL));
path4.addRect(r, SkPath::kCCW_Direction);
SkASSERT(path4.cheapIsDirection(SkPath::kCCW_Direction));
path4.moveTo(0, 0); // test for crbug.com/247770
canvas->drawPath(path4, paint);
r = SkRect::MakeXYWH(x + SkIntToScalar(310), y + SkIntToScalar(280),
SkIntToScalar(100), SkIntToScalar(100));
path4.reset();
SkASSERT(!path4.cheapComputeDirection(NULL));
path4.addRect(r, SkPath::kCW_Direction);
SkASSERT(path4.cheapIsDirection(SkPath::kCW_Direction));
path4.moveTo(0, 0); // test for crbug.com/247770
canvas->drawPath(path4, paint);
}
private:
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
DEF_GM(return SkNEW(StrokeFillGM);)
}
| bsd-3-clause |
rongeb/anit_cms_for_zf3 | vendor/zendframework/zend-mail/src/Storage/Part/PartInterface.php | 3690 | <?php
/**
* @see https://github.com/zendframework/zend-mail for the canonical source repository
* @copyright Copyright (c) 2005-2018 Zend Technologies USA Inc. (https://www.zend.com)
* @license https://github.com/zendframework/zend-mail/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Mail\Storage\Part;
use ArrayIterator;
use RecursiveIterator;
use Zend\Mail\Header\HeaderInterface;
use Zend\Mail\Headers;
interface PartInterface extends RecursiveIterator
{
/**
* Check if part is a multipart message
*
* @return bool if part is multipart
*/
public function isMultipart();
/**
* Body of part
*
* If part is multipart the raw content of this part with all sub parts is
* returned.
*
* @return string body
* @throws Exception\ExceptionInterface
*/
public function getContent();
/**
* Return size of part
*
* @return int size
*/
public function getSize();
/**
* Get part of multipart message
*
* @param int $num number of part starting with 1 for first part
* @return PartInterface wanted part
* @throws Exception\ExceptionInterface
*/
public function getPart($num);
/**
* Count parts of a multipart part
*
* @return int number of sub-parts
*/
public function countParts();
/**
* Get all headers
*
* The returned headers are as saved internally. All names are lowercased.
* The value is a string or an array if a header with the same name occurs
* more than once.
*
* @return Headers
*/
public function getHeaders();
/**
* Get a header in specified format
*
* Internally headers that occur more than once are saved as array, all
* other as string. If $format is set to string implode is used to concat
* the values (with Zend\Mime\Mime::LINEEND as delim).
*
* @param string $name name of header, matches case-insensitive, but
* camel-case is replaced with dashes
* @param string $format change type of return value to 'string' or 'array'
* @return string|array|HeaderInterface|ArrayIterator value of header in
* wanted or internal format
* @throws Exception\ExceptionInterface
*/
public function getHeader($name, $format = null);
/**
* Get a specific field from a header like content type or all fields as array
*
* If the header occurs more than once, only the value from the first
* header is returned.
*
* Throws an exception if the requested header does not exist. If the
* specific header field does not exist, returns null.
*
* @param string $name name of header, like in getHeader()
* @param string $wantedPart the wanted part, default is first, if null an
* array with all parts is returned
* @param string $firstName key name for the first part
* @return string|array wanted part or all parts as
* [$firstName => firstPart, partname => value]
* @throws Exception\ExceptionInterface
*/
public function getHeaderField($name, $wantedPart = '0', $firstName = '0');
/**
* Getter for mail headers - name is matched in lowercase
*
* This getter is short for PartInterface::getHeader($name, 'string')
*
* @see PartInterface::getHeader()
* @param string $name header name
* @return string value of header
* @throws Exception\ExceptionInterface
*/
public function __get($name);
/**
* magic method to get content of part
*
* @return string content
*/
public function __toString();
}
| bsd-3-clause |
chromium/chromium | chrome/browser/extensions/api/activity_log_private/activity_log_private_api.cc | 8470 | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/activity_log_private/activity_log_private_api.h"
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include <utility>
#include "base/bind.h"
#include "base/lazy_instance.h"
#include "base/strings/string_number_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/event_router_forwarder.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/common/extensions/api/activity_log_private.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_context.h"
#include "extensions/browser/extension_system_provider.h"
#include "extensions/browser/extensions_browser_client.h"
namespace extensions {
namespace activity_log_private = api::activity_log_private;
using activity_log_private::ActivityResultSet;
using activity_log_private::ExtensionActivity;
using activity_log_private::Filter;
static base::LazyInstance<BrowserContextKeyedAPIFactory<ActivityLogAPI>>::
DestructorAtExit g_activity_log_private_api_factory =
LAZY_INSTANCE_INITIALIZER;
// static
BrowserContextKeyedAPIFactory<ActivityLogAPI>*
ActivityLogAPI::GetFactoryInstance() {
return g_activity_log_private_api_factory.Pointer();
}
template <>
void
BrowserContextKeyedAPIFactory<ActivityLogAPI>::DeclareFactoryDependencies() {
DependsOn(ExtensionsBrowserClient::Get()->GetExtensionSystemFactory());
DependsOn(ActivityLog::GetFactoryInstance());
}
ActivityLogAPI::ActivityLogAPI(content::BrowserContext* context)
: browser_context_(context) {
if (!EventRouter::Get(browser_context_)) { // Check for testing.
DVLOG(1) << "ExtensionSystem event_router does not exist.";
return;
}
activity_log_ = extensions::ActivityLog::GetInstance(browser_context_);
DCHECK(activity_log_);
EventRouter::Get(browser_context_)->RegisterObserver(
this, activity_log_private::OnExtensionActivity::kEventName);
activity_log_->AddObserver(this);
initialized_ = true;
}
void ActivityLogAPI::Shutdown() {
if (!initialized_) { // Check for testing.
DVLOG(1) << "ExtensionSystem event_router does not exist.";
return;
}
EventRouter::Get(browser_context_)->UnregisterObserver(this);
activity_log_->RemoveObserver(this);
}
void ActivityLogAPI::OnListenerAdded(const EventListenerInfo& details) {
if (activity_log_->has_listeners())
return;
StartOrStopListeningForExtensionActivities();
}
void ActivityLogAPI::OnListenerRemoved(const EventListenerInfo& details) {
StartOrStopListeningForExtensionActivities();
}
void ActivityLogAPI::StartOrStopListeningForExtensionActivities() {
EventRouter* event_router = EventRouter::Get(browser_context_);
activity_log_->SetHasListeners(event_router->HasEventListener(
activity_log_private::OnExtensionActivity::kEventName));
}
void ActivityLogAPI::OnExtensionActivity(scoped_refptr<Action> activity) {
std::unique_ptr<base::ListValue> value(new base::ListValue());
ExtensionActivity activity_arg = activity->ConvertToExtensionActivity();
value->Append(activity_arg.ToValue());
auto event = std::make_unique<Event>(
events::ACTIVITY_LOG_PRIVATE_ON_EXTENSION_ACTIVITY,
activity_log_private::OnExtensionActivity::kEventName,
std::move(*value).TakeListDeprecated(), browser_context_);
EventRouter::Get(browser_context_)->BroadcastEvent(std::move(event));
}
ExtensionFunction::ResponseAction
ActivityLogPrivateGetExtensionActivitiesFunction::Run() {
std::unique_ptr<activity_log_private::GetExtensionActivities::Params> params(
activity_log_private::GetExtensionActivities::Params::Create(args()));
EXTENSION_FUNCTION_VALIDATE(params);
// Get the arguments in the right format.
Filter filter = std::move(params->filter);
Action::ActionType action_type = Action::ACTION_API_CALL;
switch (filter.activity_type) {
case activity_log_private::EXTENSION_ACTIVITY_FILTER_API_CALL:
action_type = Action::ACTION_API_CALL;
break;
case activity_log_private::EXTENSION_ACTIVITY_FILTER_API_EVENT:
action_type = Action::ACTION_API_EVENT;
break;
case activity_log_private::EXTENSION_ACTIVITY_FILTER_CONTENT_SCRIPT:
action_type = Action::ACTION_CONTENT_SCRIPT;
break;
case activity_log_private::EXTENSION_ACTIVITY_FILTER_DOM_ACCESS:
action_type = Action::ACTION_DOM_ACCESS;
break;
case activity_log_private::EXTENSION_ACTIVITY_FILTER_DOM_EVENT:
action_type = Action::ACTION_DOM_EVENT;
break;
case activity_log_private::EXTENSION_ACTIVITY_FILTER_WEB_REQUEST:
action_type = Action::ACTION_WEB_REQUEST;
break;
case activity_log_private::EXTENSION_ACTIVITY_FILTER_ANY:
default:
action_type = Action::ACTION_ANY;
}
std::string extension_id =
filter.extension_id ? *filter.extension_id : std::string();
std::string api_call = filter.api_call ? *filter.api_call : std::string();
std::string page_url = filter.page_url ? *filter.page_url : std::string();
std::string arg_url = filter.arg_url ? *filter.arg_url : std::string();
int days_ago = -1;
if (filter.days_ago)
days_ago = *filter.days_ago;
// Call the ActivityLog.
ActivityLog* activity_log = ActivityLog::GetInstance(browser_context());
DCHECK(activity_log);
activity_log->GetFilteredActions(
extension_id, action_type, api_call, page_url, arg_url, days_ago,
base::BindOnce(
&ActivityLogPrivateGetExtensionActivitiesFunction::OnLookupCompleted,
this));
return RespondLater();
}
void ActivityLogPrivateGetExtensionActivitiesFunction::OnLookupCompleted(
std::unique_ptr<std::vector<scoped_refptr<Action>>> activities) {
// Convert Actions to ExtensionActivities.
std::vector<ExtensionActivity> result_arr;
for (const auto& activity : *activities)
result_arr.push_back(activity->ConvertToExtensionActivity());
// Populate the return object.
ActivityResultSet result_set;
result_set.activities = std::move(result_arr);
Respond(ArgumentList(
activity_log_private::GetExtensionActivities::Results::Create(
result_set)));
}
ExtensionFunction::ResponseAction
ActivityLogPrivateDeleteActivitiesFunction::Run() {
std::unique_ptr<activity_log_private::DeleteActivities::Params> params(
activity_log_private::DeleteActivities::Params::Create(args()));
EXTENSION_FUNCTION_VALIDATE(params);
// Put the arguments in the right format.
std::vector<int64_t> action_ids;
int64_t value;
for (size_t i = 0; i < params->activity_ids.size(); i++) {
if (base::StringToInt64(params->activity_ids[i], &value))
action_ids.push_back(value);
}
ActivityLog* activity_log = ActivityLog::GetInstance(browser_context());
DCHECK(activity_log);
activity_log->RemoveActions(action_ids);
return RespondNow(NoArguments());
}
ExtensionFunction::ResponseAction
ActivityLogPrivateDeleteActivitiesByExtensionFunction::Run() {
std::unique_ptr<activity_log_private::DeleteActivitiesByExtension::Params>
params(activity_log_private::DeleteActivitiesByExtension::Params::Create(
args()));
EXTENSION_FUNCTION_VALIDATE(params);
ActivityLog* activity_log = ActivityLog::GetInstance(browser_context());
DCHECK(activity_log);
activity_log->RemoveExtensionData(params->extension_id);
return RespondNow(NoArguments());
}
ExtensionFunction::ResponseAction
ActivityLogPrivateDeleteDatabaseFunction::Run() {
ActivityLog* activity_log = ActivityLog::GetInstance(browser_context());
DCHECK(activity_log);
activity_log->DeleteDatabase();
return RespondNow(NoArguments());
}
ExtensionFunction::ResponseAction ActivityLogPrivateDeleteUrlsFunction::Run() {
std::unique_ptr<activity_log_private::DeleteUrls::Params> params(
activity_log_private::DeleteUrls::Params::Create(args()));
EXTENSION_FUNCTION_VALIDATE(params);
// Put the arguments in the right format.
std::vector<GURL> gurls;
const std::vector<std::string>& urls = params->urls;
gurls.reserve(urls.size());
for (const std::string& url : urls)
gurls.push_back(GURL(url));
ActivityLog* activity_log = ActivityLog::GetInstance(browser_context());
DCHECK(activity_log);
activity_log->RemoveURLs(gurls);
return RespondNow(NoArguments());
}
} // namespace extensions
| bsd-3-clause |
wuhengzhi/chromium-crosswalk | third_party/WebKit/Source/core/dom/custom/V0CustomElementUpgradeCandidateMap.cpp | 3701 | /*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "core/dom/custom/V0CustomElementUpgradeCandidateMap.h"
#include "core/dom/Element.h"
namespace blink {
V0CustomElementUpgradeCandidateMap* V0CustomElementUpgradeCandidateMap::create()
{
return new V0CustomElementUpgradeCandidateMap();
}
V0CustomElementUpgradeCandidateMap::~V0CustomElementUpgradeCandidateMap()
{
}
void V0CustomElementUpgradeCandidateMap::add(const V0CustomElementDescriptor& descriptor, Element* element)
{
observe(element);
UpgradeCandidateMap::AddResult result = m_upgradeCandidates.add(element, descriptor);
ASSERT_UNUSED(result, result.isNewEntry);
UnresolvedDefinitionMap::iterator it = m_unresolvedDefinitions.find(descriptor);
ElementSet* elements;
if (it == m_unresolvedDefinitions.end())
elements = m_unresolvedDefinitions.add(descriptor, new ElementSet()).storedValue->value.get();
else
elements = it->value.get();
elements->add(element);
}
void V0CustomElementUpgradeCandidateMap::elementWasDestroyed(Element* element)
{
V0CustomElementObserver::elementWasDestroyed(element);
UpgradeCandidateMap::iterator candidate = m_upgradeCandidates.find(element);
ASSERT_WITH_SECURITY_IMPLICATION(candidate != m_upgradeCandidates.end());
UnresolvedDefinitionMap::iterator elements = m_unresolvedDefinitions.find(candidate->value);
ASSERT_WITH_SECURITY_IMPLICATION(elements != m_unresolvedDefinitions.end());
elements->value->remove(element);
m_upgradeCandidates.remove(candidate);
}
V0CustomElementUpgradeCandidateMap::ElementSet* V0CustomElementUpgradeCandidateMap::takeUpgradeCandidatesFor(const V0CustomElementDescriptor& descriptor)
{
ElementSet* candidates = m_unresolvedDefinitions.take(descriptor);
if (!candidates)
return nullptr;
for (const auto& candidate : *candidates) {
unobserve(candidate);
m_upgradeCandidates.remove(candidate);
}
return candidates;
}
DEFINE_TRACE(V0CustomElementUpgradeCandidateMap)
{
visitor->trace(m_upgradeCandidates);
visitor->trace(m_unresolvedDefinitions);
V0CustomElementObserver::trace(visitor);
}
} // namespace blink
| bsd-3-clause |
alyssontkd/etec | vendor/sendgrid/sendgrid/test/SendGrid.php | 2604 | <?php
class SendGridTest_SendGrid extends PHPUnit_Framework_TestCase {
public function testVersion() {
$this->assertEquals(SendGrid::VERSION, "2.2.0");
}
public function testInitialization() {
$sendgrid = new SendGrid("user", "pass");
$this->assertEquals("SendGrid", get_class($sendgrid));
}
public function testDefaultURL() {
$sendgrid = new SendGrid("user", "pass");
$this->assertEquals("https://api.sendgrid.com/api/mail.send.json", $sendgrid->url);
}
public function testCustomURL() {
$options = array( "protocol" => "http", "host" => "sendgrid.org", "endpoint" => "/send", "port" => "80" );
$sendgrid = new SendGrid("user", "pass", $options);
$this->assertEquals("http://sendgrid.org:80/send", $sendgrid->url);
}
public function testSendResponse() {
$sendgrid = new SendGrid("foo", "bar");
$email = new SendGrid\Email();
$email->setFrom('bar@foo.com')->
setSubject('foobar subject')->
setText('foobar text')->
addTo('foo@bar.com');
$response = $sendgrid->send($email);
$this->assertEquals("Bad username / password", $response->errors[0]);
}
public function testSendResponseWithAttachment() {
$sendgrid = new SendGrid("foo", "bar");
$email = new SendGrid\Email();
$email->setFrom('p1@mailinator.com')->
setSubject('foobar subject')->
setText('foobar text')->
addTo('p1@mailinator.com')->
addAttachment('./gif.gif');
$response = $sendgrid->send($email);
$this->assertEquals("Bad username / password", $response->errors[0]);
}
public function testSendResponseWithAttachmentMissingExtension() {
$sendgrid = new SendGrid("foo", "bar");
$email = new SendGrid\Email();
$email->setFrom('p1@mailinator.com')->
setSubject('foobar subject')->
setText('foobar text')->
addTo('p1@mailinator.com')->
addAttachment('./text');
$response = $sendgrid->send($email);
$this->assertEquals("Bad username / password", $response->errors[0]);
}
public function testSendResponseWithSslOptionFalse() {
$sendgrid = new SendGrid("foo", "bar", array("switch_off_ssl_verification" => true));
$email = new SendGrid\Email();
$email->setFrom('p1@mailinator.com')->
setSubject('foobar subject')->
setText('foobar text')->
addTo('p1@mailinator.com')->
addAttachment('./text');
$response = $sendgrid->send($email);
$this->assertEquals("Bad username / password", $response->errors[0]);
}
}
| bsd-3-clause |
wuhengzhi/chromium-crosswalk | ios/chrome/browser/metrics/ios_chrome_origins_seen_service_factory.cc | 1717 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ios/chrome/browser/metrics/ios_chrome_origins_seen_service_factory.h"
#include "base/memory/ptr_util.h"
#include "base/memory/singleton.h"
#include "components/keyed_service/ios/browser_state_dependency_manager.h"
#include "components/navigation_metrics/origins_seen_service.h"
#include "ios/chrome/browser/browser_state/browser_state_otr_helper.h"
#include "ios/chrome/browser/browser_state/chrome_browser_state.h"
// static
navigation_metrics::OriginsSeenService*
IOSChromeOriginsSeenServiceFactory::GetForBrowserState(
ios::ChromeBrowserState* browser_state) {
return static_cast<navigation_metrics::OriginsSeenService*>(
GetInstance()->GetServiceForBrowserState(browser_state, true));
}
// static
IOSChromeOriginsSeenServiceFactory*
IOSChromeOriginsSeenServiceFactory::GetInstance() {
return base::Singleton<IOSChromeOriginsSeenServiceFactory>::get();
}
IOSChromeOriginsSeenServiceFactory::IOSChromeOriginsSeenServiceFactory()
: BrowserStateKeyedServiceFactory(
"OriginsSeenService",
BrowserStateDependencyManager::GetInstance()) {}
IOSChromeOriginsSeenServiceFactory::~IOSChromeOriginsSeenServiceFactory() {}
std::unique_ptr<KeyedService>
IOSChromeOriginsSeenServiceFactory::BuildServiceInstanceFor(
web::BrowserState* context) const {
return base::WrapUnique(new navigation_metrics::OriginsSeenService());
}
web::BrowserState* IOSChromeOriginsSeenServiceFactory::GetBrowserStateToUse(
web::BrowserState* context) const {
return GetBrowserStateOwnInstanceInIncognito(context);
}
| bsd-3-clause |
NCIP/cabio | software/cabio-api/system/web/dijit/_editor/nls/it/commands.js | 1753 | //>>built
define(
({
'bold': 'Grassetto',
'copy': 'Copia',
'cut': 'Taglia',
'delete': 'Annulla',
'indent': 'Rientra',
'insertHorizontalRule': 'Righello orizzontale',
'insertOrderedList': 'Elenco numerato',
'insertUnorderedList': 'Elenco a punti',
'italic': 'Corsivo',
'justifyCenter': 'Allinea al centro',
'justifyFull': 'Giustifica',
'justifyLeft': 'Allinea a sinistra',
'justifyRight': 'Allinea a destra',
'outdent': 'Annulla rientro',
'paste': 'Incolla',
'redo': 'Ripeti',
'removeFormat': 'Rimuovi formato',
'selectAll': 'Seleziona tutto',
'strikethrough': 'Barrato',
'subscript': 'Pedice',
'superscript': 'Apice',
'underline': 'Sottolinea',
'undo': 'Annulla',
'unlink': 'Rimuovi collegamento',
'createLink': 'Crea collegamento',
'toggleDir': 'Attiva/Disattiva direzione',
'insertImage': 'Inserisci immagine',
'insertTable': 'Inserisci/Modifica tabella',
'toggleTableBorder': 'Attiva/Disattiva bordo tabella',
'deleteTable': 'Elimina tabella',
'tableProp': 'Proprietà tabella',
'htmlToggle': 'Origine HTML',
'foreColor': 'Colore in primo piano',
'hiliteColor': 'Colore di sfondo',
'plainFormatBlock': 'Stile paragrafo',
'formatBlock': 'Stile paragrafo',
'fontSize': 'Dimensione tipo di carattere',
'fontName': 'Nome tipo di carattere',
'tabIndent': 'Rientro tabulazione',
"fullScreen": "Attiva/Disattiva schermo intero",
"viewSource": "Visualizza origine HTML",
"print": "Stampa",
"newPage": "Nuova pagina",
/* Error messages */
'systemShortcut': 'Azione "${0}" disponibile nel browser solo utilizzando una scelta rapida da tastiera. Utilizzare ${1}.',
'ctrlKey':'ctrl+${0}',
'appleKey':'\u2318${0}' // "command" or open-apple key on Macintosh
})
);
| bsd-3-clause |
michaelrice/yavijava | src/main/java/com/vmware/vim25/LicenseAssignmentManagerEntityFeaturePair.java | 2164 | /*================================================================================
Copyright (c) 2009 VMware, Inc. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (sjin@vmware.com)
*/
public class LicenseAssignmentManagerEntityFeaturePair extends DynamicData {
public String entityId;
public String feature;
public String getEntityId() {
return this.entityId;
}
public String getFeature() {
return this.feature;
}
public void setEntityId(String entityId) {
this.entityId = entityId;
}
public void setFeature(String feature) {
this.feature = feature;
}
} | bsd-3-clause |
ajjl/mlpack | src/mlpack/methods/sparse_autoencoder/maximal_inputs.hpp | 2907 | /**
* @file maximal_inputs.hpp
* @author Tham Ngap Wei
*
* A function to find the maximal inputs of an autoencoder.
*/
#ifndef MLPACK_METHODS_NN_MAXIMAL_INPUTS_HPP
#define MLPACK_METHODS_NN_MAXIMAL_INPUTS_HPP
#include <mlpack/core.hpp>
namespace mlpack {
namespace nn {
/**
* Given a parameters matrix from an autoencoder, maximize the hidden units of
* the parameters, storing the maximal inputs in the given output matrix.
* Details can be found on the 'Visualizing a Trained Autoencoder' page of the
* Stanford UFLDL tutorial:
*
* http://deeplearning.stanford.edu/wiki/index.php/Main_Page
*
* This function is based on the implementation (display_network.m) from the
* "Exercise: Sparse Autoencoder" page of the UFLDL tutorial:
*
* http://deeplearning.stanford.edu/wiki/index.php/Exercise:Sparse_Autoencoder
*
* Example usage of this function can be seen below. Note that this function
* can work with the ColumnsToBlocks class in order to reshape the maximal
* inputs for visualization, as in the UFLDL tutorial. The code below
* demonstrates this.
*
* @code
* arma::mat data; // Data matrix.
* const size_t vSize = 64; // Size of visible layer, depends on the data.
* const size_t hSize = 25; // Size of hidden layer, depends on requirements.
*
* const size_t numBasis = 5; // Parameter required for L-BFGS algorithm.
* const size_t numIterations = 100; // Maximum number of iterations.
*
* // Use an instantiated optimizer for the training.
* SparseAutoencoder<L_BFGS> encoder(data, vSize, hSize);
*
* arma::mat maximalInput; // Store the features learned by sparse autoencoder
* mlpack::nn::MaximalInputs(encoder.Parameters(), maximalInput);
*
* arma::mat outputs;
* const bool scale = true;
*
* ColumnsToBlocks ctb(5,5);
* arma::mat output;
* ctb.Transform(maximalInput, output);
* // Save the output as PGM, for visualization.
* output.save(fileName, arma::pgm_binary);
* @endcode
*
* @pre Layout of parameters
*
* The layout of the parameters matrix should be same as following
* @code
* // vSize 1
* // | | |
* // hSize| w1 |b1|
* // |________|__|
* // | | |
* // hSize| w2' | |
* // |________|__|
* // 1| b2' | |
* @endcode
*
* Also, the square root of vSize must be an integer (i.e. vSize must be a
* perfect square).
*
* @param parameters The parameters of the autoencoder.
* @param output Matrix to store the maximal inputs in.
*/
void MaximalInputs(const arma::mat& parameters, arma::mat& output);
/**
* Normalize each column of the input matrix by its maximum value, if that
* maximum value is not zero.
*
* @param input The input data to normalize.
* @param output A matrix to store the input data in after normalization.
*/
void NormalizeColByMax(const arma::mat& input, arma::mat& output);
} // namespace nn
} // namespace mlpack
#endif
| bsd-3-clause |
jswrenn/xtreemfs | cpp/src/ld_preload/functions.cpp | 10781 | /*
* Copyright (c) 2014 by Matthias Noack, Zuse Institute Berlin
*
* Licensed under the BSD License, see LICENSE file for details.
*
*/
#include <stdio.h>
#include <stdarg.h>
#include <stdint.h>
#include <fcntl.h>
#include "ld_preload/passthrough.h"
#include "ld_preload/preload.h"
/* Interceptor functions */
extern "C" {
int open(__const char *path, int flags, ...) {
initialize_passthrough_if_necessary();
xprintf(" open(%s)\n", path);
// if O_CREAT is set, mode MUST be specified and is ignored otherwise (at least on linux, see man 2 open)
// we only need to acquire the mode, when it must be specified, and ignore it otherwise
mode_t mode;
if (flags & O_CREAT) {
va_list ap;
va_start(ap, flags);
mode = va_arg(ap, mode_t);
va_end(ap);
}
if (overlay_initialized() && is_xtreemfs_path(path)) {
return xtreemfs_open(path, flags, mode);
} else {
xprintf(" open calling libc_open(%s)\n", path);
int ret = ((funcptr_open)libc_open)(path, flags, mode);
xprintf(" open libc_open(%s) returned %d\n", path, ret);
return ret;
}
}
int open64(__const char *path, int flags, ...) {
initialize_passthrough_if_necessary();
xprintf(" open64(%s)\n", path);
mode_t mode;
if (flags & O_CREAT) {
va_list ap;
va_start(ap, flags);
mode = va_arg(ap, mode_t);
va_end(ap);
}
return open(path, flags | O_LARGEFILE, mode);
}
#undef creat
int creat(__const char *name, mode_t mode) {
return open(name, O_CREAT | O_WRONLY | O_TRUNC, mode);
}
int close(int fd) {
initialize_passthrough_if_necessary();
xprintf(" close(%d)\n", fd);
if (overlay_initialized() && is_xtreemfs_fd(fd)) {
return xtreemfs_close(fd);
} else {
xprintf(" close passthrough(%d)\n", fd);
return ((funcptr_close)libc_close)(fd);
}
}
// failed attempt to intercept libc-internal close calls
int _close(int fd) {
xprintf(" _close(%d)\n", fd);
return close(fd);
}
int __close(int fd) {
xprintf(" __close(%d)\n", fd);
return close(fd);
}
// TODO: do we need this?
/*
int fclose(FILE *fp) {
initialize_passthrough_if_necessary();
xprintf(" fclose(%d)\n", fd);
if (is_xtreemfs_fd(fd)) {
return xtreemfs_fclose(fd);
} else {
xprintf(" fclose passthrough(%d)\n", fd);
return ((funcptr_close)libc_fclose)(fd);
}
}
*/
ssize_t pread(int fd, void* buf, size_t nbyte, off_t offset) {
initialize_passthrough_if_necessary();
xprintf(" pread(%d)\n", fd);
if (overlay_initialized() && is_xtreemfs_fd(fd)) {
return xtreemfs_pread(fd, buf, nbyte, offset);
} else {
return ((funcptr_pread)libc_pread)(fd, buf, nbyte, offset);
}
}
ssize_t pread64(int fd, void* buf, size_t nbyte, __off64_t offset) {
initialize_passthrough_if_necessary();
xprintf(" pread64(%d)\n", fd);
if (overlay_initialized() && is_xtreemfs_fd(fd)) {
return xtreemfs_pread(fd, buf, nbyte, offset);
} else {
return ((funcptr_pread)libc_pread)(fd, buf, nbyte, offset);
}
}
ssize_t read(int fd, void* buf, size_t nbyte) {
initialize_passthrough_if_necessary();
xprintf(" read(%d)\n", fd);
if (overlay_initialized() && is_xtreemfs_fd(fd)) {
return xtreemfs_read(fd, buf, nbyte);
} else {
return ((funcptr_read)libc_read)(fd, buf, nbyte);
}
}
ssize_t write(int fd, const void* buf, size_t nbyte) {
initialize_passthrough_if_necessary();
xprintf(" write(%d)\n", fd);
if (overlay_initialized() && is_xtreemfs_fd(fd)) {
xprintf(" write(%d) xtreemfs\n", fd);
return xtreemfs_write(fd, buf, nbyte);
} else {
xprintf(" write(%d) passthrough\n", fd);
return ((funcptr_write)libc_write)(fd, buf, nbyte);
}
}
int dup(int oldfd) {
initialize_passthrough_if_necessary();
xprintf(" dup(%d)\n", oldfd);
if (overlay_initialized() && is_xtreemfs_fd(oldfd)) {
//xprintf("calling xtreemfs dup(%d)\n", oldfd);
//return xtreemfs_dup(oldfd);
xprintf(" NOT IMPLEMENTED: dup for xtreemfs fd(%d)\n", oldfd);
return -1;
} else {
xprintf(" calling pasthrought dup(%d)\n", oldfd);
return ((funcptr_dup)libc_dup)(oldfd);
}
}
int dup2(int oldfd, int newfd) {
initialize_passthrough_if_necessary();
xprintf(" dup2(%d, %d)\n", oldfd, newfd);
if (overlay_initialized() && (is_xtreemfs_fd(newfd) || is_xtreemfs_fd(oldfd))) {
xprintf(" NOT IMPLEMENTED: dup2 for xtreemfs fd(%d, %d)\n", oldfd, newfd);
return -1;
} else {
return ((funcptr_dup2)libc_dup2)(oldfd, newfd);
}
// if (overlay_initialized() && is_xtreemfs_fd(newfd)) {
// xprintf(" dest is xtreemfs fd\n");
// xtreemfs_close(newfd);
// } else {
// xprintf(" dest is system fd\n");
// ((funcptr_close)libc_close)(newfd);
// }
//
// if (overlay_initialized() && is_xtreemfs_fd(oldfd)) {
// return xtreemfs_dup2(oldfd, newfd);
// } else {
// xprintf(" dup2 passthrough\n");
// return ((funcptr_dup2)libc_dup2)(oldfd, newfd);
// }
}
off_t lseek(int fd, off_t offset, int mode) {
initialize_passthrough_if_necessary();
xprintf(" lseek(%d, %ld, %d)\n", fd, offset, mode);
if (overlay_initialized() && is_xtreemfs_fd(fd)) {
return xtreemfs_lseek(fd, offset, mode);
} else {
return ((funcptr_lseek)libc_lseek)(fd, offset, mode);
}
}
int stat(const char *path, struct stat *buf) {
initialize_passthrough_if_necessary();
xprintf(" stat(%s, ...)\n", path);
if (overlay_initialized() && is_xtreemfs_path(path)) {
return xtreemfs_stat(path, buf);
} else {
return ((funcptr_stat)libc_stat)(path, buf);
}
}
int fstat(int fd, struct stat *buf) {
initialize_passthrough_if_necessary();
xprintf(" fstat(%d, ...)\n", fd);
if (overlay_initialized() && is_xtreemfs_fd(fd)) {
return xtreemfs_fstat(fd, buf);
} else {
return ((funcptr_fstat)libc_fstat)(fd, buf);
}
}
int __xstat(int ver, const char *path, struct stat *buf) {
initialize_passthrough_if_necessary();
xprintf(" __xstat(%d, %s, ...)\n", ver, path);
if (overlay_initialized() && is_xtreemfs_path(path)) {
return xtreemfs_stat(path, buf);
} else {
return ((funcptr___xstat)libc___xstat)(ver, path, buf);
}
}
int __xstat64(int ver, const char *path, struct stat64 *buf) {
initialize_passthrough_if_necessary();
xprintf(" __xstat64(%d, %s, ...)\n", ver, path);
xprintf(" __xstat64(%d, %s, ...), errno(%d)\n", ver, path, errno);
return -1;
// int i = strstr(path, "/gfs1/work/bzaztsch/job-output") == path;
// xprintf(" __xstat64(%s), returning -1 WITHOUT actually calling GetAttr, errno(%d), path(%p), strstr(%p)\n", path, errno, path, i);
// return -1;
// //if (overlay_initialized() && (strstr(path, "/gfs1/work/bzaztsch/job-output") == path)) {
// if ((strstr(path, "/gfs1/work/bzaztsch/job-output") == path)) {
// xprintf(" __xstat64(%s), returning -1 WITHOUT actually calling GetAttr, errno(%d)\n", path, errno);
// return -1;
if (overlay_initialized() && is_xtreemfs_path(path)) {
return xtreemfs_stat64(path, buf);
} else {
return ((funcptr___xstat64)libc___xstat64)(ver, path, buf);
}
}
int __fxstat(int ver, int fd, struct stat *buf) {
initialize_passthrough_if_necessary();
xprintf(" __fxstat(%d, %d, ...)\n", ver, fd);
if (overlay_initialized() && is_xtreemfs_fd(fd)) {
return xtreemfs_fstat(fd, buf);
} else {
return ((funcptr___fxstat)libc___fxstat)(ver, fd, buf);
}
}
int __fxstat64(int ver, int fd, struct stat64 *buf) {
initialize_passthrough_if_necessary();
xprintf(" __fxstat64(%d, %d, ...)\n", ver, fd);
if (overlay_initialized() && is_xtreemfs_fd(fd)) {
return xtreemfs_fstat64(fd, buf);
} else {
return ((funcptr___fxstat64)libc___fxstat64)(ver, fd, buf);
}
}
extern int __lxstat(int ver, const char *path, struct stat *buf) {
initialize_passthrough_if_necessary();
xprintf(" __lxstat(%d, %s, ...)\n", ver, path);
if (overlay_initialized() && is_xtreemfs_path(path)) {
xprintf(" NOT IMPLEMENTED: lstat for xtreemfs (%s)\n", path);
return -1;
} else {
return ((funcptr___lxstat)libc___lxstat)(ver, path, buf);
}
}
extern int __lxstat64(int ver, const char *path, struct stat64 *buf) {
initialize_passthrough_if_necessary();
xprintf(" __lxstat64(%d, %s, ...)\n", ver, path);
if (overlay_initialized() && is_xtreemfs_path(path)) {
xprintf(" NOT IMPLEMENTED: lstat64 for xtreemfs (%s)\n", path);
return -1;
} else {
return ((funcptr___lxstat64)libc___lxstat64)(ver, path, buf);
}
}
/*
extern int __fxstatat(int __ver, int __fildes, const char *__filename, struct stat *__stat_buf, int __flag) {
initialize_passthrough_if_necessary();
xprintf(" __fxstatat\n");
return -1;
}
extern int __fxstatat64(int __ver, int __fildes, const char *__filename, struct stat64 *__stat_buf, int __flag) {
initialize_passthrough_if_necessary();
xprintf(" __fxstatat64\n");
return -1;
}
*/
FILE *fopen(const char *path, const char *mode) {
initialize_passthrough_if_necessary();
if (overlay_initialized() && is_xtreemfs_path(path)) {
xprintf(" WARNING: fopen(%s, %s) called for xtreemfs\n", path, mode);
}
return ((funcptr_fopen)libc_fopen)(path, mode);
}
int truncate(const char *path, off_t length) {
initialize_passthrough_if_necessary();
xprintf(" truncate(%s, %ld)\n", path, length);
if (overlay_initialized() && is_xtreemfs_path(path)) {
xprintf(" NOT IMPLEMENTED: truncate for xtreemfs (%s)\n", path);
return -1;
} else {
return ((funcptr_truncate)libc_truncate)(path, length);
}
}
int ftruncate(int fd, off_t length) {
initialize_passthrough_if_necessary();
xprintf(" ftruncate(%d, %ld)\n", fd, length);
if (overlay_initialized() && is_xtreemfs_fd(fd)) {
xprintf(" NOT IMPLEMENTED: ftruncate for xtreemfs fd(%d)", fd);
return -1;
} else {
return ((funcptr_ftruncate)libc_ftruncate)(fd, length);
}
}
int setxattr(const char *path, const char *name, const void *value, size_t size, int flags) {
initialize_passthrough_if_necessary();
xprintf(" setxattr(%s, %s, ...)\n", path, name);
if (overlay_initialized() && is_xtreemfs_path(path)) {
xprintf(" xtreemfs_setxattr(%s, %s, ...)", path, name);
return xtreemfs_setxattr(path, name, value, size, flags);
} else {
return ((funcptr_setxattr)libattr_setxattr)(path, name, value, size, flags);
}
}
//int lsetxattr (const char *path, const char *name,
// const void *value, size_t size, int flags);
int fsetxattr(int fd, const char *name, const void *value, size_t size, int flags) {
initialize_passthrough_if_necessary();
xprintf(" fsetxattr(%d, %s, ...)\n", fd, name);
if (overlay_initialized() && is_xtreemfs_fd(fd)) {
xprintf(" NOT IMPLEMENTED: fsetxattr for xtreemfs fd(%d)", fd);
return -1;
} else {
return ((funcptr_fsetxattr)libattr_fsetxattr)(fd, name, value, size, flags);
}
}
} // extern "C"
| bsd-3-clause |
jorisvandenbossche/pandas | pandas/tests/series/test_reductions.py | 3181 | import numpy as np
import pytest
import pandas as pd
from pandas import (
MultiIndex,
Series,
)
import pandas._testing as tm
def test_reductions_td64_with_nat():
# GH#8617
ser = Series([0, pd.NaT], dtype="m8[ns]")
exp = ser[0]
assert ser.median() == exp
assert ser.min() == exp
assert ser.max() == exp
@pytest.mark.parametrize("skipna", [True, False])
def test_td64_sum_empty(skipna):
# GH#37151
ser = Series([], dtype="timedelta64[ns]")
result = ser.sum(skipna=skipna)
assert isinstance(result, pd.Timedelta)
assert result == pd.Timedelta(0)
def test_td64_summation_overflow():
# GH#9442
ser = Series(pd.date_range("20130101", periods=100000, freq="H"))
ser[0] += pd.Timedelta("1s 1ms")
# mean
result = (ser - ser.min()).mean()
expected = pd.Timedelta((pd.TimedeltaIndex(ser - ser.min()).asi8 / len(ser)).sum())
# the computation is converted to float so
# might be some loss of precision
assert np.allclose(result.value / 1000, expected.value / 1000)
# sum
msg = "overflow in timedelta operation"
with pytest.raises(ValueError, match=msg):
(ser - ser.min()).sum()
s1 = ser[0:10000]
with pytest.raises(ValueError, match=msg):
(s1 - s1.min()).sum()
s2 = ser[0:1000]
(s2 - s2.min()).sum()
def test_prod_numpy16_bug():
ser = Series([1.0, 1.0, 1.0], index=range(3))
result = ser.prod()
assert not isinstance(result, Series)
def test_sum_with_level():
obj = Series([10.0], index=MultiIndex.from_tuples([(2, 3)]))
with tm.assert_produces_warning(FutureWarning):
result = obj.sum(level=0)
expected = Series([10.0], index=[2])
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("func", [np.any, np.all])
@pytest.mark.parametrize("kwargs", [{"keepdims": True}, {"out": object()}])
def test_validate_any_all_out_keepdims_raises(kwargs, func):
ser = Series([1, 2])
param = list(kwargs)[0]
name = func.__name__
msg = (
f"the '{param}' parameter is not "
"supported in the pandas "
fr"implementation of {name}\(\)"
)
with pytest.raises(ValueError, match=msg):
func(ser, **kwargs)
def test_validate_sum_initial():
ser = Series([1, 2])
msg = (
r"the 'initial' parameter is not "
r"supported in the pandas "
r"implementation of sum\(\)"
)
with pytest.raises(ValueError, match=msg):
np.sum(ser, initial=10)
def test_validate_median_initial():
ser = Series([1, 2])
msg = (
r"the 'overwrite_input' parameter is not "
r"supported in the pandas "
r"implementation of median\(\)"
)
with pytest.raises(ValueError, match=msg):
# It seems like np.median doesn't dispatch, so we use the
# method instead of the ufunc.
ser.median(overwrite_input=True)
def test_validate_stat_keepdims():
ser = Series([1, 2])
msg = (
r"the 'keepdims' parameter is not "
r"supported in the pandas "
r"implementation of sum\(\)"
)
with pytest.raises(ValueError, match=msg):
np.sum(ser, keepdims=True)
| bsd-3-clause |
angel2d/angel2d | Code/Angel/Libraries/gwen/Util/ControlFactory/VerticalSplitter_Factory.cpp | 1211 |
#include "Gwen/Util/ControlFactory.h"
#include "Gwen/Controls.h"
using namespace Gwen;
class VerticalSplitter_Factory : public Gwen::ControlFactory::Base
{
public:
GWEN_CONTROL_FACTORY_CONSTRUCTOR( VerticalSplitter_Factory, Gwen::ControlFactory::Base )
{
}
virtual Gwen::String Name(){ return "VerticalSplitter"; }
virtual Gwen::String BaseName(){ return "Base"; }
virtual Gwen::Controls::Base* CreateInstance( Gwen::Controls::Base* parent )
{
Gwen::Controls::SplitterVertical* pControl = new Gwen::Controls::SplitterVertical( parent );
pControl->SetSize( 200, 200 );
return pControl;
}
void AddChild( Gwen::Controls::Base* ctrl, Gwen::Controls::Base* child, Gwen::Point& pos )
{
Gwen::Controls::SplitterVertical* pSplitter = gwen_cast<Gwen::Controls::SplitterVertical>(ctrl);
child->SetParent( pSplitter );
if ( pos.y < pSplitter->SplitterPos() )
pSplitter->SetPanels( child, NULL );
else
pSplitter->SetPanels( NULL, child );
}
void AddChild( Gwen::Controls::Base* ctrl, Gwen::Controls::Base* child, int iPage )
{
child->SetParent( ctrl );
}
};
GWEN_CONTROL_FACTORY( VerticalSplitter_Factory ); | bsd-3-clause |
njase/numpy | numpy/testing/utils.py | 76351 | """
Utility function to facilitate testing.
"""
from __future__ import division, absolute_import, print_function
import os
import sys
import re
import operator
import warnings
from functools import partial, wraps
import shutil
import contextlib
from tempfile import mkdtemp, mkstemp
from unittest.case import SkipTest
from numpy.core import float32, empty, arange, array_repr, ndarray
from numpy.lib.utils import deprecate
if sys.version_info[0] >= 3:
from io import StringIO
else:
from StringIO import StringIO
__all__ = [
'assert_equal', 'assert_almost_equal', 'assert_approx_equal',
'assert_array_equal', 'assert_array_less', 'assert_string_equal',
'assert_array_almost_equal', 'assert_raises', 'build_err_msg',
'decorate_methods', 'jiffies', 'memusage', 'print_assert_equal',
'raises', 'rand', 'rundocs', 'runstring', 'verbose', 'measure',
'assert_', 'assert_array_almost_equal_nulp', 'assert_raises_regex',
'assert_array_max_ulp', 'assert_warns', 'assert_no_warnings',
'assert_allclose', 'IgnoreException', 'clear_and_catch_warnings',
'SkipTest', 'KnownFailureException', 'temppath', 'tempdir', 'IS_PYPY',
'HAS_REFCOUNT', 'suppress_warnings'
]
class KnownFailureException(Exception):
'''Raise this exception to mark a test as a known failing test.'''
pass
KnownFailureTest = KnownFailureException # backwards compat
verbose = 0
IS_PYPY = '__pypy__' in sys.modules
HAS_REFCOUNT = getattr(sys, 'getrefcount', None) is not None
def import_nose():
""" Import nose only when needed.
"""
nose_is_good = True
minimum_nose_version = (1, 0, 0)
try:
import nose
except ImportError:
nose_is_good = False
else:
if nose.__versioninfo__ < minimum_nose_version:
nose_is_good = False
if not nose_is_good:
msg = ('Need nose >= %d.%d.%d for tests - see '
'http://nose.readthedocs.io' %
minimum_nose_version)
raise ImportError(msg)
return nose
def assert_(val, msg=''):
"""
Assert that works in release mode.
Accepts callable msg to allow deferring evaluation until failure.
The Python built-in ``assert`` does not work when executing code in
optimized mode (the ``-O`` flag) - no byte-code is generated for it.
For documentation on usage, refer to the Python documentation.
"""
if not val:
try:
smsg = msg()
except TypeError:
smsg = msg
raise AssertionError(smsg)
def gisnan(x):
"""like isnan, but always raise an error if type not supported instead of
returning a TypeError object.
Notes
-----
isnan and other ufunc sometimes return a NotImplementedType object instead
of raising any exception. This function is a wrapper to make sure an
exception is always raised.
This should be removed once this problem is solved at the Ufunc level."""
from numpy.core import isnan
st = isnan(x)
if isinstance(st, type(NotImplemented)):
raise TypeError("isnan not supported for this type")
return st
def gisfinite(x):
"""like isfinite, but always raise an error if type not supported instead of
returning a TypeError object.
Notes
-----
isfinite and other ufunc sometimes return a NotImplementedType object instead
of raising any exception. This function is a wrapper to make sure an
exception is always raised.
This should be removed once this problem is solved at the Ufunc level."""
from numpy.core import isfinite, errstate
with errstate(invalid='ignore'):
st = isfinite(x)
if isinstance(st, type(NotImplemented)):
raise TypeError("isfinite not supported for this type")
return st
def gisinf(x):
"""like isinf, but always raise an error if type not supported instead of
returning a TypeError object.
Notes
-----
isinf and other ufunc sometimes return a NotImplementedType object instead
of raising any exception. This function is a wrapper to make sure an
exception is always raised.
This should be removed once this problem is solved at the Ufunc level."""
from numpy.core import isinf, errstate
with errstate(invalid='ignore'):
st = isinf(x)
if isinstance(st, type(NotImplemented)):
raise TypeError("isinf not supported for this type")
return st
@deprecate(message="numpy.testing.rand is deprecated in numpy 1.11. "
"Use numpy.random.rand instead.")
def rand(*args):
"""Returns an array of random numbers with the given shape.
This only uses the standard library, so it is useful for testing purposes.
"""
import random
from numpy.core import zeros, float64
results = zeros(args, float64)
f = results.flat
for i in range(len(f)):
f[i] = random.random()
return results
if os.name == 'nt':
# Code "stolen" from enthought/debug/memusage.py
def GetPerformanceAttributes(object, counter, instance=None,
inum=-1, format=None, machine=None):
# NOTE: Many counters require 2 samples to give accurate results,
# including "% Processor Time" (as by definition, at any instant, a
# thread's CPU usage is either 0 or 100). To read counters like this,
# you should copy this function, but keep the counter open, and call
# CollectQueryData() each time you need to know.
# See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp
# My older explanation for this was that the "AddCounter" process forced
# the CPU to 100%, but the above makes more sense :)
import win32pdh
if format is None:
format = win32pdh.PDH_FMT_LONG
path = win32pdh.MakeCounterPath( (machine, object, instance, None, inum, counter))
hq = win32pdh.OpenQuery()
try:
hc = win32pdh.AddCounter(hq, path)
try:
win32pdh.CollectQueryData(hq)
type, val = win32pdh.GetFormattedCounterValue(hc, format)
return val
finally:
win32pdh.RemoveCounter(hc)
finally:
win32pdh.CloseQuery(hq)
def memusage(processName="python", instance=0):
# from win32pdhutil, part of the win32all package
import win32pdh
return GetPerformanceAttributes("Process", "Virtual Bytes",
processName, instance,
win32pdh.PDH_FMT_LONG, None)
elif sys.platform[:5] == 'linux':
def memusage(_proc_pid_stat='/proc/%s/stat' % (os.getpid())):
"""
Return virtual memory size in bytes of the running python.
"""
try:
f = open(_proc_pid_stat, 'r')
l = f.readline().split(' ')
f.close()
return int(l[22])
except:
return
else:
def memusage():
"""
Return memory usage of running python. [Not implemented]
"""
raise NotImplementedError
if sys.platform[:5] == 'linux':
def jiffies(_proc_pid_stat='/proc/%s/stat' % (os.getpid()),
_load_time=[]):
"""
Return number of jiffies elapsed.
Return number of jiffies (1/100ths of a second) that this
process has been scheduled in user mode. See man 5 proc.
"""
import time
if not _load_time:
_load_time.append(time.time())
try:
f = open(_proc_pid_stat, 'r')
l = f.readline().split(' ')
f.close()
return int(l[13])
except:
return int(100*(time.time()-_load_time[0]))
else:
# os.getpid is not in all platforms available.
# Using time is safe but inaccurate, especially when process
# was suspended or sleeping.
def jiffies(_load_time=[]):
"""
Return number of jiffies elapsed.
Return number of jiffies (1/100ths of a second) that this
process has been scheduled in user mode. See man 5 proc.
"""
import time
if not _load_time:
_load_time.append(time.time())
return int(100*(time.time()-_load_time[0]))
def build_err_msg(arrays, err_msg, header='Items are not equal:',
verbose=True, names=('ACTUAL', 'DESIRED'), precision=8):
msg = ['\n' + header]
if err_msg:
if err_msg.find('\n') == -1 and len(err_msg) < 79-len(header):
msg = [msg[0] + ' ' + err_msg]
else:
msg.append(err_msg)
if verbose:
for i, a in enumerate(arrays):
if isinstance(a, ndarray):
# precision argument is only needed if the objects are ndarrays
r_func = partial(array_repr, precision=precision)
else:
r_func = repr
try:
r = r_func(a)
except Exception as exc:
r = '[repr failed for <{}>: {}]'.format(type(a).__name__, exc)
if r.count('\n') > 3:
r = '\n'.join(r.splitlines()[:3])
r += '...'
msg.append(' %s: %s' % (names[i], r))
return '\n'.join(msg)
def assert_equal(actual,desired,err_msg='',verbose=True):
"""
Raises an AssertionError if two objects are not equal.
Given two objects (scalars, lists, tuples, dictionaries or numpy arrays),
check that all elements of these objects are equal. An exception is raised
at the first conflicting values.
Parameters
----------
actual : array_like
The object to check.
desired : array_like
The expected object.
err_msg : str, optional
The error message to be printed in case of failure.
verbose : bool, optional
If True, the conflicting values are appended to the error message.
Raises
------
AssertionError
If actual and desired are not equal.
Examples
--------
>>> np.testing.assert_equal([4,5], [4,6])
...
<type 'exceptions.AssertionError'>:
Items are not equal:
item=1
ACTUAL: 5
DESIRED: 6
"""
__tracebackhide__ = True # Hide traceback for py.test
if isinstance(desired, dict):
if not isinstance(actual, dict):
raise AssertionError(repr(type(actual)))
assert_equal(len(actual), len(desired), err_msg, verbose)
for k, i in desired.items():
if k not in actual:
raise AssertionError(repr(k))
assert_equal(actual[k], desired[k], 'key=%r\n%s' % (k, err_msg), verbose)
return
if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):
assert_equal(len(actual), len(desired), err_msg, verbose)
for k in range(len(desired)):
assert_equal(actual[k], desired[k], 'item=%r\n%s' % (k, err_msg), verbose)
return
from numpy.core import ndarray, isscalar, signbit
from numpy.lib import iscomplexobj, real, imag
if isinstance(actual, ndarray) or isinstance(desired, ndarray):
return assert_array_equal(actual, desired, err_msg, verbose)
msg = build_err_msg([actual, desired], err_msg, verbose=verbose)
# Handle complex numbers: separate into real/imag to handle
# nan/inf/negative zero correctly
# XXX: catch ValueError for subclasses of ndarray where iscomplex fail
try:
usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
except ValueError:
usecomplex = False
if usecomplex:
if iscomplexobj(actual):
actualr = real(actual)
actuali = imag(actual)
else:
actualr = actual
actuali = 0
if iscomplexobj(desired):
desiredr = real(desired)
desiredi = imag(desired)
else:
desiredr = desired
desiredi = 0
try:
assert_equal(actualr, desiredr)
assert_equal(actuali, desiredi)
except AssertionError:
raise AssertionError(msg)
# Inf/nan/negative zero handling
try:
# isscalar test to check cases such as [np.nan] != np.nan
if isscalar(desired) != isscalar(actual):
raise AssertionError(msg)
# If one of desired/actual is not finite, handle it specially here:
# check that both are nan if any is a nan, and test for equality
# otherwise
if not (gisfinite(desired) and gisfinite(actual)):
isdesnan = gisnan(desired)
isactnan = gisnan(actual)
if isdesnan or isactnan:
if not (isdesnan and isactnan):
raise AssertionError(msg)
else:
if not desired == actual:
raise AssertionError(msg)
return
elif desired == 0 and actual == 0:
if not signbit(desired) == signbit(actual):
raise AssertionError(msg)
# If TypeError or ValueError raised while using isnan and co, just handle
# as before
except (TypeError, ValueError, NotImplementedError):
pass
# Explicitly use __eq__ for comparison, ticket #2552
with suppress_warnings() as sup:
# TODO: Better handling will to needed when change happens!
sup.filter(DeprecationWarning, ".*NAT ==")
sup.filter(FutureWarning, ".*NAT ==")
if not (desired == actual):
raise AssertionError(msg)
def print_assert_equal(test_string, actual, desired):
"""
Test if two objects are equal, and print an error message if test fails.
The test is performed with ``actual == desired``.
Parameters
----------
test_string : str
The message supplied to AssertionError.
actual : object
The object to test for equality against `desired`.
desired : object
The expected result.
Examples
--------
>>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 1])
>>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 2])
Traceback (most recent call last):
...
AssertionError: Test XYZ of func xyz failed
ACTUAL:
[0, 1]
DESIRED:
[0, 2]
"""
__tracebackhide__ = True # Hide traceback for py.test
import pprint
if not (actual == desired):
msg = StringIO()
msg.write(test_string)
msg.write(' failed\nACTUAL: \n')
pprint.pprint(actual, msg)
msg.write('DESIRED: \n')
pprint.pprint(desired, msg)
raise AssertionError(msg.getvalue())
def assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=True):
"""
Raises an AssertionError if two items are not equal up to desired
precision.
.. note:: It is recommended to use one of `assert_allclose`,
`assert_array_almost_equal_nulp` or `assert_array_max_ulp`
instead of this function for more consistent floating point
comparisons.
The test verifies that the elements of ``actual`` and ``desired`` satisfy.
``abs(desired-actual) < 1.5 * 10**(-decimal)``
That is a looser test than originally documented, but agrees with what the
actual implementation in `assert_array_almost_equal` did up to rounding
vagaries. An exception is raised at conflicting values. For ndarrays this
delegates to assert_array_almost_equal
Parameters
----------
actual : array_like
The object to check.
desired : array_like
The expected object.
decimal : int, optional
Desired precision, default is 7.
err_msg : str, optional
The error message to be printed in case of failure.
verbose : bool, optional
If True, the conflicting values are appended to the error message.
Raises
------
AssertionError
If actual and desired are not equal up to specified precision.
See Also
--------
assert_allclose: Compare two array_like objects for equality with desired
relative and/or absolute precision.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
Examples
--------
>>> import numpy.testing as npt
>>> npt.assert_almost_equal(2.3333333333333, 2.33333334)
>>> npt.assert_almost_equal(2.3333333333333, 2.33333334, decimal=10)
...
<type 'exceptions.AssertionError'>:
Items are not equal:
ACTUAL: 2.3333333333333002
DESIRED: 2.3333333399999998
>>> npt.assert_almost_equal(np.array([1.0,2.3333333333333]),
... np.array([1.0,2.33333334]), decimal=9)
...
<type 'exceptions.AssertionError'>:
Arrays are not almost equal
<BLANKLINE>
(mismatch 50.0%)
x: array([ 1. , 2.33333333])
y: array([ 1. , 2.33333334])
"""
__tracebackhide__ = True # Hide traceback for py.test
from numpy.core import ndarray
from numpy.lib import iscomplexobj, real, imag
# Handle complex numbers: separate into real/imag to handle
# nan/inf/negative zero correctly
# XXX: catch ValueError for subclasses of ndarray where iscomplex fail
try:
usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
except ValueError:
usecomplex = False
def _build_err_msg():
header = ('Arrays are not almost equal to %d decimals' % decimal)
return build_err_msg([actual, desired], err_msg, verbose=verbose,
header=header)
if usecomplex:
if iscomplexobj(actual):
actualr = real(actual)
actuali = imag(actual)
else:
actualr = actual
actuali = 0
if iscomplexobj(desired):
desiredr = real(desired)
desiredi = imag(desired)
else:
desiredr = desired
desiredi = 0
try:
assert_almost_equal(actualr, desiredr, decimal=decimal)
assert_almost_equal(actuali, desiredi, decimal=decimal)
except AssertionError:
raise AssertionError(_build_err_msg())
if isinstance(actual, (ndarray, tuple, list)) \
or isinstance(desired, (ndarray, tuple, list)):
return assert_array_almost_equal(actual, desired, decimal, err_msg)
try:
# If one of desired/actual is not finite, handle it specially here:
# check that both are nan if any is a nan, and test for equality
# otherwise
if not (gisfinite(desired) and gisfinite(actual)):
if gisnan(desired) or gisnan(actual):
if not (gisnan(desired) and gisnan(actual)):
raise AssertionError(_build_err_msg())
else:
if not desired == actual:
raise AssertionError(_build_err_msg())
return
except (NotImplementedError, TypeError):
pass
if abs(desired - actual) >= 1.5 * 10.0**(-decimal):
raise AssertionError(_build_err_msg())
def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=True):
"""
Raises an AssertionError if two items are not equal up to significant
digits.
.. note:: It is recommended to use one of `assert_allclose`,
`assert_array_almost_equal_nulp` or `assert_array_max_ulp`
instead of this function for more consistent floating point
comparisons.
Given two numbers, check that they are approximately equal.
Approximately equal is defined as the number of significant digits
that agree.
Parameters
----------
actual : scalar
The object to check.
desired : scalar
The expected object.
significant : int, optional
Desired precision, default is 7.
err_msg : str, optional
The error message to be printed in case of failure.
verbose : bool, optional
If True, the conflicting values are appended to the error message.
Raises
------
AssertionError
If actual and desired are not equal up to specified precision.
See Also
--------
assert_allclose: Compare two array_like objects for equality with desired
relative and/or absolute precision.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
Examples
--------
>>> np.testing.assert_approx_equal(0.12345677777777e-20, 0.1234567e-20)
>>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345671e-20,
significant=8)
>>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345672e-20,
significant=8)
...
<type 'exceptions.AssertionError'>:
Items are not equal to 8 significant digits:
ACTUAL: 1.234567e-021
DESIRED: 1.2345672000000001e-021
the evaluated condition that raises the exception is
>>> abs(0.12345670e-20/1e-21 - 0.12345672e-20/1e-21) >= 10**-(8-1)
True
"""
__tracebackhide__ = True # Hide traceback for py.test
import numpy as np
(actual, desired) = map(float, (actual, desired))
if desired == actual:
return
# Normalized the numbers to be in range (-10.0,10.0)
# scale = float(pow(10,math.floor(math.log10(0.5*(abs(desired)+abs(actual))))))
with np.errstate(invalid='ignore'):
scale = 0.5*(np.abs(desired) + np.abs(actual))
scale = np.power(10, np.floor(np.log10(scale)))
try:
sc_desired = desired/scale
except ZeroDivisionError:
sc_desired = 0.0
try:
sc_actual = actual/scale
except ZeroDivisionError:
sc_actual = 0.0
msg = build_err_msg([actual, desired], err_msg,
header='Items are not equal to %d significant digits:' %
significant,
verbose=verbose)
try:
# If one of desired/actual is not finite, handle it specially here:
# check that both are nan if any is a nan, and test for equality
# otherwise
if not (gisfinite(desired) and gisfinite(actual)):
if gisnan(desired) or gisnan(actual):
if not (gisnan(desired) and gisnan(actual)):
raise AssertionError(msg)
else:
if not desired == actual:
raise AssertionError(msg)
return
except (TypeError, NotImplementedError):
pass
if np.abs(sc_desired - sc_actual) >= np.power(10., -(significant-1)):
raise AssertionError(msg)
def assert_array_compare(comparison, x, y, err_msg='', verbose=True,
header='', precision=6, equal_nan=True):
__tracebackhide__ = True # Hide traceback for py.test
from numpy.core import array, isnan, isinf, any, all, inf
x = array(x, copy=False, subok=True)
y = array(y, copy=False, subok=True)
def safe_comparison(*args, **kwargs):
# There are a number of cases where comparing two arrays hits special
# cases in array_richcompare, specifically around strings and void
# dtypes. Basically, we just can't do comparisons involving these
# types, unless both arrays have exactly the *same* type. So
# e.g. you can apply == to two string arrays, or two arrays with
# identical structured dtypes. But if you compare a non-string array
# to a string array, or two arrays with non-identical structured
# dtypes, or anything like that, then internally stuff blows up.
# Currently, when things blow up, we just return a scalar False or
# True. But we also emit a DeprecationWarning, b/c eventually we
# should raise an error here. (Ideally we might even make this work
# properly, but since that will require rewriting a bunch of how
# ufuncs work then we are not counting on that.)
#
# The point of this little function is to let the DeprecationWarning
# pass (or maybe eventually catch the errors and return False, I
# dunno, that's a little trickier and we can figure that out when the
# time comes).
with suppress_warnings() as sup:
sup.filter(DeprecationWarning, ".*==")
sup.filter(FutureWarning, ".*==")
return comparison(*args, **kwargs)
def isnumber(x):
return x.dtype.char in '?bhilqpBHILQPefdgFDG'
def chk_same_position(x_id, y_id, hasval='nan'):
"""Handling nan/inf: check that x and y have the nan/inf at the same
locations."""
try:
assert_array_equal(x_id, y_id)
except AssertionError:
msg = build_err_msg([x, y],
err_msg + '\nx and y %s location mismatch:'
% (hasval), verbose=verbose, header=header,
names=('x', 'y'), precision=precision)
raise AssertionError(msg)
try:
cond = (x.shape == () or y.shape == ()) or x.shape == y.shape
if not cond:
msg = build_err_msg([x, y],
err_msg
+ '\n(shapes %s, %s mismatch)' % (x.shape,
y.shape),
verbose=verbose, header=header,
names=('x', 'y'), precision=precision)
if not cond:
raise AssertionError(msg)
if isnumber(x) and isnumber(y):
if equal_nan:
x_isnan, y_isnan = isnan(x), isnan(y)
# Validate that NaNs are in the same place
if any(x_isnan) or any(y_isnan):
chk_same_position(x_isnan, y_isnan, hasval='nan')
x_isinf, y_isinf = isinf(x), isinf(y)
# Validate that infinite values are in the same place
if any(x_isinf) or any(y_isinf):
# Check +inf and -inf separately, since they are different
chk_same_position(x == +inf, y == +inf, hasval='+inf')
chk_same_position(x == -inf, y == -inf, hasval='-inf')
# Combine all the special values
x_id, y_id = x_isinf, y_isinf
if equal_nan:
x_id |= x_isnan
y_id |= y_isnan
# Only do the comparison if actual values are left
if all(x_id):
return
if any(x_id):
val = safe_comparison(x[~x_id], y[~y_id])
else:
val = safe_comparison(x, y)
else:
val = safe_comparison(x, y)
if isinstance(val, bool):
cond = val
reduced = [0]
else:
reduced = val.ravel()
cond = reduced.all()
reduced = reduced.tolist()
if not cond:
match = 100-100.0*reduced.count(1)/len(reduced)
msg = build_err_msg([x, y],
err_msg
+ '\n(mismatch %s%%)' % (match,),
verbose=verbose, header=header,
names=('x', 'y'), precision=precision)
if not cond:
raise AssertionError(msg)
except ValueError:
import traceback
efmt = traceback.format_exc()
header = 'error during assertion:\n\n%s\n\n%s' % (efmt, header)
msg = build_err_msg([x, y], err_msg, verbose=verbose, header=header,
names=('x', 'y'), precision=precision)
raise ValueError(msg)
def assert_array_equal(x, y, err_msg='', verbose=True):
"""
Raises an AssertionError if two array_like objects are not equal.
Given two array_like objects, check that the shape is equal and all
elements of these objects are equal. An exception is raised at
shape mismatch or conflicting values. In contrast to the standard usage
in numpy, NaNs are compared like numbers, no assertion is raised if
both objects have NaNs in the same positions.
The usual caution for verifying equality with floating point numbers is
advised.
Parameters
----------
x : array_like
The actual object to check.
y : array_like
The desired, expected object.
err_msg : str, optional
The error message to be printed in case of failure.
verbose : bool, optional
If True, the conflicting values are appended to the error message.
Raises
------
AssertionError
If actual and desired objects are not equal.
See Also
--------
assert_allclose: Compare two array_like objects for equality with desired
relative and/or absolute precision.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
Examples
--------
The first assert does not raise an exception:
>>> np.testing.assert_array_equal([1.0,2.33333,np.nan],
... [np.exp(0),2.33333, np.nan])
Assert fails with numerical inprecision with floats:
>>> np.testing.assert_array_equal([1.0,np.pi,np.nan],
... [1, np.sqrt(np.pi)**2, np.nan])
...
<type 'exceptions.ValueError'>:
AssertionError:
Arrays are not equal
<BLANKLINE>
(mismatch 50.0%)
x: array([ 1. , 3.14159265, NaN])
y: array([ 1. , 3.14159265, NaN])
Use `assert_allclose` or one of the nulp (number of floating point values)
functions for these cases instead:
>>> np.testing.assert_allclose([1.0,np.pi,np.nan],
... [1, np.sqrt(np.pi)**2, np.nan],
... rtol=1e-10, atol=0)
"""
assert_array_compare(operator.__eq__, x, y, err_msg=err_msg,
verbose=verbose, header='Arrays are not equal')
def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True):
"""
Raises an AssertionError if two objects are not equal up to desired
precision.
.. note:: It is recommended to use one of `assert_allclose`,
`assert_array_almost_equal_nulp` or `assert_array_max_ulp`
instead of this function for more consistent floating point
comparisons.
The test verifies identical shapes and that the elements of ``actual`` and
``desired`` satisfy.
``abs(desired-actual) < 1.5 * 10**(-decimal)``
That is a looser test than originally documented, but agrees with what the
actual implementation did up to rounding vagaries. An exception is raised
at shape mismatch or conflicting values. In contrast to the standard usage
in numpy, NaNs are compared like numbers, no assertion is raised if both
objects have NaNs in the same positions.
Parameters
----------
x : array_like
The actual object to check.
y : array_like
The desired, expected object.
decimal : int, optional
Desired precision, default is 6.
err_msg : str, optional
The error message to be printed in case of failure.
verbose : bool, optional
If True, the conflicting values are appended to the error message.
Raises
------
AssertionError
If actual and desired are not equal up to specified precision.
See Also
--------
assert_allclose: Compare two array_like objects for equality with desired
relative and/or absolute precision.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
Examples
--------
the first assert does not raise an exception
>>> np.testing.assert_array_almost_equal([1.0,2.333,np.nan],
[1.0,2.333,np.nan])
>>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
... [1.0,2.33339,np.nan], decimal=5)
...
<type 'exceptions.AssertionError'>:
AssertionError:
Arrays are not almost equal
<BLANKLINE>
(mismatch 50.0%)
x: array([ 1. , 2.33333, NaN])
y: array([ 1. , 2.33339, NaN])
>>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
... [1.0,2.33333, 5], decimal=5)
<type 'exceptions.ValueError'>:
ValueError:
Arrays are not almost equal
x: array([ 1. , 2.33333, NaN])
y: array([ 1. , 2.33333, 5. ])
"""
__tracebackhide__ = True # Hide traceback for py.test
from numpy.core import around, number, float_, result_type, array
from numpy.core.numerictypes import issubdtype
from numpy.core.fromnumeric import any as npany
def compare(x, y):
try:
if npany(gisinf(x)) or npany( gisinf(y)):
xinfid = gisinf(x)
yinfid = gisinf(y)
if not xinfid == yinfid:
return False
# if one item, x and y is +- inf
if x.size == y.size == 1:
return x == y
x = x[~xinfid]
y = y[~yinfid]
except (TypeError, NotImplementedError):
pass
# make sure y is an inexact type to avoid abs(MIN_INT); will cause
# casting of x later.
dtype = result_type(y, 1.)
y = array(y, dtype=dtype, copy=False, subok=True)
z = abs(x - y)
if not issubdtype(z.dtype, number):
z = z.astype(float_) # handle object arrays
return z < 1.5 * 10.0**(-decimal)
assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,
header=('Arrays are not almost equal to %d decimals' % decimal),
precision=decimal)
def assert_array_less(x, y, err_msg='', verbose=True):
"""
Raises an AssertionError if two array_like objects are not ordered by less
than.
Given two array_like objects, check that the shape is equal and all
elements of the first object are strictly smaller than those of the
second object. An exception is raised at shape mismatch or incorrectly
ordered values. Shape mismatch does not raise if an object has zero
dimension. In contrast to the standard usage in numpy, NaNs are
compared, no assertion is raised if both objects have NaNs in the same
positions.
Parameters
----------
x : array_like
The smaller object to check.
y : array_like
The larger object to compare.
err_msg : string
The error message to be printed in case of failure.
verbose : bool
If True, the conflicting values are appended to the error message.
Raises
------
AssertionError
If actual and desired objects are not equal.
See Also
--------
assert_array_equal: tests objects for equality
assert_array_almost_equal: test objects for equality up to precision
Examples
--------
>>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1.1, 2.0, np.nan])
>>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1, 2.0, np.nan])
...
<type 'exceptions.ValueError'>:
Arrays are not less-ordered
(mismatch 50.0%)
x: array([ 1., 1., NaN])
y: array([ 1., 2., NaN])
>>> np.testing.assert_array_less([1.0, 4.0], 3)
...
<type 'exceptions.ValueError'>:
Arrays are not less-ordered
(mismatch 50.0%)
x: array([ 1., 4.])
y: array(3)
>>> np.testing.assert_array_less([1.0, 2.0, 3.0], [4])
...
<type 'exceptions.ValueError'>:
Arrays are not less-ordered
(shapes (3,), (1,) mismatch)
x: array([ 1., 2., 3.])
y: array([4])
"""
__tracebackhide__ = True # Hide traceback for py.test
assert_array_compare(operator.__lt__, x, y, err_msg=err_msg,
verbose=verbose,
header='Arrays are not less-ordered')
def runstring(astr, dict):
exec(astr, dict)
def assert_string_equal(actual, desired):
"""
Test if two strings are equal.
If the given strings are equal, `assert_string_equal` does nothing.
If they are not equal, an AssertionError is raised, and the diff
between the strings is shown.
Parameters
----------
actual : str
The string to test for equality against the expected string.
desired : str
The expected string.
Examples
--------
>>> np.testing.assert_string_equal('abc', 'abc')
>>> np.testing.assert_string_equal('abc', 'abcd')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
...
AssertionError: Differences in strings:
- abc+ abcd? +
"""
# delay import of difflib to reduce startup time
__tracebackhide__ = True # Hide traceback for py.test
import difflib
if not isinstance(actual, str):
raise AssertionError(repr(type(actual)))
if not isinstance(desired, str):
raise AssertionError(repr(type(desired)))
if re.match(r'\A'+desired+r'\Z', actual, re.M):
return
diff = list(difflib.Differ().compare(actual.splitlines(1), desired.splitlines(1)))
diff_list = []
while diff:
d1 = diff.pop(0)
if d1.startswith(' '):
continue
if d1.startswith('- '):
l = [d1]
d2 = diff.pop(0)
if d2.startswith('? '):
l.append(d2)
d2 = diff.pop(0)
if not d2.startswith('+ '):
raise AssertionError(repr(d2))
l.append(d2)
if diff:
d3 = diff.pop(0)
if d3.startswith('? '):
l.append(d3)
else:
diff.insert(0, d3)
if re.match(r'\A'+d2[2:]+r'\Z', d1[2:]):
continue
diff_list.extend(l)
continue
raise AssertionError(repr(d1))
if not diff_list:
return
msg = 'Differences in strings:\n%s' % (''.join(diff_list)).rstrip()
if actual != desired:
raise AssertionError(msg)
def rundocs(filename=None, raise_on_error=True):
"""
Run doctests found in the given file.
By default `rundocs` raises an AssertionError on failure.
Parameters
----------
filename : str
The path to the file for which the doctests are run.
raise_on_error : bool
Whether to raise an AssertionError when a doctest fails. Default is
True.
Notes
-----
The doctests can be run by the user/developer by adding the ``doctests``
argument to the ``test()`` call. For example, to run all tests (including
doctests) for `numpy.lib`:
>>> np.lib.test(doctests=True) #doctest: +SKIP
"""
from numpy.compat import npy_load_module
import doctest
if filename is None:
f = sys._getframe(1)
filename = f.f_globals['__file__']
name = os.path.splitext(os.path.basename(filename))[0]
m = npy_load_module(name, filename)
tests = doctest.DocTestFinder().find(m)
runner = doctest.DocTestRunner(verbose=False)
msg = []
if raise_on_error:
out = lambda s: msg.append(s)
else:
out = None
for test in tests:
runner.run(test, out=out)
if runner.failures > 0 and raise_on_error:
raise AssertionError("Some doctests failed:\n%s" % "\n".join(msg))
def raises(*args,**kwargs):
nose = import_nose()
return nose.tools.raises(*args,**kwargs)
def assert_raises(*args, **kwargs):
"""
assert_raises(exception_class, callable, *args, **kwargs)
assert_raises(exception_class)
Fail unless an exception of class exception_class is thrown
by callable when invoked with arguments args and keyword
arguments kwargs. If a different type of exception is
thrown, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.
Alternatively, `assert_raises` can be used as a context manager:
>>> from numpy.testing import assert_raises
>>> with assert_raises(ZeroDivisionError):
... 1 / 0
is equivalent to
>>> def div(x, y):
... return x / y
>>> assert_raises(ZeroDivisionError, div, 1, 0)
"""
__tracebackhide__ = True # Hide traceback for py.test
nose = import_nose()
return nose.tools.assert_raises(*args,**kwargs)
def assert_raises_regex(exception_class, expected_regexp, *args, **kwargs):
"""
assert_raises_regex(exception_class, expected_regexp, callable, *args,
**kwargs)
assert_raises_regex(exception_class, expected_regexp)
Fail unless an exception of class exception_class and with message that
matches expected_regexp is thrown by callable when invoked with arguments
args and keyword arguments kwargs.
Alternatively, can be used as a context manager like `assert_raises`.
Name of this function adheres to Python 3.2+ reference, but should work in
all versions down to 2.6.
Notes
-----
.. versionadded:: 1.9.0
"""
__tracebackhide__ = True # Hide traceback for py.test
nose = import_nose()
if sys.version_info.major >= 3:
funcname = nose.tools.assert_raises_regex
else:
# Only present in Python 2.7, missing from unittest in 2.6
funcname = nose.tools.assert_raises_regexp
return funcname(exception_class, expected_regexp, *args, **kwargs)
def decorate_methods(cls, decorator, testmatch=None):
"""
Apply a decorator to all methods in a class matching a regular expression.
The given decorator is applied to all public methods of `cls` that are
matched by the regular expression `testmatch`
(``testmatch.search(methodname)``). Methods that are private, i.e. start
with an underscore, are ignored.
Parameters
----------
cls : class
Class whose methods to decorate.
decorator : function
Decorator to apply to methods
testmatch : compiled regexp or str, optional
The regular expression. Default value is None, in which case the
nose default (``re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep)``)
is used.
If `testmatch` is a string, it is compiled to a regular expression
first.
"""
if testmatch is None:
testmatch = re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep)
else:
testmatch = re.compile(testmatch)
cls_attr = cls.__dict__
# delayed import to reduce startup time
from inspect import isfunction
methods = [_m for _m in cls_attr.values() if isfunction(_m)]
for function in methods:
try:
if hasattr(function, 'compat_func_name'):
funcname = function.compat_func_name
else:
funcname = function.__name__
except AttributeError:
# not a function
continue
if testmatch.search(funcname) and not funcname.startswith('_'):
setattr(cls, funcname, decorator(function))
return
def measure(code_str,times=1,label=None):
"""
Return elapsed time for executing code in the namespace of the caller.
The supplied code string is compiled with the Python builtin ``compile``.
The precision of the timing is 10 milli-seconds. If the code will execute
fast on this timescale, it can be executed many times to get reasonable
timing accuracy.
Parameters
----------
code_str : str
The code to be timed.
times : int, optional
The number of times the code is executed. Default is 1. The code is
only compiled once.
label : str, optional
A label to identify `code_str` with. This is passed into ``compile``
as the second argument (for run-time error messages).
Returns
-------
elapsed : float
Total elapsed time in seconds for executing `code_str` `times` times.
Examples
--------
>>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)',
... times=times)
>>> print("Time for a single execution : ", etime / times, "s")
Time for a single execution : 0.005 s
"""
frame = sys._getframe(1)
locs, globs = frame.f_locals, frame.f_globals
code = compile(code_str,
'Test name: %s ' % label,
'exec')
i = 0
elapsed = jiffies()
while i < times:
i += 1
exec(code, globs, locs)
elapsed = jiffies() - elapsed
return 0.01*elapsed
def _assert_valid_refcount(op):
"""
Check that ufuncs don't mishandle refcount of object `1`.
Used in a few regression tests.
"""
if not HAS_REFCOUNT:
return True
import numpy as np
b = np.arange(100*100).reshape(100, 100)
c = b
i = 1
rc = sys.getrefcount(i)
for j in range(15):
d = op(b, c)
assert_(sys.getrefcount(i) >= rc)
del d # for pyflakes
def assert_allclose(actual, desired, rtol=1e-7, atol=0, equal_nan=True,
err_msg='', verbose=True):
"""
Raises an AssertionError if two objects are not equal up to desired
tolerance.
The test is equivalent to ``allclose(actual, desired, rtol, atol)``.
It compares the difference between `actual` and `desired` to
``atol + rtol * abs(desired)``.
.. versionadded:: 1.5.0
Parameters
----------
actual : array_like
Array obtained.
desired : array_like
Array desired.
rtol : float, optional
Relative tolerance.
atol : float, optional
Absolute tolerance.
equal_nan : bool, optional.
If True, NaNs will compare equal.
err_msg : str, optional
The error message to be printed in case of failure.
verbose : bool, optional
If True, the conflicting values are appended to the error message.
Raises
------
AssertionError
If actual and desired are not equal up to specified precision.
See Also
--------
assert_array_almost_equal_nulp, assert_array_max_ulp
Examples
--------
>>> x = [1e-5, 1e-3, 1e-1]
>>> y = np.arccos(np.cos(x))
>>> assert_allclose(x, y, rtol=1e-5, atol=0)
"""
__tracebackhide__ = True # Hide traceback for py.test
import numpy as np
def compare(x, y):
return np.core.numeric.isclose(x, y, rtol=rtol, atol=atol,
equal_nan=equal_nan)
actual, desired = np.asanyarray(actual), np.asanyarray(desired)
header = 'Not equal to tolerance rtol=%g, atol=%g' % (rtol, atol)
assert_array_compare(compare, actual, desired, err_msg=str(err_msg),
verbose=verbose, header=header, equal_nan=equal_nan)
def assert_array_almost_equal_nulp(x, y, nulp=1):
"""
Compare two arrays relatively to their spacing.
This is a relatively robust method to compare two arrays whose amplitude
is variable.
Parameters
----------
x, y : array_like
Input arrays.
nulp : int, optional
The maximum number of unit in the last place for tolerance (see Notes).
Default is 1.
Returns
-------
None
Raises
------
AssertionError
If the spacing between `x` and `y` for one or more elements is larger
than `nulp`.
See Also
--------
assert_array_max_ulp : Check that all items of arrays differ in at most
N Units in the Last Place.
spacing : Return the distance between x and the nearest adjacent number.
Notes
-----
An assertion is raised if the following condition is not met::
abs(x - y) <= nulps * spacing(maximum(abs(x), abs(y)))
Examples
--------
>>> x = np.array([1., 1e-10, 1e-20])
>>> eps = np.finfo(x.dtype).eps
>>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x)
>>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x)
Traceback (most recent call last):
...
AssertionError: X and Y are not equal to 1 ULP (max is 2)
"""
__tracebackhide__ = True # Hide traceback for py.test
import numpy as np
ax = np.abs(x)
ay = np.abs(y)
ref = nulp * np.spacing(np.where(ax > ay, ax, ay))
if not np.all(np.abs(x-y) <= ref):
if np.iscomplexobj(x) or np.iscomplexobj(y):
msg = "X and Y are not equal to %d ULP" % nulp
else:
max_nulp = np.max(nulp_diff(x, y))
msg = "X and Y are not equal to %d ULP (max is %g)" % (nulp, max_nulp)
raise AssertionError(msg)
def assert_array_max_ulp(a, b, maxulp=1, dtype=None):
"""
Check that all items of arrays differ in at most N Units in the Last Place.
Parameters
----------
a, b : array_like
Input arrays to be compared.
maxulp : int, optional
The maximum number of units in the last place that elements of `a` and
`b` can differ. Default is 1.
dtype : dtype, optional
Data-type to convert `a` and `b` to if given. Default is None.
Returns
-------
ret : ndarray
Array containing number of representable floating point numbers between
items in `a` and `b`.
Raises
------
AssertionError
If one or more elements differ by more than `maxulp`.
See Also
--------
assert_array_almost_equal_nulp : Compare two arrays relatively to their
spacing.
Examples
--------
>>> a = np.linspace(0., 1., 100)
>>> res = np.testing.assert_array_max_ulp(a, np.arcsin(np.sin(a)))
"""
__tracebackhide__ = True # Hide traceback for py.test
import numpy as np
ret = nulp_diff(a, b, dtype)
if not np.all(ret <= maxulp):
raise AssertionError("Arrays are not almost equal up to %g ULP" %
maxulp)
return ret
def nulp_diff(x, y, dtype=None):
"""For each item in x and y, return the number of representable floating
points between them.
Parameters
----------
x : array_like
first input array
y : array_like
second input array
dtype : dtype, optional
Data-type to convert `x` and `y` to if given. Default is None.
Returns
-------
nulp : array_like
number of representable floating point numbers between each item in x
and y.
Examples
--------
# By definition, epsilon is the smallest number such as 1 + eps != 1, so
# there should be exactly one ULP between 1 and 1 + eps
>>> nulp_diff(1, 1 + np.finfo(x.dtype).eps)
1.0
"""
import numpy as np
if dtype:
x = np.array(x, dtype=dtype)
y = np.array(y, dtype=dtype)
else:
x = np.array(x)
y = np.array(y)
t = np.common_type(x, y)
if np.iscomplexobj(x) or np.iscomplexobj(y):
raise NotImplementedError("_nulp not implemented for complex array")
x = np.array(x, dtype=t)
y = np.array(y, dtype=t)
if not x.shape == y.shape:
raise ValueError("x and y do not have the same shape: %s - %s" %
(x.shape, y.shape))
def _diff(rx, ry, vdt):
diff = np.array(rx-ry, dtype=vdt)
return np.abs(diff)
rx = integer_repr(x)
ry = integer_repr(y)
return _diff(rx, ry, t)
def _integer_repr(x, vdt, comp):
# Reinterpret binary representation of the float as sign-magnitude:
# take into account two-complement representation
# See also
# http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
rx = x.view(vdt)
if not (rx.size == 1):
rx[rx < 0] = comp - rx[rx < 0]
else:
if rx < 0:
rx = comp - rx
return rx
def integer_repr(x):
"""Return the signed-magnitude interpretation of the binary representation of
x."""
import numpy as np
if x.dtype == np.float32:
return _integer_repr(x, np.int32, np.int32(-2**31))
elif x.dtype == np.float64:
return _integer_repr(x, np.int64, np.int64(-2**63))
else:
raise ValueError("Unsupported dtype %s" % x.dtype)
# The following two classes are copied from python 2.6 warnings module (context
# manager)
class WarningMessage(object):
"""
Holds the result of a single showwarning() call.
Deprecated in 1.8.0
Notes
-----
`WarningMessage` is copied from the Python 2.6 warnings module,
so it can be used in NumPy with older Python versions.
"""
_WARNING_DETAILS = ("message", "category", "filename", "lineno", "file",
"line")
def __init__(self, message, category, filename, lineno, file=None,
line=None):
local_values = locals()
for attr in self._WARNING_DETAILS:
setattr(self, attr, local_values[attr])
if category:
self._category_name = category.__name__
else:
self._category_name = None
def __str__(self):
return ("{message : %r, category : %r, filename : %r, lineno : %s, "
"line : %r}" % (self.message, self._category_name,
self.filename, self.lineno, self.line))
class WarningManager(object):
"""
A context manager that copies and restores the warnings filter upon
exiting the context.
The 'record' argument specifies whether warnings should be captured by a
custom implementation of ``warnings.showwarning()`` and be appended to a
list returned by the context manager. Otherwise None is returned by the
context manager. The objects appended to the list are arguments whose
attributes mirror the arguments to ``showwarning()``.
The 'module' argument is to specify an alternative module to the module
named 'warnings' and imported under that name. This argument is only useful
when testing the warnings module itself.
Deprecated in 1.8.0
Notes
-----
`WarningManager` is a copy of the ``catch_warnings`` context manager
from the Python 2.6 warnings module, with slight modifications.
It is copied so it can be used in NumPy with older Python versions.
"""
def __init__(self, record=False, module=None):
self._record = record
if module is None:
self._module = sys.modules['warnings']
else:
self._module = module
self._entered = False
def __enter__(self):
if self._entered:
raise RuntimeError("Cannot enter %r twice" % self)
self._entered = True
self._filters = self._module.filters
self._module.filters = self._filters[:]
self._showwarning = self._module.showwarning
if self._record:
log = []
def showwarning(*args, **kwargs):
log.append(WarningMessage(*args, **kwargs))
self._module.showwarning = showwarning
return log
else:
return None
def __exit__(self):
if not self._entered:
raise RuntimeError("Cannot exit %r without entering first" % self)
self._module.filters = self._filters
self._module.showwarning = self._showwarning
@contextlib.contextmanager
def _assert_warns_context(warning_class, name=None):
__tracebackhide__ = True # Hide traceback for py.test
with suppress_warnings() as sup:
l = sup.record(warning_class)
yield
if not len(l) > 0:
name_str = " when calling %s" % name if name is not None else ""
raise AssertionError("No warning raised" + name_str)
def assert_warns(warning_class, *args, **kwargs):
"""
Fail unless the given callable throws the specified warning.
A warning of class warning_class should be thrown by the callable when
invoked with arguments args and keyword arguments kwargs.
If a different type of warning is thrown, it will not be caught.
If called with all arguments other than the warning class omitted, may be
used as a context manager:
with assert_warns(SomeWarning):
do_something()
The ability to be used as a context manager is new in NumPy v1.11.0.
.. versionadded:: 1.4.0
Parameters
----------
warning_class : class
The class defining the warning that `func` is expected to throw.
func : callable
The callable to test.
\\*args : Arguments
Arguments passed to `func`.
\\*\\*kwargs : Kwargs
Keyword arguments passed to `func`.
Returns
-------
The value returned by `func`.
"""
if not args:
return _assert_warns_context(warning_class)
func = args[0]
args = args[1:]
with _assert_warns_context(warning_class, name=func.__name__):
return func(*args, **kwargs)
@contextlib.contextmanager
def _assert_no_warnings_context(name=None):
__tracebackhide__ = True # Hide traceback for py.test
with warnings.catch_warnings(record=True) as l:
warnings.simplefilter('always')
yield
if len(l) > 0:
name_str = " when calling %s" % name if name is not None else ""
raise AssertionError("Got warnings%s: %s" % (name_str, l))
def assert_no_warnings(*args, **kwargs):
"""
Fail if the given callable produces any warnings.
If called with all arguments omitted, may be used as a context manager:
with assert_no_warnings():
do_something()
The ability to be used as a context manager is new in NumPy v1.11.0.
.. versionadded:: 1.7.0
Parameters
----------
func : callable
The callable to test.
\\*args : Arguments
Arguments passed to `func`.
\\*\\*kwargs : Kwargs
Keyword arguments passed to `func`.
Returns
-------
The value returned by `func`.
"""
if not args:
return _assert_no_warnings_context()
func = args[0]
args = args[1:]
with _assert_no_warnings_context(name=func.__name__):
return func(*args, **kwargs)
def _gen_alignment_data(dtype=float32, type='binary', max_size=24):
"""
generator producing data with different alignment and offsets
to test simd vectorization
Parameters
----------
dtype : dtype
data type to produce
type : string
'unary': create data for unary operations, creates one input
and output array
'binary': create data for unary operations, creates two input
and output array
max_size : integer
maximum size of data to produce
Returns
-------
if type is 'unary' yields one output, one input array and a message
containing information on the data
if type is 'binary' yields one output array, two input array and a message
containing information on the data
"""
ufmt = 'unary offset=(%d, %d), size=%d, dtype=%r, %s'
bfmt = 'binary offset=(%d, %d, %d), size=%d, dtype=%r, %s'
for o in range(3):
for s in range(o + 2, max(o + 3, max_size)):
if type == 'unary':
inp = lambda: arange(s, dtype=dtype)[o:]
out = empty((s,), dtype=dtype)[o:]
yield out, inp(), ufmt % (o, o, s, dtype, 'out of place')
d = inp()
yield d, d, ufmt % (o, o, s, dtype, 'in place')
yield out[1:], inp()[:-1], ufmt % \
(o + 1, o, s - 1, dtype, 'out of place')
yield out[:-1], inp()[1:], ufmt % \
(o, o + 1, s - 1, dtype, 'out of place')
yield inp()[:-1], inp()[1:], ufmt % \
(o, o + 1, s - 1, dtype, 'aliased')
yield inp()[1:], inp()[:-1], ufmt % \
(o + 1, o, s - 1, dtype, 'aliased')
if type == 'binary':
inp1 = lambda: arange(s, dtype=dtype)[o:]
inp2 = lambda: arange(s, dtype=dtype)[o:]
out = empty((s,), dtype=dtype)[o:]
yield out, inp1(), inp2(), bfmt % \
(o, o, o, s, dtype, 'out of place')
d = inp1()
yield d, d, inp2(), bfmt % \
(o, o, o, s, dtype, 'in place1')
d = inp2()
yield d, inp1(), d, bfmt % \
(o, o, o, s, dtype, 'in place2')
yield out[1:], inp1()[:-1], inp2()[:-1], bfmt % \
(o + 1, o, o, s - 1, dtype, 'out of place')
yield out[:-1], inp1()[1:], inp2()[:-1], bfmt % \
(o, o + 1, o, s - 1, dtype, 'out of place')
yield out[:-1], inp1()[:-1], inp2()[1:], bfmt % \
(o, o, o + 1, s - 1, dtype, 'out of place')
yield inp1()[1:], inp1()[:-1], inp2()[:-1], bfmt % \
(o + 1, o, o, s - 1, dtype, 'aliased')
yield inp1()[:-1], inp1()[1:], inp2()[:-1], bfmt % \
(o, o + 1, o, s - 1, dtype, 'aliased')
yield inp1()[:-1], inp1()[:-1], inp2()[1:], bfmt % \
(o, o, o + 1, s - 1, dtype, 'aliased')
class IgnoreException(Exception):
"Ignoring this exception due to disabled feature"
@contextlib.contextmanager
def tempdir(*args, **kwargs):
"""Context manager to provide a temporary test folder.
All arguments are passed as this to the underlying tempfile.mkdtemp
function.
"""
tmpdir = mkdtemp(*args, **kwargs)
try:
yield tmpdir
finally:
shutil.rmtree(tmpdir)
@contextlib.contextmanager
def temppath(*args, **kwargs):
"""Context manager for temporary files.
Context manager that returns the path to a closed temporary file. Its
parameters are the same as for tempfile.mkstemp and are passed directly
to that function. The underlying file is removed when the context is
exited, so it should be closed at that time.
Windows does not allow a temporary file to be opened if it is already
open, so the underlying file must be closed after opening before it
can be opened again.
"""
fd, path = mkstemp(*args, **kwargs)
os.close(fd)
try:
yield path
finally:
os.remove(path)
class clear_and_catch_warnings(warnings.catch_warnings):
""" Context manager that resets warning registry for catching warnings
Warnings can be slippery, because, whenever a warning is triggered, Python
adds a ``__warningregistry__`` member to the *calling* module. This makes
it impossible to retrigger the warning in this module, whatever you put in
the warnings filters. This context manager accepts a sequence of `modules`
as a keyword argument to its constructor and:
* stores and removes any ``__warningregistry__`` entries in given `modules`
on entry;
* resets ``__warningregistry__`` to its previous state on exit.
This makes it possible to trigger any warning afresh inside the context
manager without disturbing the state of warnings outside.
For compatibility with Python 3.0, please consider all arguments to be
keyword-only.
Parameters
----------
record : bool, optional
Specifies whether warnings should be captured by a custom
implementation of ``warnings.showwarning()`` and be appended to a list
returned by the context manager. Otherwise None is returned by the
context manager. The objects appended to the list are arguments whose
attributes mirror the arguments to ``showwarning()``.
modules : sequence, optional
Sequence of modules for which to reset warnings registry on entry and
restore on exit. To work correctly, all 'ignore' filters should
filter by one of these modules.
Examples
--------
>>> import warnings
>>> with clear_and_catch_warnings(modules=[np.core.fromnumeric]):
... warnings.simplefilter('always')
... warnings.filterwarnings('ignore', module='np.core.fromnumeric')
... # do something that raises a warning but ignore those in
... # np.core.fromnumeric
"""
class_modules = ()
def __init__(self, record=False, modules=()):
self.modules = set(modules).union(self.class_modules)
self._warnreg_copies = {}
super(clear_and_catch_warnings, self).__init__(record=record)
def __enter__(self):
for mod in self.modules:
if hasattr(mod, '__warningregistry__'):
mod_reg = mod.__warningregistry__
self._warnreg_copies[mod] = mod_reg.copy()
mod_reg.clear()
return super(clear_and_catch_warnings, self).__enter__()
def __exit__(self, *exc_info):
super(clear_and_catch_warnings, self).__exit__(*exc_info)
for mod in self.modules:
if hasattr(mod, '__warningregistry__'):
mod.__warningregistry__.clear()
if mod in self._warnreg_copies:
mod.__warningregistry__.update(self._warnreg_copies[mod])
class suppress_warnings(object):
"""
Context manager and decorator doing much the same as
``warnings.catch_warnings``.
However, it also provides a filter mechanism to work around
http://bugs.python.org/issue4180.
This bug causes Python before 3.4 to not reliably show warnings again
after they have been ignored once (even within catch_warnings). It
means that no "ignore" filter can be used easily, since following
tests might need to see the warning. Additionally it allows easier
specificity for testing warnings and can be nested.
Parameters
----------
forwarding_rule : str, optional
One of "always", "once", "module", or "location". Analogous to
the usual warnings module filter mode, it is useful to reduce
noise mostly on the outmost level. Unsuppressed and unrecorded
warnings will be forwarded based on this rule. Defaults to "always".
"location" is equivalent to the warnings "default", match by exact
location the warning warning originated from.
Notes
-----
Filters added inside the context manager will be discarded again
when leaving it. Upon entering all filters defined outside a
context will be applied automatically.
When a recording filter is added, matching warnings are stored in the
``log`` attribute as well as in the list returned by ``record``.
If filters are added and the ``module`` keyword is given, the
warning registry of this module will additionally be cleared when
applying it, entering the context, or exiting it. This could cause
warnings to appear a second time after leaving the context if they
were configured to be printed once (default) and were already
printed before the context was entered.
Nesting this context manager will work as expected when the
forwarding rule is "always" (default). Unfiltered and unrecorded
warnings will be passed out and be matched by the outer level.
On the outmost level they will be printed (or caught by another
warnings context). The forwarding rule argument can modify this
behaviour.
Like ``catch_warnings`` this context manager is not threadsafe.
Examples
--------
>>> with suppress_warnings() as sup:
... sup.filter(DeprecationWarning, "Some text")
... sup.filter(module=np.ma.core)
... log = sup.record(FutureWarning, "Does this occur?")
... command_giving_warnings()
... # The FutureWarning was given once, the filtered warnings were
... # ignored. All other warnings abide outside settings (may be
... # printed/error)
... assert_(len(log) == 1)
... assert_(len(sup.log) == 1) # also stored in log attribute
Or as a decorator:
>>> sup = suppress_warnings()
>>> sup.filter(module=np.ma.core) # module must match exact
>>> @sup
>>> def some_function():
... # do something which causes a warning in np.ma.core
... pass
"""
def __init__(self, forwarding_rule="always"):
self._entered = False
# Suppressions are either instance or defined inside one with block:
self._suppressions = []
if forwarding_rule not in {"always", "module", "once", "location"}:
raise ValueError("unsupported forwarding rule.")
self._forwarding_rule = forwarding_rule
def _clear_registries(self):
if hasattr(warnings, "_filters_mutated"):
# clearing the registry should not be necessary on new pythons,
# instead the filters should be mutated.
warnings._filters_mutated()
return
# Simply clear the registry, this should normally be harmless,
# note that on new pythons it would be invalidated anyway.
for module in self._tmp_modules:
if hasattr(module, "__warningregistry__"):
module.__warningregistry__.clear()
def _filter(self, category=Warning, message="", module=None, record=False):
if record:
record = [] # The log where to store warnings
else:
record = None
if self._entered:
if module is None:
warnings.filterwarnings(
"always", category=category, message=message)
else:
module_regex = module.__name__.replace('.', '\.') + '$'
warnings.filterwarnings(
"always", category=category, message=message,
module=module_regex)
self._tmp_modules.add(module)
self._clear_registries()
self._tmp_suppressions.append(
(category, message, re.compile(message, re.I), module, record))
else:
self._suppressions.append(
(category, message, re.compile(message, re.I), module, record))
return record
def filter(self, category=Warning, message="", module=None):
"""
Add a new suppressing filter or apply it if the state is entered.
Parameters
----------
category : class, optional
Warning class to filter
message : string, optional
Regular expression matching the warning message.
module : module, optional
Module to filter for. Note that the module (and its file)
must match exactly and cannot be a submodule. This may make
it unreliable for external modules.
Notes
-----
When added within a context, filters are only added inside
the context and will be forgotten when the context is exited.
"""
self._filter(category=category, message=message, module=module,
record=False)
def record(self, category=Warning, message="", module=None):
"""
Append a new recording filter or apply it if the state is entered.
All warnings matching will be appended to the ``log`` attribute.
Parameters
----------
category : class, optional
Warning class to filter
message : string, optional
Regular expression matching the warning message.
module : module, optional
Module to filter for. Note that the module (and its file)
must match exactly and cannot be a submodule. This may make
it unreliable for external modules.
Returns
-------
log : list
A list which will be filled with all matched warnings.
Notes
-----
When added within a context, filters are only added inside
the context and will be forgotten when the context is exited.
"""
return self._filter(category=category, message=message, module=module,
record=True)
def __enter__(self):
if self._entered:
raise RuntimeError("cannot enter suppress_warnings twice.")
self._orig_show = warnings.showwarning
if hasattr(warnings, "_showwarnmsg"):
self._orig_showmsg = warnings._showwarnmsg
self._filters = warnings.filters
warnings.filters = self._filters[:]
self._entered = True
self._tmp_suppressions = []
self._tmp_modules = set()
self._forwarded = set()
self.log = [] # reset global log (no need to keep same list)
for cat, mess, _, mod, log in self._suppressions:
if log is not None:
del log[:] # clear the log
if mod is None:
warnings.filterwarnings(
"always", category=cat, message=mess)
else:
module_regex = mod.__name__.replace('.', '\.') + '$'
warnings.filterwarnings(
"always", category=cat, message=mess,
module=module_regex)
self._tmp_modules.add(mod)
warnings.showwarning = self._showwarning
if hasattr(warnings, "_showwarnmsg"):
warnings._showwarnmsg = self._showwarnmsg
self._clear_registries()
return self
def __exit__(self, *exc_info):
warnings.showwarning = self._orig_show
if hasattr(warnings, "_showwarnmsg"):
warnings._showwarnmsg = self._orig_showmsg
warnings.filters = self._filters
self._clear_registries()
self._entered = False
del self._orig_show
del self._filters
def _showwarnmsg(self, msg):
self._showwarning(msg.message, msg.category, msg.filename, msg.lineno,
msg.file, msg.line, use_warnmsg=msg)
def _showwarning(self, message, category, filename, lineno,
*args, **kwargs):
use_warnmsg = kwargs.pop("use_warnmsg", None)
for cat, _, pattern, mod, rec in (
self._suppressions + self._tmp_suppressions)[::-1]:
if (issubclass(category, cat) and
pattern.match(message.args[0]) is not None):
if mod is None:
# Message and category match, either recorded or ignored
if rec is not None:
msg = WarningMessage(message, category, filename,
lineno, **kwargs)
self.log.append(msg)
rec.append(msg)
return
# Use startswith, because warnings strips the c or o from
# .pyc/.pyo files.
elif mod.__file__.startswith(filename):
# The message and module (filename) match
if rec is not None:
msg = WarningMessage(message, category, filename,
lineno, **kwargs)
self.log.append(msg)
rec.append(msg)
return
# There is no filter in place, so pass to the outside handler
# unless we should only pass it once
if self._forwarding_rule == "always":
if use_warnmsg is None:
self._orig_show(message, category, filename, lineno,
*args, **kwargs)
else:
self._orig_showmsg(use_warnmsg)
return
if self._forwarding_rule == "once":
signature = (message.args, category)
elif self._forwarding_rule == "module":
signature = (message.args, category, filename)
elif self._forwarding_rule == "location":
signature = (message.args, category, filename, lineno)
if signature in self._forwarded:
return
self._forwarded.add(signature)
if use_warnmsg is None:
self._orig_show(message, category, filename, lineno, *args,
**kwargs)
else:
self._orig_showmsg(use_warnmsg)
def __call__(self, func):
"""
Function decorator to apply certain suppressions to a whole
function.
"""
@wraps(func)
def new_func(*args, **kwargs):
with self:
return func(*args, **kwargs)
return new_func
| bsd-3-clause |
michaelrice/yavijava | src/main/java/com/vmware/vim25/HostVFlashManagerVFlashCacheConfigSpec.java | 2401 | /*================================================================================
Copyright (c) 2013 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class HostVFlashManagerVFlashCacheConfigSpec extends DynamicData {
public String defaultVFlashModule;
public long swapCacheReservationInGB;
public String getDefaultVFlashModule() {
return this.defaultVFlashModule;
}
public long getSwapCacheReservationInGB() {
return this.swapCacheReservationInGB;
}
public void setDefaultVFlashModule(String defaultVFlashModule) {
this.defaultVFlashModule = defaultVFlashModule;
}
public void setSwapCacheReservationInGB(long swapCacheReservationInGB) {
this.swapCacheReservationInGB = swapCacheReservationInGB;
}
} | bsd-3-clause |
jsqu99/alchemy_cms | spec/libraries/permissions_spec.rb | 9516 | require 'spec_helper'
require 'cancan/matchers'
describe Alchemy::Permissions do
subject { ability }
let(:ability) { Alchemy::Permissions.new(user) }
let(:attachment) { mock_model(Alchemy::Attachment, restricted?: false) }
let(:restricted_attachment) { mock_model(Alchemy::Attachment, restricted?: true) }
let(:picture) { mock_model(Alchemy::Picture, restricted?: false) }
let(:restricted_picture) { mock_model(Alchemy::Picture, restricted?: true) }
let(:public_page) { build_stubbed(:public_page, restricted: false) }
let(:unpublic_page) { build_stubbed(:page, public: false) }
let(:visible_page) { build_stubbed(:page, restricted: false, visible: true) }
let(:not_visible_page) { build_stubbed(:public_page, restricted: false, visible: false) }
let(:restricted_page) { build_stubbed(:public_page, public: true, restricted: true) }
let(:visible_restricted_page) { build_stubbed(:page, visible: true, restricted: true) }
let(:published_element) { mock_model(Alchemy::Element, restricted?: false, public?: true, trashed?: false) }
let(:restricted_element) { mock_model(Alchemy::Element, restricted?: true, public?: true, trashed?: false) }
let(:published_content) { mock_model(Alchemy::Content, restricted?: false, public?: true, trashed?: false) }
let(:restricted_content) { mock_model(Alchemy::Content, restricted?: true, public?: true, trashed?: false) }
context "A guest user" do
let(:user) { nil }
it "can only download not restricted attachments" do
is_expected.to be_able_to(:download, attachment)
is_expected.not_to be_able_to(:download, restricted_attachment)
end
it "can only see not restricted attachments" do
is_expected.to be_able_to(:show, attachment)
is_expected.not_to be_able_to(:show, restricted_attachment)
end
it "can only see not restricted pictures" do
is_expected.to be_able_to(:show, picture)
is_expected.to be_able_to(:thumbnail, picture)
is_expected.to be_able_to(:zoom, picture)
is_expected.not_to be_able_to(:show, restricted_picture)
is_expected.not_to be_able_to(:thumbnail, restricted_picture)
is_expected.not_to be_able_to(:zoom, restricted_picture)
end
it "can only visit not restricted pages" do
is_expected.to be_able_to(:show, public_page)
is_expected.not_to be_able_to(:show, restricted_page)
is_expected.to be_able_to(:index, public_page)
is_expected.not_to be_able_to(:index, restricted_page)
end
it "can only see visible not restricted pages" do
is_expected.to be_able_to(:see, visible_page)
is_expected.not_to be_able_to(:see, not_visible_page)
end
it "can only see public not restricted elements" do
is_expected.to be_able_to(:show, published_element)
is_expected.not_to be_able_to(:show, restricted_element)
is_expected.to be_able_to(:index, published_element)
is_expected.not_to be_able_to(:index, restricted_element)
end
it "can only see public not restricted contents" do
is_expected.to be_able_to(:show, published_content)
is_expected.not_to be_able_to(:show, restricted_content)
is_expected.to be_able_to(:index, published_content)
is_expected.not_to be_able_to(:index, restricted_content)
end
end
context "A member" do
let(:user) { build(:alchemy_dummy_user) }
it "can download all attachments" do
is_expected.to be_able_to(:download, attachment)
is_expected.to be_able_to(:download, restricted_attachment)
end
it "can see all attachments" do
is_expected.to be_able_to(:show, attachment)
is_expected.to be_able_to(:show, restricted_attachment)
end
it "can see all pictures" do
is_expected.to be_able_to(:show, picture)
is_expected.to be_able_to(:thumbnail, picture)
is_expected.to be_able_to(:zoom, picture)
is_expected.to be_able_to(:show, restricted_picture)
is_expected.to be_able_to(:thumbnail, restricted_picture)
is_expected.to be_able_to(:zoom, restricted_picture)
end
it "can visit restricted pages" do
is_expected.to be_able_to(:show, public_page)
is_expected.to be_able_to(:show, restricted_page)
is_expected.to be_able_to(:index, public_page)
is_expected.to be_able_to(:index, restricted_page)
end
it "can see visible restricted pages" do
is_expected.to be_able_to(:see, visible_page)
is_expected.to be_able_to(:see, visible_restricted_page)
end
it "can not see invisible pages" do
is_expected.not_to be_able_to(:see, not_visible_page)
end
it "can see public restricted elements" do
is_expected.to be_able_to(:show, published_element)
is_expected.to be_able_to(:show, restricted_element)
is_expected.to be_able_to(:index, published_element)
is_expected.to be_able_to(:index, restricted_element)
end
it "can see public restricted contents" do
is_expected.to be_able_to(:show, published_content)
is_expected.to be_able_to(:show, restricted_content)
is_expected.to be_able_to(:index, published_content)
is_expected.to be_able_to(:index, restricted_content)
end
end
context "An author" do
let(:user) { build(:alchemy_dummy_user, :as_author) }
it "can leave the admin area" do
is_expected.to be_able_to(:leave, :alchemy_admin)
end
it "can visit the dashboard" do
is_expected.to be_able_to(:index, :alchemy_admin_dashboard)
is_expected.to be_able_to(:info, :alchemy_admin_dashboard)
end
it "can see picture thumbnails" do
is_expected.to be_able_to(:thumbnail, Alchemy::Picture)
end
it "can edit page content" do
is_expected.to be_able_to(:show, unpublic_page)
is_expected.to be_able_to(:index, Alchemy::Page)
is_expected.to be_able_to(:info, Alchemy::Page)
is_expected.to be_able_to(:configure, Alchemy::Page)
is_expected.to be_able_to(:update, Alchemy::Page)
is_expected.to be_able_to(:fold, Alchemy::Page)
is_expected.to be_able_to(:link, Alchemy::Page)
is_expected.to be_able_to(:visit, Alchemy::Page)
is_expected.to be_able_to(:unlock, Alchemy::Page)
end
it "can not publish pages" do
is_expected.to_not be_able_to(:publish, Alchemy::Page)
end
it "can manage elements" do
is_expected.to be_able_to(:manage, Alchemy::Element)
end
it "can see all attachments" do
is_expected.to be_able_to(:read, Alchemy::Attachment)
is_expected.to be_able_to(:download, Alchemy::Attachment)
end
it "can see all pictures" do
is_expected.to be_able_to(:read, Alchemy::Picture)
is_expected.to be_able_to(:info, Alchemy::Picture)
end
it "can manage contents" do
is_expected.to be_able_to(:manage, Alchemy::Content)
end
it "can manage essences" do
is_expected.to be_able_to(:manage, Alchemy::EssencePicture)
is_expected.to be_able_to(:manage, Alchemy::EssenceFile)
end
it "can see the trash" do
is_expected.to be_able_to(:index, :trash)
end
it "can manage the clipboard" do
is_expected.to be_able_to(:manage, :alchemy_admin_clipboard)
end
it "can see tags" do
is_expected.to be_able_to(:read, Alchemy::Tag)
is_expected.to be_able_to(:autocomplete, Alchemy::Tag)
end
it "can index layoutpages" do
is_expected.to be_able_to(:index, :alchemy_admin_layoutpages)
end
end
context "An editor" do
let(:user) { build(:alchemy_dummy_user, :as_editor) }
it "can manage pages" do
is_expected.to be_able_to(:copy, Alchemy::Page)
is_expected.to be_able_to(:copy_language_tree, Alchemy::Page)
is_expected.to be_able_to(:create, Alchemy::Page)
is_expected.to be_able_to(:destroy, Alchemy::Page)
is_expected.to be_able_to(:flush, Alchemy::Page)
is_expected.to be_able_to(:order, Alchemy::Page)
is_expected.to be_able_to(:sort, Alchemy::Page)
is_expected.to be_able_to(:switch_language, Alchemy::Page)
end
it "can publish pages" do
is_expected.to be_able_to(:publish, Alchemy::Page)
end
it "can not see invisible pages" do
is_expected.not_to be_able_to(:see, not_visible_page)
end
it "can clear the trash" do
is_expected.to be_able_to(:clear, :trash)
end
it "can manage attachments" do
is_expected.to be_able_to(:manage, Alchemy::Attachment)
end
it "can manage pictures" do
is_expected.to be_able_to(:manage, Alchemy::Picture)
end
it "can manage tags" do
is_expected.to be_able_to(:manage, Alchemy::Tag)
end
end
context "An admin" do
let(:user) { build(:alchemy_dummy_user, :as_admin) }
it "can check for alchemy updates" do
is_expected.to be_able_to(:update_check, :alchemy_admin_dashboard)
end
it "can manage languages" do
is_expected.to be_able_to(:manage, Alchemy::Language)
end
it "can manage sites" do
is_expected.to be_able_to(:manage, Alchemy::Site)
end
end
context "A logged in user without a role" do
let(:user) { mock_model(Alchemy.user_class, alchemy_roles: []) }
it "can only see visible not restricted pages (like the guest role)" do
is_expected.to be_able_to(:see, visible_page)
is_expected.not_to be_able_to(:see, not_visible_page)
end
end
end
| bsd-3-clause |
chromium/chromium | ash/quick_pair/repository/fast_pair/device_metadata_fetcher.cc | 4157 | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/quick_pair/repository/fast_pair/device_metadata_fetcher.h"
#include "ash/quick_pair/common/fast_pair/fast_pair_http_result.h"
#include "ash/quick_pair/common/fast_pair/fast_pair_metrics.h"
#include "ash/quick_pair/common/logging.h"
#include "ash/quick_pair/proto/fastpair.pb.h"
#include "ash/quick_pair/repository/unauthenticated_http_fetcher.h"
#include "base/base64.h"
#include "base/strings/stringprintf.h"
#include "google_apis/google_api_keys.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "url/gurl.h"
namespace {
const char kGetObservedDeviceUrl[] =
"https://nearbydevices-pa.googleapis.com/v1/device/"
"%d?key=%s&mode=MODE_RELEASE&alt=proto";
const net::NetworkTrafficAnnotationTag kTrafficAnnotation =
net::DefineNetworkTrafficAnnotation("fast_pair_device_metadata_fetcher", R"(
semantics {
sender: "Fast Pair repository access"
description:
"Retrieves details about bluetooth devices that have been "
"discovered in range."
trigger: "Eligible bluetooth device is in range."
data:
"Details about a bluetooth peripheral, including name and picture."
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: NO
setting:
"You can enable or disable this feature by toggling on/off the "
"Fast Pair toggle in chrome://os-settings under 'Bluetooth'. The "
"feature is enabled by default. "
chrome_policy {
FastPairEnabled {
FastPairEnabled: true
}
}
})");
} // namespace
namespace ash {
namespace quick_pair {
DeviceMetadataFetcher::DeviceMetadataFetcher()
: http_fetcher_(
std::make_unique<UnauthenticatedHttpFetcher>(kTrafficAnnotation)) {}
DeviceMetadataFetcher::DeviceMetadataFetcher(
std::unique_ptr<HttpFetcher> http_fetcher)
: http_fetcher_(std::move(http_fetcher)) {}
DeviceMetadataFetcher::~DeviceMetadataFetcher() = default;
void DeviceMetadataFetcher::LookupDeviceId(int id,
GetObservedDeviceCallback callback) {
GURL url = GURL(base::StringPrintf(kGetObservedDeviceUrl, id,
google_apis::GetAPIKey().c_str()));
http_fetcher_->ExecuteGetRequest(
url, base::BindOnce(&DeviceMetadataFetcher::OnFetchComplete,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void DeviceMetadataFetcher::LookupHexDeviceId(
const std::string& hex_id,
GetObservedDeviceCallback callback) {
int id = std::strtol(hex_id.c_str(), nullptr, 16);
LookupDeviceId(id, std::move(callback));
}
void DeviceMetadataFetcher::OnFetchComplete(
GetObservedDeviceCallback callback,
std::unique_ptr<std::string> response_body,
std::unique_ptr<FastPairHttpResult> http_result) {
QP_LOG(VERBOSE) << __func__ << ": HTTP result: "
<< (http_result ? http_result->ToString() : "[null]");
if (!http_result) {
QP_LOG(WARNING) << __func__ << "Unable to make request.";
std::move(callback).Run(absl::nullopt, /*has_retryable_error=*/true);
return;
}
RecordDeviceMetadataFetchResult(*http_result);
if (!response_body) {
QP_LOG(WARNING) << "No response.";
// Only suggest retrying when the actual request failed, otherwise there is
// no matching metadata for the given model_id.
std::move(callback).Run(absl::nullopt,
/*has_retryable_error=*/!http_result->IsSuccess());
return;
}
nearby::fastpair::GetObservedDeviceResponse device_metadata;
if (!device_metadata.ParseFromString(*response_body)) {
QP_LOG(WARNING) << "Failed to parse.";
std::move(callback).Run(absl::nullopt, /*has_retryable_error=*/true);
return;
}
std::move(callback).Run(device_metadata, /*has_retryable_error=*/false);
}
} // namespace quick_pair
} // namespace ash
| bsd-3-clause |
rodrigoramosrx2/phalcon-devtools | ide/stubs/Phalcon/validation/ValidatorInterface.php | 804 | <?php
namespace Phalcon\Validation;
/**
* Phalcon\Validation\ValidatorInterface
*
* Interface for Phalcon\Validation\Validator
*/
interface ValidatorInterface
{
/**
* Checks if an option is defined
*
* @param string $key
* @return bool
*/
public function hasOption($key);
/**
* Returns an option in the validator's options
* Returns null if the option hasn't set
*
* @param string $key
* @param mixed $defaultValue
* @return mixed
*/
public function getOption($key, $defaultValue = null);
/**
* Executes the validation
*
* @param \Phalcon\Validation $validation
* @param string $attribute
* @return bool
*/
public function validate(\Phalcon\Validation $validation, $attribute);
}
| bsd-3-clause |
chromium/chromium | ash/webui/eche_app_ui/eche_app_manager.cc | 6012 | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/webui/eche_app_ui/eche_app_manager.h"
#include "ash/components/phonehub/phone_hub_manager.h"
#include "ash/public/cpp/network_config_service.h"
#include "ash/services/secure_channel/public/cpp/client/connection_manager_impl.h"
#include "ash/webui/eche_app_ui/apps_access_manager_impl.h"
#include "ash/webui/eche_app_ui/eche_connector_impl.h"
#include "ash/webui/eche_app_ui/eche_message_receiver_impl.h"
#include "ash/webui/eche_app_ui/eche_notification_generator.h"
#include "ash/webui/eche_app_ui/eche_presence_manager.h"
#include "ash/webui/eche_app_ui/eche_signaler.h"
#include "ash/webui/eche_app_ui/eche_uid_provider.h"
#include "ash/webui/eche_app_ui/launch_app_helper.h"
#include "ash/webui/eche_app_ui/system_info.h"
#include "ash/webui/eche_app_ui/system_info_provider.h"
#include "base/system/sys_info.h"
namespace ash {
namespace {
const char kSecureChannelFeatureName[] = "eche";
const char kMetricNameResult[] = "Eche.Connection.Result";
const char kMetricNameDuration[] = "Eche.Connection.Duration";
const char kMetricNameLatency[] = "Eche.Connectivity.Latency";
} // namespace
namespace eche_app {
EcheAppManager::EcheAppManager(
PrefService* pref_service,
std::unique_ptr<SystemInfo> system_info,
phonehub::PhoneHubManager* phone_hub_manager,
device_sync::DeviceSyncClient* device_sync_client,
multidevice_setup::MultiDeviceSetupClient* multidevice_setup_client,
secure_channel::SecureChannelClient* secure_channel_client,
std::unique_ptr<secure_channel::PresenceMonitorClient>
presence_monitor_client,
LaunchAppHelper::LaunchEcheAppFunction launch_eche_app_function,
LaunchAppHelper::CloseEcheAppFunction close_eche_app_function,
LaunchAppHelper::LaunchNotificationFunction launch_notification_function)
: connection_manager_(
std::make_unique<secure_channel::ConnectionManagerImpl>(
multidevice_setup_client,
device_sync_client,
secure_channel_client,
kSecureChannelFeatureName,
kMetricNameResult,
kMetricNameLatency,
kMetricNameDuration)),
feature_status_provider_(std::make_unique<EcheFeatureStatusProvider>(
phone_hub_manager,
device_sync_client,
multidevice_setup_client,
connection_manager_.get())),
launch_app_helper_(
std::make_unique<LaunchAppHelper>(phone_hub_manager,
launch_eche_app_function,
close_eche_app_function,
launch_notification_function)),
eche_notification_click_handler_(
std::make_unique<EcheNotificationClickHandler>(
phone_hub_manager,
feature_status_provider_.get(),
launch_app_helper_.get())),
eche_connector_(
std::make_unique<EcheConnectorImpl>(feature_status_provider_.get(),
connection_manager_.get())),
signaler_(std::make_unique<EcheSignaler>(eche_connector_.get(),
connection_manager_.get())),
message_receiver_(
std::make_unique<EcheMessageReceiverImpl>(connection_manager_.get())),
eche_presence_manager_(std::make_unique<EchePresenceManager>(
feature_status_provider_.get(),
device_sync_client,
multidevice_setup_client,
std::move(presence_monitor_client),
eche_connector_.get(),
message_receiver_.get())),
uid_(std::make_unique<EcheUidProvider>(pref_service)),
eche_recent_app_click_handler_(
std::make_unique<EcheRecentAppClickHandler>(
phone_hub_manager,
feature_status_provider_.get(),
launch_app_helper_.get())),
notification_generator_(std::make_unique<EcheNotificationGenerator>(
launch_app_helper_.get())),
apps_access_manager_(std::make_unique<AppsAccessManagerImpl>(
eche_connector_.get(),
message_receiver_.get(),
feature_status_provider_.get(),
pref_service)) {
ash::GetNetworkConfigService(
remote_cros_network_config_.BindNewPipeAndPassReceiver());
system_info_provider_ = std::make_unique<SystemInfoProvider>(
std::move(system_info), remote_cros_network_config_.get());
}
EcheAppManager::~EcheAppManager() = default;
void EcheAppManager::BindSignalingMessageExchangerInterface(
mojo::PendingReceiver<mojom::SignalingMessageExchanger> receiver) {
signaler_->Bind(std::move(receiver));
}
void EcheAppManager::BindSystemInfoProviderInterface(
mojo::PendingReceiver<mojom::SystemInfoProvider> receiver) {
system_info_provider_->Bind(std::move(receiver));
}
void EcheAppManager::BindUidGeneratorInterface(
mojo::PendingReceiver<mojom::UidGenerator> receiver) {
uid_->Bind(std::move(receiver));
}
void EcheAppManager::BindNotificationGeneratorInterface(
mojo::PendingReceiver<mojom::NotificationGenerator> receiver) {
notification_generator_->Bind(std::move(receiver));
}
AppsAccessManager* EcheAppManager::GetAppsAccessManager() {
return apps_access_manager_.get();
}
// NOTE: These should be destroyed in the opposite order of how these objects
// are initialized in the constructor.
void EcheAppManager::Shutdown() {
system_info_provider_.reset();
apps_access_manager_.reset();
notification_generator_.reset();
eche_recent_app_click_handler_.reset();
uid_.reset();
eche_presence_manager_.reset();
message_receiver_.reset();
signaler_.reset();
eche_connector_.reset();
eche_notification_click_handler_.reset();
launch_app_helper_.reset();
feature_status_provider_.reset();
connection_manager_.reset();
}
} // namespace eche_app
} // namespace ash
| bsd-3-clause |
golang/leveldb | version_edit_test.go | 4894 | // Copyright 2012 The LevelDB-Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package leveldb
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"reflect"
"testing"
"github.com/golang/leveldb/record"
)
func checkRoundTrip(e0 versionEdit) error {
var e1 versionEdit
buf := new(bytes.Buffer)
if err := e0.encode(buf); err != nil {
return fmt.Errorf("encode: %v", err)
}
if err := e1.decode(buf); err != nil {
return fmt.Errorf("decode: %v", err)
}
if !reflect.DeepEqual(e1, e0) {
return fmt.Errorf("\n\tgot %#v\n\twant %#v", e1, e0)
}
return nil
}
func TestVersionEditRoundTrip(t *testing.T) {
testCases := []versionEdit{
// An empty version edit.
{},
// A complete version edit.
{
comparatorName: "11",
logNumber: 22,
prevLogNumber: 33,
nextFileNumber: 44,
lastSequence: 55,
compactPointers: []compactPointerEntry{
{
level: 0,
key: internalKey("600"),
},
{
level: 1,
key: internalKey("601"),
},
{
level: 2,
key: internalKey("602"),
},
},
deletedFiles: map[deletedFileEntry]bool{
deletedFileEntry{
level: 3,
fileNum: 703,
}: true,
deletedFileEntry{
level: 4,
fileNum: 704,
}: true,
},
newFiles: []newFileEntry{
{
level: 5,
meta: fileMetadata{
fileNum: 805,
size: 8050,
smallest: internalKey("abc\x00\x01\x02\x03\x04\x05\x06\x07"),
largest: internalKey("xyz\x01\xff\xfe\xfd\xfc\xfb\xfa\xf9"),
},
},
{
level: 6,
meta: fileMetadata{
fileNum: 806,
size: 8060,
smallest: internalKey("A\x00\x01\x02\x03\x04\x05\x06\x07"),
largest: internalKey("Z\x01\xff\xfe\xfd\xfc\xfb\xfa\xf9"),
},
},
},
},
}
for _, tc := range testCases {
if err := checkRoundTrip(tc); err != nil {
t.Error(err)
}
}
}
func TestVersionEditDecode(t *testing.T) {
testCases := []struct {
filename string
encodedEdits []string
edits []versionEdit
}{
// db-stage-1 and db-stage-2 have the same manifest.
{
filename: "db-stage-1/MANIFEST-000002",
encodedEdits: []string{
"\x01\x1aleveldb.BytewiseComparator",
"\x02\x03\x09\x00\x03\x04\x04\x00",
},
edits: []versionEdit{
{
comparatorName: "leveldb.BytewiseComparator",
},
{
logNumber: 3,
prevLogNumber: 0,
nextFileNumber: 4,
lastSequence: 0,
},
},
},
// db-stage-3 and db-stage-4 have the same manifest.
{
filename: "db-stage-3/MANIFEST-000004",
encodedEdits: []string{
"\x01\x1aleveldb.BytewiseComparator",
"\x02\x06\x09\x00\x03\x07\x04\x05\x07\x00\x05\xa5\x01" +
"\x0bbar\x00\x05\x00\x00\x00\x00\x00\x00" +
"\x0bfoo\x01\x01\x00\x00\x00\x00\x00\x00",
},
edits: []versionEdit{
{
comparatorName: "leveldb.BytewiseComparator",
},
{
logNumber: 6,
prevLogNumber: 0,
nextFileNumber: 7,
lastSequence: 5,
newFiles: []newFileEntry{
{
level: 0,
meta: fileMetadata{
fileNum: 5,
size: 165,
smallest: internalKey("bar\x00\x05\x00\x00\x00\x00\x00\x00"),
largest: internalKey("foo\x01\x01\x00\x00\x00\x00\x00\x00"),
},
},
},
},
},
},
}
loop:
for _, tc := range testCases {
f, err := os.Open("testdata/" + tc.filename)
if err != nil {
t.Errorf("filename=%q: open error: %v", tc.filename, err)
continue
}
defer f.Close()
i, r := 0, record.NewReader(f)
for {
rr, err := r.Next()
if err == io.EOF {
break
}
if err != nil {
t.Errorf("filename=%q i=%d: record reader error: %v", tc.filename, i, err)
continue loop
}
if i >= len(tc.edits) {
t.Errorf("filename=%q i=%d: too many version edits", tc.filename, i+1)
continue loop
}
encodedEdit, err := ioutil.ReadAll(rr)
if err != nil {
t.Errorf("filename=%q i=%d: read error: %v", tc.filename, i, err)
continue loop
}
if s := string(encodedEdit); s != tc.encodedEdits[i] {
t.Errorf("filename=%q i=%d: got encoded %q, want %q", tc.filename, i, s, tc.encodedEdits[i])
continue loop
}
var edit versionEdit
err = edit.decode(bytes.NewReader(encodedEdit))
if err != nil {
t.Errorf("filename=%q i=%d: decode error: %v", tc.filename, i, err)
continue loop
}
if !reflect.DeepEqual(edit, tc.edits[i]) {
t.Errorf("filename=%q i=%d: decode\n\tgot %#v\n\twant %#v", tc.filename, i, edit, tc.edits[i])
continue loop
}
if err := checkRoundTrip(edit); err != nil {
t.Errorf("filename=%q i=%d: round trip: %v", tc.filename, i, err)
continue loop
}
i++
}
if i != len(tc.edits) {
t.Errorf("filename=%q: got %d edits, want %d", tc.filename, i, len(tc.edits))
continue
}
}
}
| bsd-3-clause |
dtrotzjr/elsa-and-friends | elsa/stdconv.cc | 36074 | // stdconv.cc see license.txt for copyright and terms of use
// code for stdconv.h
#include "stdconv.h" // this module
#include "cc_type.h" // Type
#include "cc_env.h" // Env
#include "trace.h" // tracingSys
/*
* 2005-04-03: ARR_QUAL_CONV:
*
* It is possible to convert (say)
*
* pointer to array of int
*
* to
*
* pointer to array of const int
*
* because 3.9.3p5 apparently intends cv qualifiers on arrays and
* array elements to be interchangeable with respect to standard
* conversions. See this post:
*
* http://groups-beta.google.com/group/comp.std.c++/msg/1396c9ff05f4e86f?dmode=source
*
* So the strategy in this module (marked with "ARR_QUAL_CONV")
* is to "pull" qualifiers on array elements up to the level of
* the (outermost) ArrayType, as if they were attached to that
* object (only). This is done primarily by 'getSrcCVFlags'.
*/
// ----------------------- StandardConversion -------------------
string toString(StandardConversion c)
{
stringBuilder sb;
if (c == SC_ERROR) {
return string("SC_ERROR");
}
if (c == SC_IDENTITY) {
return string("SC_IDENTITY");
}
#define CASE(label) \
case label: \
if (sb.length()) { sb << "|"; } \
sb << #label; \
break;
switch (c & SC_GROUP_1_MASK) {
default: return stringc << "bad code: " << (int)c;
case SC_IDENTITY: break;
CASE(SC_LVAL_TO_RVAL)
CASE(SC_ARRAY_TO_PTR)
CASE(SC_FUNC_TO_PTR)
}
switch (c & SC_GROUP_3_MASK) {
default: return stringc << "bad code: " << (int)c;
case SC_IDENTITY: break;
CASE(SC_QUAL_CONV)
}
switch (c & SC_GROUP_2_MASK) {
default: return stringc << "bad code: " << (int)c;
case SC_IDENTITY: break;
CASE(SC_INT_PROM)
CASE(SC_FLOAT_PROM)
CASE(SC_INT_CONV)
CASE(SC_FLOAT_CONV)
CASE(SC_FLOAT_INT_CONV)
CASE(SC_PTR_CONV)
CASE(SC_PTR_MEMB_CONV)
CASE(SC_BOOL_CONV)
}
#undef CASE
if (c & ~(SC_GROUP_1_MASK | SC_GROUP_2_MASK | SC_GROUP_3_MASK)) {
return stringc << "bad code: " << (int)c;
}
return sb;
}
StandardConversion removeLval(StandardConversion scs)
{
if ((scs & SC_GROUP_1_MASK) == SC_LVAL_TO_RVAL) {
// remove this transformation
return scs & (SC_GROUP_2_MASK | SC_GROUP_3_MASK);
}
else {
return scs;
}
}
bool isSubsequenceOf(StandardConversion left, StandardConversion right)
{
StandardConversion L, R;
L = left & SC_GROUP_1_MASK;
R = right & SC_GROUP_1_MASK;
if (!( L == SC_IDENTITY || L == R )) {
return false;
}
L = left & SC_GROUP_2_MASK;
R = right & SC_GROUP_2_MASK;
if (!( L == SC_IDENTITY || L == R )) {
return false;
}
L = left & SC_GROUP_3_MASK;
R = right & SC_GROUP_3_MASK;
if (!( L == SC_IDENTITY || L == R )) {
return false;
}
return true;
}
// ---------------------------- SCRank ----------------------------
// table 9
SCRank getRank(StandardConversion scs)
{
if ((scs & SC_GROUP_2_MASK) >= SC_INT_CONV) {
return SCR_CONVERSION;
}
if (scs & SC_GROUP_2_MASK) {
return SCR_PROMOTION;
}
return SCR_EXACT;
}
// --------------------- getStandardConversion --------------------
bool isIntegerPromotion(AtomicType const *src, AtomicType const *dest);
// int (including bitfield), bool, or enum
bool isIntegerNumeric(Type const *t, SimpleType const *tSimple)
{
if (tSimple) {
return isIntegerType(tSimple->type) ||
tSimple->type == ST_BOOL ||
tSimple->type == ST_PROMOTED_INTEGRAL;
}
// TODO: bitfields are also a valid integer conversion source,
// once I have an explicit representation for them
return t->isEnumType();
}
// any of above, or float
bool isNumeric(Type const *t, SimpleType const *tSimple)
{
return isIntegerNumeric(t, tSimple) ||
(tSimple && isFloatType(tSimple->type)) ||
(tSimple && tSimple->type == ST_PROMOTED_ARITHMETIC);
}
#if 0 // unused, but potentially useful at some point
static char const *atomicName(AtomicType::Tag tag)
{
switch (tag) {
default: xfailure("bad tag");
case AtomicType::T_SIMPLE: return "simple";
case AtomicType::T_COMPOUND: return "compound";
case AtomicType::T_ENUM: return "enum";
case AtomicType::T_TYPEVAR: return "type variable";
}
}
#endif // 0
static char const *ctorName(Type::Tag tag)
{
switch (tag) {
default: xfailure("bad tag");
case Type::T_ATOMIC: return "atomic";
case Type::T_POINTER: return "pointer";
case Type::T_FUNCTION: return "function";
case Type::T_ARRAY: return "array";
case Type::T_POINTERTOMEMBER: return "ptr-to-member";
}
}
// implementation class
class Conversion {
public:
// original parameters to 'getStandardConversion'
string *errorMsg;
SpecialExpr srcSpecial;
Type const *src;
Type const *dest;
bool destIsReceiver;
// eventual return value
StandardConversion ret;
// when true, every destination pointer type constructor
// has had 'const' in its cv flags
bool destConst;
// count how many pointer or ptr-to-member type ctors we
// have stripped so far
int ptrCtorsStripped;
public:
Conversion(string *e, SpecialExpr sp, Type const *s, Type const *d, bool dir)
: errorMsg(e),
srcSpecial(sp),
src(s),
dest(d),
destIsReceiver(dir),
ret(SC_IDENTITY),
destConst(true),
ptrCtorsStripped(0)
{}
StandardConversion error(char const *why);
bool stripPtrCtor(CVFlags scv, CVFlags dcv, bool isReference=false);
};
StandardConversion Conversion::error(char const *why)
{
// 10/02/04: This is probably not the best way to handle this, but one
// problem with 'getStandardConversion' is if the source and destination
// are both references, it wants to pair those references up, but it is
// also possible to implicitly convert away the source reference and bind
// the dest reference, *if* the dest reference is a reference to const.
//
// So, if we are about to report an error (which is why we are in
// this function), and the dest is 'T const &', try again with a
// dest of just 'T'.
if (dest->isReference() &&
dest->getAtType()->isConst()) {
return getStandardConversion(errorMsg, srcSpecial, src, dest->getAtType(),
destIsReceiver);
}
if (errorMsg) {
*errorMsg = stringc
<< "cannot convert `" << src->toString()
<< "' to `" << dest->toString()
<< "': " << why;
}
return ret = SC_ERROR;
}
// strip pointer constructors, update local state; return true
// if we've encountered an error, in which case 'ret' is set
// to the error code to return
bool Conversion::stripPtrCtor(CVFlags scv, CVFlags dcv, bool isReference)
{
if (scv != dcv) {
if (isReference) {
// Conversion from 'int &' to 'int const &' is equivalent to
// SC_LVAL_TO_RVAL, or so I'm led to believe by 13.3.3.2 para 3,
// second example. 13.3.3.1.4 para 5 talks about "reference-
// compatible with added qualification", but I don't then see
// a later discussion of what exactly this means.
//
// update: that term is defined in 8.5.3, and I now think that
// binding 'A&' to 'A const &' should be an SC_QUAL_CONV, just
// like with pointers...; moreover, I suspect that since
// SC_LVAL_TO_RVAL and SC_QUAL_CONV have the same *rank*, I'll
// still be able to pass 13.3.3.2 para 3 ex. 2
xassert(ret == SC_IDENTITY); // shouldn't have had anything added yet
//ret |= SC_QUAL_CONV;
// trying again.. 13.3.3.1.4 para 1
ret |= SC_IDENTITY;
// old code; if ultimately this solution works, I'll drop the
// 'isReference' parameter to this function entirely...
//ret |= SC_LVAL_TO_RVAL;
}
else {
ret |= SC_QUAL_CONV;
}
}
if (scv & ~dcv) {
error("the source has some cv flag that the dest does not");
return true;
}
if (!destConst && (scv != dcv)) {
error("changed cv flags below non-const pointer");
return true;
}
if (!( dcv & CV_CONST )) {
destConst = false;
}
ptrCtorsStripped++;
return false;
}
// ARR_QUAL_CONV: Regard cv flags on an array element to be cv flags
// on the array itself. Dig down below arbitrarily many levels of
// array to find the element.
CVFlags getSrcCVFlags(Type const *src)
{
if (src->isArrayType()) {
ArrayType const *at = src->asArrayTypeC();
return getSrcCVFlags(at->eltType);
}
else {
return src->getCVFlags();
}
}
// Below, each time I extract the CV flags from the 'dest' type,
// I use this function. Whenever 'dest' names a polymorphic type,
// I pretend it has the same CV flags as the source so we don't
// get spurious mismatches.
CVFlags getDestCVFlags(Type const *dest, CVFlags srcCV)
{
CVFlags destCV = getSrcCVFlags(dest);
// 9/23/04: If the destination type is polymorphic, then pretend
// the flags match.
if (dest->isSimpleType()) {
SimpleTypeId id = dest->asSimpleTypeC()->type;
if (id == ST_ANY_OBJ_TYPE ||
id == ST_ANY_NON_VOID ||
id == ST_ANY_TYPE) {
destCV = srcCV;
}
}
return destCV;
}
bool canConvertToBaseClass(Type const *src, Type const *dest, bool &ambig)
{
if (!dest->isCompoundType()) {
return false;
}
CompoundType const *destCt = dest->asCompoundTypeC();
CompoundType const *srcCt = NULL;
if (src->isCompoundType()) {
srcCt = src->asCompoundTypeC();
}
else if (src->isPseudoInstantiation()) {
// (e.g. in/t0386.cc) conversion from pseudoinstantiation: can
// convert to any of the concrete bases
srcCt = src->asCVAtomicTypeC()->atomic->asPseudoInstantiationC()->primary;
}
else {
return false;
}
if (srcCt->hasStrictBaseClass(destCt)) {
ambig = !srcCt->hasUnambiguousBaseClass(destCt);
return true;
}
return false;
}
// not sure if this is such a good idea..
bool couldBeAnything(Type const *t)
{
// PseudoInstantiation is left out because a PI has to be
// a class type
return t->isSimple(ST_DEPENDENT) ||
t->isTypeVariable() ||
t->isDependentQType();
}
// one of the goals of this function is to *not* construct any
// intermediate Type objects; I should be able to do this computation
// without allocating, and if I can then that avoids interaction
// problems with Type annotation systems
StandardConversion getStandardConversion
(string *errorMsg, SpecialExpr srcSpecial, Type const *src, Type const *dest,
bool destIsReceiver)
{
Conversion conv(errorMsg, srcSpecial, src, dest, destIsReceiver);
// --------------- group 1 ----------------
if (src->isReference() &&
!src->asRvalC()->isFunctionType() &&
!src->asRvalC()->isArrayType() &&
!dest->isReference()) {
conv.ret |= SC_LVAL_TO_RVAL;
src = src->asReferenceTypeC()->atType;
// the src type must be complete for this conversion
if (src->isCompoundType() &&
src->asCompoundTypeC()->forward) {
return conv.error("type must be complete to strip '&'");
}
// am I supposed to check cv flags?
}
else if (!src->isReference() && dest->isReference()) {
// binding an (rvalue) object to a reference
if (!destIsReceiver) {
// are we trying to bind to a non-const reference? if so,
// then we can't do it (cppstd 13.3.3.1.4 para 3)
ReferenceType const *destPT = dest->asReferenceTypeC();
if (!destPT->atType->isConst()) {
// can't form the conversion
return conv.error("attempt to bind an rvalue to a non-const reference");
}
}
// strip off the destination reference
dest = dest->asReferenceTypeC()->atType;
// now, one final exception: ordinarily, there's no standard
// conversion from C to P (where C inherits from P); but it *is*
// legal to bind an rvalue of type C to a const reference to P
// (cppstd 13.3.3.1.4 para 1)
if (dest->isCompoundType() &&
src->isCompoundType() &&
src->asCompoundTypeC()->hasStrictBaseClass(dest->asCompoundTypeC())) {
// TODO: ambiguous? inaccessible?
return SC_PTR_CONV; // "derived-to-base Conversion"
}
}
else if (src->asRvalC()->isArrayType() && dest->isPointer()) {
// 7/19/03: 'src' can be an lvalue (cppstd 4.2 para 1)
conv.ret |= SC_ARRAY_TO_PTR;
// note: even if we strip a reference here, we do not say it
// is SC_LVAL_TO_RVAL (why? because I can't represent that.. and
// I hope that that is right...)
src = src->asRvalC()->asArrayTypeC()->eltType;
dest = dest->asPointerTypeC()->atType;
// do one level of qualification conversion checking
CVFlags scv = getSrcCVFlags(src);
CVFlags dcv = getDestCVFlags(dest, scv);
if (srcSpecial == SE_STRINGLIT &&
scv == CV_CONST &&
dcv == CV_NONE) {
// special exception of 4.2 para 2: string literals can be
// converted to 'char*' (w/o 'const'); we'll already have
// converted 'char const []' to 'char const *', so this just
// adds the qualification conversion
//
// TODO: it might be nice to have a CCLang option to disable
// this, so that we could get soundness at the expense of
// compatibility with legacy code
conv.ret |= SC_QUAL_CONV;
scv = CV_NONE; // avoid error in stripPtrCtor, below
}
if (conv.stripPtrCtor(scv, dcv))
{ return conv.ret; }
}
else if (src->isFunctionType() && dest->isPointerType()) {
conv.ret |= SC_FUNC_TO_PTR;
dest = dest->asPointerTypeC()->atType;
CVFlags scv = getSrcCVFlags(src);
CVFlags dcv = getDestCVFlags(dest, scv);
if (conv.stripPtrCtor(scv, dcv))
{ return conv.ret; }
}
// 9/25/04: conversions to bool that must be preceded by a
// group 1 conversion
if (dest->isBool()) {
// these conversions always yield 'true'.. I wonder if there
// is a good way to take advantage of that..
Type const *s = src->asRvalC();
if (s->isArrayType()) {
return conv.ret | SC_ARRAY_TO_PTR | SC_BOOL_CONV;
}
if (s->isFunctionType()) {
return conv.ret | SC_FUNC_TO_PTR | SC_BOOL_CONV;
}
}
// At this point, if the types are to be convertible, their
// constructed type structure must be isomorphic, possibly with the
// exception of cv flags and/or the containing class for member
// pointers. The next phase checks the isomorphism and verifies
// that any difference in the cv flags is within the legal
// variations.
// ---------------- group 3 --------------------
// deconstruct the type constructors until at least one of them
// hits the leaf
while (!src->isCVAtomicType() &&
!dest->isCVAtomicType()) {
if (src->getTag() != dest->getTag()) {
// when PointerType and ReferenceType were unified, I had
// a slightly more informative message for one case
if (src->isPointerType() && dest->isReferenceType()) {
return conv.error("cannot convert rvalue to lvalue");
}
else {
return conv.error("different type constructors");
}
}
switch (src->getTag()) {
default: xfailure("bad type tag");
case Type::T_POINTER:
case Type::T_REFERENCE: {
bool isReference = (src->isReference());
src = src->getAtType();
dest = dest->getAtType();
// we look at the cv flags one level down because all of the
// rules in cppstd talk about things like "pointer to cv T",
// i.e. pairing the * with the cv one level down in their
// descriptive patterns
CVFlags srcCV = getSrcCVFlags(src);
CVFlags destCV = getDestCVFlags(dest, srcCV);
if (conv.stripPtrCtor(srcCV, destCV, isReference))
{ return conv.ret; }
break;
}
case Type::T_FUNCTION: {
// no variance is allowed whatsoever once we reach a function
// type, which is a little odd since I'd think it would be
// ok to pass
// int (*)(Base*)
// where
// int (*)(Derived*)
// is expected, but I don't see such a provision in cppstd
//
// 2005-04-15: Actually, 13.4p7 address this directly, and
// explains that it is indeed illegal.
//
// Also, 8.3.5p4 says that exception specs are irrelevant here,
// even though (again) there is a sound subtyping lattice.
if (src->equals(dest)) {
return conv.ret;
}
else {
return conv.error("unequal function types");
}
}
case Type::T_ARRAY: {
// like functions, no conversions are possible on array types,
// including (as far as I can see) converting
// int[3]
// to
// int[]
//
// ARR_QUAL_CONV: A qualification conversion is possible. The
// element qualifier will already have been processed, so ignore
// it during equality checking.
if (src->equals(dest, MF_IGNORE_ELT_CV)) {
return conv.ret;
}
else {
return conv.error("unequal array types");
}
}
case Type::T_POINTERTOMEMBER: {
PointerToMemberType const *s = src->asPointerToMemberTypeC();
PointerToMemberType const *d = dest->asPointerToMemberTypeC();
if (s->inClass() != d->inClass()) {
if (conv.ptrCtorsStripped == 0) {
// opposite to first ptr ctor, we allow Base -> Derived
if (!d->inClass()->hasUnambiguousBaseClass(s->inClass())) {
return conv.error("src member's class is not an unambiguous "
"base of dest member's class");
}
else if (d->inClass()->hasVirtualBase(s->inClass())) {
return conv.error("src member's class is a virtual base of "
"dest member's class");
}
else {
// TODO: check accessibility.. this depends on the access privileges
// of the code we're in now..
// this is actually a group 2 conversion
conv.ret |= SC_PTR_MEMB_CONV;
}
}
else {
// after the first ctor, variance is not allowed
return conv.error("unequal member classes in ptr-to-member that "
"is not the topmost type");
}
}
src = s->atType;
dest = d->atType;
CVFlags scv = getSrcCVFlags(src);
CVFlags dcv = getDestCVFlags(dest, scv);
if (conv.stripPtrCtor(scv, dcv))
{ return conv.ret; }
// 10/08/04: (t0344.cc) For ptr-to-member where the member is
// a function, we need to ignore the receiver parameter. So
// what follows is basically the T_FUNCTION case, above, but
// with a different EqFlags passed.
if (src->isFunctionType() && dest->isFunctionType()) {
if (src->equals(dest, MF_IGNORE_IMPLICIT)) {
return conv.ret;
}
else {
return conv.error("unequal function types");
}
}
break;
}
}
}
// ---------------- group 2 --------------
if (couldBeAnything(src) ||
couldBeAnything(dest)) {
// conversion could be as good as identity (in/t0572.cc)
return conv.ret;
}
// if I check equality here, will it mess anything up?
// no, looks ok; I'm going to try folding polymorphic
// checking into equality itself...
//
// appears to work! I'll tag the old stuff with "delete me"
// for the moment
if (src->equals(dest, MF_POLYMORPHIC)) {
return conv.ret; // identical now
}
if (conv.ptrCtorsStripped == 1 &&
dest->isSimple(ST_VOID)) {
return conv.ret | SC_PTR_CONV; // converting T* to void*
}
// if both types have not arrived at CVAtomic, then they
// are not convertible
if (!src->isCVAtomicType() ||
!dest->isCVAtomicType()) {
// exception: pointer -> bool
if (dest->isSimple(ST_BOOL) &&
(src->isPointerType() || src->isPointerToMemberType())) {
return conv.ret | SC_BOOL_CONV;
}
// exception: 0 -> (null) pointer
if (srcSpecial == SE_ZERO) {
if (dest->isPointerType()) {
return conv.ret | SC_PTR_CONV;
}
if (dest->isPointerToMemberType()) {
return conv.ret | SC_PTR_MEMB_CONV;
}
}
if (errorMsg) {
// if reporting, I go out of my way a bit here since I expect
// this to be a relatively common error and I'd like to provide
// as much information as will be useful
if (dest->isReference()) {
return conv.error("cannot convert rvalue to lvalue");
}
return conv.error(stringc
<< "different type constructors, "
<< ctorName(src->getTag()) << " vs. "
<< ctorName(dest->getTag()));
}
else {
return SC_ERROR; // for performance, don't make the string at all
}
}
// now we're down to atomics; we expect equality, but ignoring cv
// flags because they've already been handled
CVAtomicType const *s = src->asCVAtomicTypeC();
CVAtomicType const *d = dest->asCVAtomicTypeC();
if (conv.ptrCtorsStripped > 0) {
if (conv.ptrCtorsStripped == 1) {
bool ambig = false;
if (canConvertToBaseClass(src, dest, ambig)) {
if (ambig) {
return conv.error("base class is ambiguous");
}
// TODO: check accessibility.. this depends on the access privileges
// of the code we're in now..
return conv.ret | SC_PTR_CONV; // converting Derived* to Base*
}
}
// since we stripped ptrs, final type must be equal
if (s->atomic->equals(d->atomic)) {
return conv.ret;
}
else {
// 9/25/04: (in/t0316.cc) I'm not sure where the best place to do
// this is, in part b/c I don't know what the real rule is. This
// allows e.g. 'unsigned int &' to be passed where 'int const &'
// is expected.
if (conv.dest->isReference() &&
conv.dest->getAtType()->isConst()) {
// just strip the reference part of the dest; this is like binding
// the (const) reference, which is not an explicit part of the
// "conversion"
return getStandardConversion(errorMsg, srcSpecial, conv.src,
conv.dest->asRvalC(), destIsReceiver);
}
return conv.error("incompatible atomic types");
}
}
else {
// further info on this: 13.3.3.1 para 6, excerpt:
// "Any difference in top-level cv-qualification is
// subsumed by the initialization and does not
// constitute a conversion."
#if 0 // am I supposed to do any checking?
// I'm not perfectly clear on the checking I should do for
// the cv flags here. lval-to-rval says that 'int const &'
// becomes 'int' whereas 'Foo const &' becomes 'Foo const'
if ((conv.ret & SC_LVAL_TO_RVAL) && // did we do lval-to-rval?
s->atomic->isSimpleType()) { // were we a ref to simple?
// clear any 'const' on the source
scv &= ~CV_CONST;
}
if (scv != dcv) {
return conv.error("different cv flags (is this right?)");
}
#endif // 0
}
if (s->atomic->equals(d->atomic)) {
return conv.ret; // identical now
}
SimpleType const *srcSimple = src->isSimpleType() ? src->asSimpleTypeC() : NULL;
SimpleType const *destSimple = dest->isSimpleType() ? dest->asSimpleTypeC() : NULL;
if (isIntegerPromotion(s->atomic, d->atomic)) {
return conv.ret | SC_INT_PROM;
}
if (srcSimple && srcSimple->type == ST_FLOAT &&
destSimple && destSimple->type == ST_DOUBLE) {
return conv.ret | SC_FLOAT_PROM;
}
// do this before checking for SC_INT_CONV, since a destination
// type of 'bool' is explicitly excluded by 4.7 para 4
if (isNumeric(src, srcSimple) &&
destSimple && destSimple->type == ST_BOOL) {
return conv.ret | SC_BOOL_CONV;
}
if (isIntegerNumeric(src, srcSimple) &&
destSimple && isIntegerType(destSimple->type)) {
return conv.ret | SC_INT_CONV;
}
bool srcFloat = srcSimple && isFloatType(srcSimple->type);
bool destFloat = destSimple && isFloatType(destSimple->type);
if (srcFloat && destFloat) {
return conv.ret | SC_FLOAT_CONV;
}
if (isNumeric(src, srcSimple) &&
isNumeric(dest, destSimple) &&
(srcFloat || destFloat)) { // last test required if both are enums
return conv.ret | SC_FLOAT_INT_CONV;
}
// no more conversion possibilities remain; I don't print the
// atomic kinds, because the error is based on more than just
// the kinds; moreover, since I already know I didn't strip
// any ptr ctors, the full types should be easy to read
return conv.error("incompatible atomic types");
}
// This function implements Section 4.5, which contains
// implementation-determined details. Promotions are distinguished
// from conversions in that they are preferred over conversions during
// overload resolution. Since this distinction is implementation-
// dependent, I envision that users might replace this function with
// an implementation that better suits them.
//
// NOTE: One way to get a conservative analysis that never silently
// chooses among potentially-ambiguous choices is to make this always
// return false.
//
// Another idea: It would be nice to have a set of tests such that
// by running the tests one could determine what choices a given compiler
// makes, so that this function could be modified accordingly to
// imitate that behavior.
bool isIntegerPromotion(AtomicType const *src, AtomicType const *dest)
{
bool srcSimple = src->isSimpleType();
bool destSimple = dest->isSimpleType();
SimpleTypeId sid = srcSimple? src->asSimpleTypeC()->type : ST_ERROR;
SimpleTypeId did = destSimple? dest->asSimpleTypeC()->type : ST_ERROR;
if (did == ST_INT ||
did == ST_PROMOTED_INTEGRAL ||
did == ST_PROMOTED_ARITHMETIC) {
// paragraph 1: char/short -> int
// implementation choice: I assume char is 8 bits and short
// is 16 bits and int is 32 bits, so all map to 'int', as
// opposed to 'unsigned int'
if (sid == ST_CHAR ||
sid == ST_UNSIGNED_CHAR ||
sid == ST_SIGNED_CHAR ||
sid == ST_SHORT_INT ||
sid == ST_UNSIGNED_SHORT_INT) {
return true;
}
// paragraph 2: wchar_t/enum -> int
// implementation choice: I assume wchar_t and all enums fit into ints
if (sid == ST_WCHAR_T ||
src->isEnumType()) {
return true;
}
// TODO: paragraph 3: bitfields
// paragraph 4: bool -> int
if (sid == ST_BOOL) {
return true;
}
}
return false;
}
Type *makeSimpleType(TypeFactory &tfac, SimpleTypeId id)
{
return tfac.getSimpleType(id);
}
Type *getConcreteDestType(TypeFactory &tfac, Type *srcType,
StandardConversion sconv,
SimpleTypeId destPolyType)
{
// move 'srcType' closer to the actual dest type according to group 1
if (sconv & SC_LVAL_TO_RVAL) {
srcType = srcType->getAtType();
sconv &= ~SC_LVAL_TO_RVAL;
}
else {
// I don't think any other group 1 is possible when
// converting to a polymorphic type
xassert(!( sconv & SC_GROUP_1_MASK ));
}
// group 3: I believe this is impossible too
xassert(!( sconv & SC_GROUP_3_MASK ));
// so now we only have group 2 to deal with
xassert(sconv == (sconv & SC_GROUP_2_MASK));
// if no conversions remain, we're done
if (sconv == SC_IDENTITY) {
return srcType;
}
switch (destPolyType) {
// if this fails, the caller most likely failed to recognize
// that it could answer its question directly
default: xfailure("bad polymorphic type");
// the following includes some guesswork... there are probably
// bugs here; for now, I generally prefer to return something
// than to fail an assertion
case ST_PROMOTED_INTEGRAL:
// most likely SC_INT_PROM; I only promote to ST_INT
return makeSimpleType(tfac, ST_INT);
case ST_PROMOTED_ARITHMETIC:
if (sconv == SC_INT_PROM) {
return makeSimpleType(tfac, ST_INT);
}
else {
return makeSimpleType(tfac, ST_DOUBLE);
}
// not sure what conversions would be needed here..
case ST_INTEGRAL:
case ST_ARITHMETIC:
case ST_ARITHMETIC_NON_BOOL:
return makeSimpleType(tfac, ST_INT);
case ST_ANY_OBJ_TYPE:
case ST_ANY_NON_VOID:
case ST_ANY_TYPE:
// I really have no idea what could cause a conversion
// here, so I will go ahead and complain
xfailure("I don't think this is possible; conversion to very broad polymorphic type?");
return makeSimpleType(tfac, ST_INT); // silence warning...
}
}
void getIntegerStats(SimpleTypeId id, int &length, int &uns)
{
switch (id) {
default: xfailure("bad id for getIntegerLength");
case ST_INT: length=0; uns=0; return;
case ST_UNSIGNED_INT: length=0; uns=1; return;
case ST_LONG_INT: length=1; uns=0; return;
case ST_UNSIGNED_LONG_INT: length=1; uns=1; return;
case ST_LONG_LONG: length=2; uns=0; return;
case ST_UNSIGNED_LONG_LONG: length=2; uns=1; return;
}
}
// implemented below
static SimpleTypeId uacHelper(SimpleTypeId leftId, SimpleTypeId rightId);
// cppstd section 5 para 9
// and C99 secton 6.3.1.8 para 1
Type *usualArithmeticConversions(TypeFactory &tfac, Type *left, Type *right)
{
if (left->isError()) { return left; }
if (right->isError()) { return right; }
// if either operand is of type long double, [return] long double
if (left->isSimple(ST_LONG_DOUBLE)) { return left; }
if (right->isSimple(ST_LONG_DOUBLE)) { return right; }
// similar for double
if (left->isSimple(ST_DOUBLE)) { return left; }
if (right->isSimple(ST_DOUBLE)) { return right; }
// and float
if (left->isSimple(ST_FLOAT)) { return left; }
if (right->isSimple(ST_FLOAT)) { return right; }
// now apply integral promotions (4.5)
SimpleTypeId leftId = applyIntegralPromotions(left);
SimpleTypeId rightId = applyIntegralPromotions(right);
// conversions on SimpleTypeIds
SimpleTypeId lubId = uacHelper(leftId, rightId);
// package it
return makeSimpleType(tfac, lubId);
}
SimpleTypeId usualArithmeticConversions(SimpleTypeId leftId, SimpleTypeId rightId)
{
// same initial tests as above, but directly on the ids
// if either operand is of type long double, [return] long double
if (leftId == ST_LONG_DOUBLE) { return leftId; }
if (rightId == ST_LONG_DOUBLE) { return rightId; }
// similar for double
if (leftId == ST_DOUBLE) { return leftId; }
if (rightId == ST_DOUBLE) { return rightId; }
// and float
if (leftId == ST_FLOAT) { return leftId; }
if (rightId == ST_FLOAT) { return rightId; }
// now apply integral promotions (4.5)
leftId = applyIntegralPromotions(leftId);
rightId = applyIntegralPromotions(rightId);
// conversions on SimpleTypeIds
SimpleTypeId lubId = uacHelper(leftId, rightId);
return lubId;
}
static SimpleTypeId uacHelper(SimpleTypeId leftId, SimpleTypeId rightId)
{
// At this point, both cppstd and C99 go into gory detail
// case-analyzing the types (which are both integral types at least
// 'int' or bigger/wider). However, the effect of both analyses is
// to simply compute the least upper bound over the lattice of the
// "all values can be represented by" relation. This relation
// is always an extension of the following minimal one:
//
// long long -------> unsigned long long
// ^ ^
// | |
// long -------> unsigned long
// ^ ^
// | |
// int -------> unsigned int
//
// Additional implementation-specific edges may be added when the
// representation ranges allow. For example if 'long' is 64 bits
// and 'unsigned int' is 32 bits, then there will be an edge from
// 'unsigned int' to 'long', and that edge participates in the
// least-upper-bound computation. I play it conservative and
// compute my LUB over just the minimal one displayed above.
// mod out the length (C99 term: "conversion rank") and unsignedness
int leftLength, leftUns;
getIntegerStats(leftId, leftLength, leftUns);
int rightLength, rightUns;
getIntegerStats(rightId, rightLength, rightUns);
// least upper bound of a product lattice
int lubLength = max(leftLength, rightLength);
int lubUns = max(leftUns, rightUns);
// put them back together
static SimpleTypeId const map[3 /*length*/][2 /*unsignedness*/] = {
{ ST_INT, ST_UNSIGNED_INT },
{ ST_LONG_INT, ST_UNSIGNED_LONG_INT },
{ ST_LONG_LONG, ST_UNSIGNED_LONG_LONG }
};
SimpleTypeId lubId = map[lubLength][lubUns];
return lubId;
}
// cppstd 4.5
SimpleTypeId applyIntegralPromotions(Type *t)
{
// since I only promote to 'int', this is easy
if (!t->isSimpleType()) { // enumerations, mainly
return ST_INT;
}
SimpleTypeId id = t->asSimpleTypeC()->type;
return applyIntegralPromotions(id);
}
SimpleTypeId applyIntegralPromotions(SimpleTypeId id)
{
switch (id) {
case ST_CHAR:
case ST_SIGNED_CHAR:
case ST_UNSIGNED_CHAR:
case ST_SHORT_INT:
case ST_UNSIGNED_SHORT_INT:
case ST_WCHAR_T:
case ST_BOOL:
return ST_INT; // promote smaller integer values
default:
return id; // keep everything else
}
}
void test_getStandardConversion(
Env &env, SpecialExpr special, Type const *src, Type const *dest,
int expected)
{
// run our function
string errorMsg;
StandardConversion actual = getStandardConversion(&errorMsg, special, src, dest);
// turn any resulting messags into warnings, so I can see their
// results without causing the final exit status to be nonzero
if (actual == SC_ERROR) {
env.warning(errorMsg);
}
// did the function do what we expected?
if (actual != expected) {
// no, explain the situation
env.error(stringc
<< "getStandardConversion("
<< toString(special) << ", `"
<< src->toString() << "', `"
<< dest->toString() << "') yielded "
<< toString(actual) << ", but I expected "
<< toString((StandardConversion)expected));
}
else if (tracingSys("gSC")) {
// make a warning to show what happened anyway
env.warning(stringc
<< "getStandardConversion("
<< toString(special) << ", `"
<< src->toString() << "', `"
<< dest->toString() << "') yielded "
<< toString(actual));
}
}
// ------------------- reference-relatedness ------------------
bool isReferenceRelatedTo(Type *t1, Type *t2)
{
// ignoring toplevel cv-qualification, either t1 and t2 must be
// the same type, or they must be classes and t1 must be a base
// class of t2
// this sometimes ends up with t2 being polymorphic, so it goes first
if (t2->equals(t1, MF_IGNORE_TOP_CV | MF_POLYMORPHIC)) {
return true;
}
// this implicitly skips toplevel cv
if (t1->isCompoundType() &&
t2->isCompoundType() &&
t2->asCompoundType()->hasBaseClass(t1->asCompoundType())) {
return true;
}
return false;
}
int referenceCompatibility(Type *t1, Type *t2)
{
if (!isReferenceRelatedTo(t1, t2)) {
return 0; // not even related
}
// get the toplevel cv flags
CVFlags cv1 = t1->getCVFlags();
CVFlags cv2 = t2->getCVFlags();
if (cv1 == cv2) {
return 2; // exact match
}
if (cv1 & cv2 == cv2) {
// cv1 is a superset
return 1; // "compatible with added qualification"
}
return 0; // not compatible
}
// EOF
| bsd-3-clause |
adobe/chromium | chrome/common/child_process_logging_win.cc | 7878 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/child_process_logging.h"
#include <windows.h>
#include "base/command_line.h"
#include "base/string_util.h"
#include "base/string_number_conversions.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/installer/util/google_update_settings.h"
#include "content/public/common/gpu_info.h"
#include "googleurl/src/gurl.h"
namespace child_process_logging {
// exported in breakpad_win.cc: void __declspec(dllexport) __cdecl SetActiveURL.
typedef void (__cdecl *MainSetActiveURL)(const wchar_t*);
// exported in breakpad_win.cc: void __declspec(dllexport) __cdecl SetClientId.
typedef void (__cdecl *MainSetClientId)(const wchar_t*);
// exported in breakpad_win.cc:
// void __declspec(dllexport) __cdecl SetNumberOfExtensions.
typedef void (__cdecl *MainSetNumberOfExtensions)(int);
// exported in breakpad_win.cc:
// void __declspec(dllexport) __cdecl SetExtensionID.
typedef void (__cdecl *MainSetExtensionID)(size_t, const wchar_t*);
// exported in breakpad_win.cc: void __declspec(dllexport) __cdecl SetGpuInfo.
typedef void (__cdecl *MainSetGpuInfo)(const wchar_t*, const wchar_t*,
const wchar_t*, const wchar_t*,
const wchar_t*);
// exported in breakpad_win.cc:
// void __declspec(dllexport) __cdecl SetPrinterInfo.
typedef void (__cdecl *MainSetPrinterInfo)(const wchar_t*);
// exported in breakpad_win.cc:
// void __declspec(dllexport) __cdecl SetNumberOfViews.
typedef void (__cdecl *MainSetNumberOfViews)(int);
// exported in breakpad_win.cc:
// void __declspec(dllexport) __cdecl SetCommandLine
typedef void (__cdecl *MainSetCommandLine)(const CommandLine*);
// exported in breakpad_field_trial_win.cc:
// void __declspec(dllexport) __cdecl SetExperimentList
typedef void (__cdecl *MainSetExperimentList)(const std::vector<string16>&);
void SetActiveURL(const GURL& url) {
static MainSetActiveURL set_active_url = NULL;
// note: benign race condition on set_active_url.
if (!set_active_url) {
HMODULE exe_module = GetModuleHandle(chrome::kBrowserProcessExecutableName);
if (!exe_module)
return;
set_active_url = reinterpret_cast<MainSetActiveURL>(
GetProcAddress(exe_module, "SetActiveURL"));
if (!set_active_url)
return;
}
(set_active_url)(UTF8ToWide(url.possibly_invalid_spec()).c_str());
}
void SetClientId(const std::string& client_id) {
std::string str(client_id);
// Remove all instance of '-' char from the GUID. So BCD-WXY becomes BCDWXY.
ReplaceSubstringsAfterOffset(&str, 0, "-", "");
if (str.empty())
return;
std::wstring wstr = ASCIIToWide(str);
std::wstring old_wstr;
if (!GoogleUpdateSettings::GetMetricsId(&old_wstr) ||
wstr != old_wstr)
GoogleUpdateSettings::SetMetricsId(wstr);
static MainSetClientId set_client_id = NULL;
// note: benign race condition on set_client_id.
if (!set_client_id) {
HMODULE exe_module = GetModuleHandle(chrome::kBrowserProcessExecutableName);
if (!exe_module)
return;
set_client_id = reinterpret_cast<MainSetClientId>(
GetProcAddress(exe_module, "SetClientId"));
if (!set_client_id)
return;
}
(set_client_id)(wstr.c_str());
}
std::string GetClientId() {
std::wstring wstr_client_id;
if (GoogleUpdateSettings::GetMetricsId(&wstr_client_id))
return WideToASCII(wstr_client_id);
else
return std::string();
}
void SetActiveExtensions(const std::set<std::string>& extension_ids) {
static MainSetNumberOfExtensions set_number_of_extensions = NULL;
// note: benign race condition on set_number_of_extensions.
if (!set_number_of_extensions) {
HMODULE exe_module = GetModuleHandle(chrome::kBrowserProcessExecutableName);
if (!exe_module)
return;
set_number_of_extensions = reinterpret_cast<MainSetNumberOfExtensions>(
GetProcAddress(exe_module, "SetNumberOfExtensions"));
if (!set_number_of_extensions)
return;
}
static MainSetExtensionID set_extension_id = NULL;
// note: benign race condition on set_extension_id.
if (!set_extension_id) {
HMODULE exe_module = GetModuleHandle(chrome::kBrowserProcessExecutableName);
if (!exe_module)
return;
set_extension_id = reinterpret_cast<MainSetExtensionID>(
GetProcAddress(exe_module, "SetExtensionID"));
if (!set_extension_id)
return;
}
(set_number_of_extensions)(static_cast<int>(extension_ids.size()));
std::set<std::string>::const_iterator iter = extension_ids.begin();
for (size_t i = 0; i < kMaxReportedActiveExtensions; ++i) {
if (iter != extension_ids.end()) {
(set_extension_id)(i, ASCIIToWide(iter->c_str()).c_str());
++iter;
} else {
(set_extension_id)(i, L"");
}
}
}
void SetGpuInfo(const content::GPUInfo& gpu_info) {
static MainSetGpuInfo set_gpu_info = NULL;
// note: benign race condition on set_gpu_info.
if (!set_gpu_info) {
HMODULE exe_module = GetModuleHandle(chrome::kBrowserProcessExecutableName);
if (!exe_module)
return;
set_gpu_info = reinterpret_cast<MainSetGpuInfo>(
GetProcAddress(exe_module, "SetGpuInfo"));
if (!set_gpu_info)
return;
}
(set_gpu_info)(
base::StringPrintf(L"0x%04x", gpu_info.vendor_id).c_str(),
base::StringPrintf(L"0x%04x", gpu_info.device_id).c_str(),
UTF8ToUTF16(gpu_info.driver_version).c_str(),
UTF8ToUTF16(gpu_info.pixel_shader_version).c_str(),
UTF8ToUTF16(gpu_info.vertex_shader_version).c_str());
}
void SetPrinterInfo(const char* printer_info) {
static MainSetPrinterInfo set_printer_info = NULL;
// note: benign race condition on set_printer_info.
if (!set_printer_info) {
HMODULE exe_module = GetModuleHandle(chrome::kBrowserProcessExecutableName);
if (!exe_module)
return;
set_printer_info = reinterpret_cast<MainSetPrinterInfo>(
GetProcAddress(exe_module, "SetPrinterInfo"));
if (!set_printer_info)
return;
}
(set_printer_info)(UTF8ToWide(printer_info).c_str());
}
void SetCommandLine(const CommandLine* command_line) {
static MainSetCommandLine set_command_line = NULL;
// note: benign race condition on set_command_line.
if (!set_command_line) {
HMODULE exe_module = GetModuleHandle(chrome::kBrowserProcessExecutableName);
if (!exe_module)
return;
set_command_line = reinterpret_cast<MainSetCommandLine>(
GetProcAddress(exe_module, "SetCommandLine"));
if (!set_command_line)
return;
}
(set_command_line)(command_line);
}
void SetExperimentList(const std::vector<string16>& state) {
static MainSetExperimentList set_experiment_list = NULL;
// note: benign race condition on set_experiment_list.
if (!set_experiment_list) {
HMODULE exe_module = GetModuleHandle(chrome::kBrowserProcessExecutableName);
if (!exe_module)
return;
set_experiment_list = reinterpret_cast<MainSetExperimentList>(
GetProcAddress(exe_module, "SetExperimentList"));
if (!set_experiment_list)
return;
}
(set_experiment_list)(state);
}
void SetNumberOfViews(int number_of_views) {
static MainSetNumberOfViews set_number_of_views = NULL;
// note: benign race condition on set_number_of_views.
if (!set_number_of_views) {
HMODULE exe_module = GetModuleHandle(chrome::kBrowserProcessExecutableName);
if (!exe_module)
return;
set_number_of_views = reinterpret_cast<MainSetNumberOfViews>(
GetProcAddress(exe_module, "SetNumberOfViews"));
if (!set_number_of_views)
return;
}
(set_number_of_views)(number_of_views);
}
} // namespace child_process_logging
| bsd-3-clause |
sushipai/yii2016 | common/widgets/online/Online.php | 395 | <?php
namespace common\widgets\online;
use Yii;
use yii\base\Widget;
class Online extends Widget {
public function run() {
if (Yii::$app->params['qq_open'] === '1') {
$list = Yii::$app->params['qq_list'];
if (strpos($list, '|') !== false) {
return $this->render('online', ['list' => explode(',', $list)]);
}
}
}
}
| bsd-3-clause |
goddardl/gaffer | python/GafferOSLUITest/DocumentationTest.py | 2214 | ##########################################################################
#
# Copyright (c) 2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software 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.
#
##########################################################################
import GafferUITest
import GafferImage
import GafferImageUI
import GafferScene
import GafferSceneUI
import GafferOSL
import GafferOSLUI
class DocumentationTest( GafferUITest.TestCase ) :
def test( self ) :
self.maxDiff = None
self.assertNodesAreDocumented(
GafferOSL,
additionalTerminalPlugTypes = ( GafferScene.ScenePlug, GafferImage.ImagePlug )
)
if __name__ == "__main__":
unittest.main()
| bsd-3-clause |
eric-seekas/hex | src/hex_switches_port.cc | 3298 | // Copyright (c) 2012-2013 NetEase Youdao Inc. and other heX contributors. All
// rights reserved. Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file.
#include "hex_switches_port.h"
#include "default_values.h"
#include <string>
namespace hex {
static bool hex_module_ = false;
#if defined(OS_WIN)
static bool desktop_widget_ = false;
#endif // OS_WIN
static bool single_process_ = !GET_DEFAULT_VALUE(multiple_process);
static std::string locked_path_ = GET_DEFAULT_VALUE(locked_path);
static std::string disabled_node_modules_ =
GET_DEFAULT_VALUE(disabled_node_modules);
static std::string enabled_node_modules_ =
GET_DEFAULT_VALUE(enabled_node_modules);
static bool disable_node_third_party_native_modules_ =
GET_DEFAULT_VALUE(disable_node_third_party_native_modules);
static std::string node_args_ = EMPTY_STRING;
static bool launch_node_in_all_pages_ =
GET_DEFAULT_VALUE(launch_node_in_all_pages);
static bool launch_node_in_background_ =
GET_DEFAULT_VALUE(launch_node_in_background);
static bool load_node_manually_ = GET_DEFAULT_VALUE(load_node_manually);
static bool disable_async_node_apis_ =
GET_DEFAULT_VALUE(disable_async_node_apis);
static bool disable_form_apis_ = GET_DEFAULT_VALUE(form_disable_form_apis);
void SetHeXModule(bool hex_module) {
hex_module_ = hex_module;
}
bool HeXModule() {
return hex_module_;
}
#if defined(OS_WIN)
/*void SetDesktopWidget(bool desktop_widget) {
desktop_widget_ = desktop_widget;
}
bool DesktopWidget() {
return desktop_widget_;
}*/
#endif // OS_WIN
void SetSingleProcess(bool single_process) {
single_process_ = single_process;
}
bool SingleProcess() {
return single_process_;
}
void SetDisableFormApis(bool apis) {
disable_form_apis_ = apis;
}
bool DisableFormApis() {
return disable_form_apis_;
}
void SetLockedPath(const char* path) {
locked_path_ = path;
}
const char* LockedPath() {
return locked_path_.c_str();
}
void SetDisabledNodeModules(const char* disabled) {
disabled_node_modules_ = disabled;
}
const char* DisabledNodeModules() {
return disabled_node_modules_.c_str();
}
void SetEnabledNodeModules(const char* enabled) {
enabled_node_modules_ = enabled;
}
const char* EnabledNodeModules() {
return enabled_node_modules_.c_str();
}
void SetDisableNodeThirdPartyNativeModules(bool no_native) {
disable_node_third_party_native_modules_ = no_native;
}
bool DisableNodeThirdPartyNativeModules() {
return disable_node_third_party_native_modules_;
}
void SetNodeArgs(const char* args) {
node_args_ = args;
}
const char* NodeArgs() {
return node_args_.c_str();
}
void SetLaunchNodeInAllPages(bool in_all_pages) {
launch_node_in_all_pages_ = in_all_pages;
}
bool LaunchNodeInAllPages() {
return launch_node_in_all_pages_;
}
void SetLaunchNodeInBackground(bool in_background) {
launch_node_in_background_ = in_background;
}
bool LaunchNodeInBackground() {
return launch_node_in_background_;
}
void SetLoadNodeManually(bool manually) {
load_node_manually_ = manually;
}
bool LoadNodeManually() {
return load_node_manually_;
}
void SetDisableAsyncNodeApis(bool async) {
disable_async_node_apis_ = async;
}
bool DisableAsyncNodeApis() {
return disable_async_node_apis_;
}
} // namespace hex
| bsd-3-clause |
iPlantCollaborativeOpenSource/iRODS3.2-custom | nt/iExp/MetaView.cpp | 14795 | // MetaView.cpp : implementation file
//
#include "stdafx.h"
#include "inquisitor.h"
#include "MetaView.h"
#include "InquisitorDoc.h"
#include "winiObjects.h"
#include "CCEdit.h"
//#include "winbase.h"
#define REPORT_ATTR 0
#define REPORT_VALU 1
#define REPORT_WIDTH_ATTR 200
#define REPORT_WIDTH_VALU 200
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//extern CMutex gMutex;
//extern CCriticalSection gCS;
extern CMutex gCS;
extern int gCount;
extern CImageList gIconListLarge;
extern CImageList gIconListSmall;
/////////////////////////////////////////////////////////////////////////////
// CMetaView
IMPLEMENT_DYNCREATE(CMetaView, CListView)
CMetaView::CMetaView()
{
m_bInitialized = false;
m_bEditing = false;
}
CMetaView::~CMetaView()
{
}
BEGIN_MESSAGE_MAP(CMetaView, CListView)
//{{AFX_MSG_MAP(CMetaView)
ON_NOTIFY_REFLECT(NM_SETFOCUS, OnSetfocus)
ON_UPDATE_COMMAND_UI(ID_NEW_COLLECTION, OnUpdateNewCollection)
ON_UPDATE_COMMAND_UI(ID_NEW_CONTAINER, OnUpdateNewContainer)
//ON_UPDATE_COMMAND_UI(ID_QUERY, OnUpdateQuery)
ON_UPDATE_COMMAND_UI(ID_UPLOAD, OnUpdateUpload)
ON_UPDATE_COMMAND_UI(ID_UPLOADFOLDER, OnUpdateUploadFolder)
ON_UPDATE_COMMAND_UI(ID_DOWNLOAD, OnUpdateDownload)
ON_UPDATE_COMMAND_UI(ID_REPLICATE, OnUpdateReplicate)
ON_UPDATE_COMMAND_UI(ID_SYNCHRONIZE, OnUpdateSynchronize)
ON_UPDATE_COMMAND_UI(ID_ACCESS_CTRL, OnUpdateAccessCtrl)
//ON_COMMAND(ID_DELETE, OnDelete)
ON_COMMAND(ID_METADATA, OnMetadata)
//ON_UPDATE_COMMAND_UI(ID_METADATA, OnUpdateMetadata)
ON_UPDATE_COMMAND_UI(ID_DELETE, OnUpdateDelete)
ON_COMMAND(ID_RENAME, OnRename)
ON_UPDATE_COMMAND_UI(ID_RENAME, OnUpdateRename)
ON_UPDATE_COMMAND_UI(ID_COMMENT, OnUpdateComment)
ON_WM_LBUTTONDOWN()
ON_NOTIFY_REFLECT(LVN_ENDLABELEDIT, OnEndlabeledit)
ON_COMMAND(ID_NEW_META, OnNewMeta)
ON_UPDATE_COMMAND_UI(ID_NEW_META, OnUpdateNewMeta)
ON_NOTIFY_REFLECT(NM_RCLICK, OnRclick)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMetaView drawing
void CMetaView::OnDraw(CDC* pDC)
{
CDocument* pDoc = GetDocument();
ASSERT_VALID(pDoc);
CListCtrl& refCtrl = GetListCtrl();
refCtrl.InsertItem(0,"Item!");
}
/////////////////////////////////////////////////////////////////////////////
// CMetaView diagnostics
#ifdef _DEBUG
void CMetaView::AssertValid() const
{
CListView::AssertValid();
}
void CMetaView::Dump(CDumpContext& dc) const
{
CListView::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CMetaView message handlers
BOOL CMetaView::PreCreateWindow(CREATESTRUCT& cs)
{
if(!CListView::PreCreateWindow(cs))
return FALSE;
cs.style |= LVS_EDITLABELS;
return TRUE;
}
//this function is called once per connection, but may be called several times during the
//lifetime of the program because single document interfaces resuse the document object.
//this operation needs to be done after the window's been created, but only once during
//the lifetime of the process - hence the variable.
void CMetaView::OnInitialUpdate()
{
if(!m_bInitialized)
{
CListCtrl& list = GetListCtrl();
list.SetImageList(&gIconListSmall,LVSIL_SMALL);
list.SetImageList(&gIconListLarge,LVSIL_NORMAL);
list.InsertColumn(REPORT_ATTR,"Attribute", LVCFMT_LEFT, REPORT_WIDTH_ATTR);
list.InsertColumn(REPORT_VALU,"Value", LVCFMT_LEFT, REPORT_WIDTH_VALU);
list.ModifyStyle(0, LVS_REPORT);
m_bInitialized = true;
}
//OnUpdate(this, NULL, NULL);
}
#if _DEBUG
CInquisitorDoc* CMetaView::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CInquisitorDoc)));
return (CInquisitorDoc*)m_pDocument;
}
#endif
#if 0
void CMetaView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint)
{
CListCtrl& list = GetListCtrl();
return;
list.DeleteAllItems();
m_nRedirector.clear();
if(3 == lHint) //code to clear screen
return;
CInquisitorDoc* pDoc = GetDocument();
WINI::INode* node = pDoc->GetCurrentNode();
if(NULL == node)
return;
int count = node->CountChildren();
m_nRedirector.resize(count);
WINI::INode* child;
int type;
DWORD dwStyle = GetWindowLong(list.m_hWnd, GWL_STYLE);
int image, selected_image;
for(int i = 0; i < node->CountChildren(); i++)
{
child = node->GetChild(i);
type = child->GetType();
if(WINI_METADATA != type)
continue;
WINI::IMetadataNode* metadata = (WINI::IMetadataNode*)child;
const char * blah = metadata->GetName();
GetImage(type, 0, child->isOpen(), image, selected_image);
int position;
if(dwStyle & LVS_REPORT && !(dwStyle & LVS_SMALLICON))
{
position = list.InsertItem(i, metadata->GetAttribute(), image);
m_nRedirector[position] = i;
list.SetItemText(position, 1, metadata->GetValue());
}else
{
position = list.InsertItem(i, metadata->GetName(), image);
m_nRedirector[position] = i;
}
}
}
#endif
void CMetaView::GetImage(const int& node_type, const char* sub_type, bool isOpen, int &image, int& selected_image)
{
switch(node_type)
{
case WINI_DATASET:
image = 1;
break;
case WINI_COLLECTION:
image = 2;
break;
case WINI_METADATA:
image = 3;
break;
case WINI_ACCESS:
image = 12;
break;
case WINI_RESOURCE:
if(0 == strcmp("unix file system", sub_type))
image = 14;
else if(0 == strcmp("hpss file system", sub_type))
image = 15;
else if(0 == strcmp("oracle dblobj database", sub_type))
image = 13;
else
image = 7;
break;
case WINI_QUERY:
image = 4;
break;
case WINI_DOMAIN:
image = 10;
break;
case WINI_USER:
image = 9;
break;
case WINI_ZONE:
image = 16;
break;
default:
image = 0;
break;
}
selected_image = image + 42;
if(isOpen)
image += 21;
}
void CMetaView::OnSetfocus(NMHDR* pNMHDR, LRESULT* pResult)
{
*pResult = 0;
}
void CMetaView::OnUpdateNewCollection(CCmdUI* pCmdUI)
{
// TODO: Add your command update UI handler code here
pCmdUI->Enable(FALSE);
}
void CMetaView::OnUpdateNewContainer(CCmdUI* pCmdUI)
{
// TODO: Add your command update UI handler code here
pCmdUI->Enable(FALSE);
}
#if 0
void CMetaView::OnUpdateQuery(CCmdUI* pCmdUI)
{
CInquisitorDoc* pDoc = GetDocument();
//WINI::INode* Node = pDoc->GetCurrentNode();
if(NULL == Node)
{
pCmdUI->Enable(FALSE);
return;
}
switch(Node->GetType())
{
case WINI_COLLECTION:
case WINI_QUERY:
break;
default:
pCmdUI->Enable(FALSE);
}
}
#endif
void CMetaView::OnUpdateUpload(CCmdUI* pCmdUI)
{
// TODO: Add your command update UI handler code here
pCmdUI->Enable(FALSE);
}
void CMetaView::OnUpdateUploadFolder(CCmdUI* pCmdUI)
{
// TODO: Add your command update UI handler code here
pCmdUI->Enable(FALSE);
}
void CMetaView::OnUpdateDownload(CCmdUI* pCmdUI)
{
// TODO: Add your command update UI handler code here
pCmdUI->Enable(FALSE);
}
void CMetaView::OnUpdateReplicate(CCmdUI* pCmdUI)
{
// TODO: Add your command update UI handler code here
pCmdUI->Enable(FALSE);
}
void CMetaView::OnUpdateSynchronize(CCmdUI* pCmdUI)
{
pCmdUI->Enable(FALSE);
}
void CMetaView::OnUpdateAccessCtrl(CCmdUI* pCmdUI)
{
// TODO: Add your command update UI handler code here
pCmdUI->Enable(FALSE);
}
#if 0
void CMetaView::OnDelete()
{
CListCtrl& list = GetListCtrl();
int count = list.GetSelectedCount();
gCount = count;
POSITION POS;
int pos;
CInquisitorDoc* pDoc = GetDocument();
if(IDNO == AfxMessageBox("Do you wish to delete the selected item(s)?", MB_YESNO))
{
return;
}
//WINI::INode* parent = pDoc->GetCurrentNode();
WINI::INode* child;
POS = list.GetFirstSelectedItemPosition();
int type;
while(POS)
{
pos = list.GetNextSelectedItem(POS);
child = parent->GetChild(m_nRedirector[pos]);
type = child->GetType(); //if it cans, it'll can here before it hits the thread
ASSERT(WINI_METADATA == type);
//pDoc->Delete(child);
}
}
#endif
void CMetaView::OnMetadata()
{
// TODO: Add your command handler code here
AfxMessageBox("Extended Metadata dialog not yet implemented.");
}
#if 0
void CMetaView::OnUpdateMetadata(CCmdUI* pCmdUI)
{
CInquisitorDoc* pDoc = GetDocument();
WINI::INode* node = pDoc->GetCurrentNode();
switch(node->GetType())
{
case WINI_DATASET:
case WINI_COLLECTION:
break;
default:
pCmdUI->Enable(FALSE);
break;
}
}
#endif
void CMetaView::OnUpdateDelete(CCmdUI* pCmdUI)
{
CListCtrl& list = GetListCtrl();
if(list.GetSelectedCount() == 0)
pCmdUI->Enable(FALSE);
}
void CMetaView::OnRename()
{
// TODO: Add your command handler code here
}
void CMetaView::OnUpdateRename(CCmdUI* pCmdUI)
{
pCmdUI->Enable(FALSE);
}
void CMetaView::OnUpdateComment(CCmdUI* pCmdUI)
{
pCmdUI->Enable(FALSE);
}
void CMetaView::OnLButtonDown(UINT nFlags, CPoint point)
{
int index;
CListView::OnLButtonDown(nFlags, point);
int colnum;
if( ( index = HitTestEx( point, &colnum )) != -1 )
{
int blah;
for (unsigned int i=0; i < GetListCtrl().GetSelectedCount();i++)
{
blah = GetListCtrl().GetNextItem(i, LVNI_SELECTED);
GetListCtrl().SetItemState(blah, 0, LVIS_SELECTED | LVIS_FOCUSED);
}
if(colnum > 0)
{
if( GetWindowLong(m_hWnd, GWL_STYLE) & LVS_EDITLABELS )
EditSubLabel( index, colnum );
}
else
{
GetListCtrl().SetItemState( index, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
}
}
}
void CMetaView::OnEndlabeledit(NMHDR* pNMHDR, LRESULT* pResult)
{
LV_DISPINFO *plvDispInfo = (LV_DISPINFO *)pNMHDR;
LV_ITEM *plvItem = &plvDispInfo->item;
*pResult = 0;
CInquisitorDoc* pDoc;
WINI::IMetadataNode *meta;
//pDoc functions call update so no need to set pResult to 1.
//but we need to reset manually (remove the invalid new item) if it fails ...
if(plvItem->pszText != NULL)
{
if(0 != strcmp(plvItem->pszText, ""))
{
pDoc = (CInquisitorDoc*)GetDocument();
if(plvItem->iSubItem == 0)
{
//pDoc->AddNewMetadata(plvItem->pszText, "");
EditSubLabel(plvItem->iItem, 1);
}else
{
//meta = (WINI::IMetadataNode*)(pDoc->GetCurrentNode()->GetChild(m_nRedirector[plvItem->iItem]));
//if(0 != strcmp(meta->GetValue(), plvItem->pszText))
// pDoc->SetMetadataValue(meta, plvItem->pszText);
}
}else
{
if(plvItem->iSubItem == 0)
GetListCtrl().DeleteItem(plvItem->iItem);
}
}
}
int CMetaView::HitTestEx(CPoint &point, int *col) const
{
CListCtrl& list = GetListCtrl();
int colnum = 0;
int row = list.HitTest( point, NULL );
if( col ) *col = 0;
// Make sure that the ListView is in LVS_REPORT
if((GetWindowLong(m_hWnd, GWL_STYLE) & LVS_TYPEMASK) != LVS_REPORT )
return row;
// Get the top and bottom row visible
row = list.GetTopIndex();
int bottom = row + list.GetCountPerPage();
if( bottom > list.GetItemCount() )
bottom = list.GetItemCount();
// Get the number of columns
CHeaderCtrl* pHeader = (CHeaderCtrl*)list.GetDlgItem(0);
int nColumnCount = pHeader->GetItemCount();
// Loop through the visible rows
for( ;row <=bottom;row++)
{
// Get bounding rect of item and check whether point falls in it.
CRect rect;
list.GetItemRect( row, &rect, LVIR_BOUNDS );
if( rect.PtInRect(point) )
{
// Now find the column
for( colnum = 0; colnum < nColumnCount; colnum++ )
{
int colwidth = list.GetColumnWidth(colnum);
if( point.x >= rect.left
&& point.x <= (rect.left + colwidth ) )
{
if( col ) *col = colnum;
return row;
}
rect.left += colwidth;
}
}
}
return -1;
}
CEdit* CMetaView::EditSubLabel( int nItem, int nCol )
{
CListCtrl& list = GetListCtrl();
// The returned pointer should not be saved
// Make sure that the item is visible
if( !list.EnsureVisible( nItem, TRUE ) ) return NULL;
// Make sure that nCol is valid
CHeaderCtrl* pHeader = (CHeaderCtrl*)list.GetDlgItem(0);
int nColumnCount = pHeader->GetItemCount();
if( nCol >= nColumnCount || list.GetColumnWidth(nCol) < 5 )
return NULL;
// Get the column offset
int offset = 0;
for( int i = 0; i < nCol; i++ )
offset += list.GetColumnWidth( i );
CRect rect;
list.GetItemRect( nItem, &rect, LVIR_BOUNDS );
// Now scroll if we need to expose the column
CRect rcClient;
list.GetClientRect( &rcClient );
if( offset + rect.left < 0 || offset + rect.left > rcClient.right )
{
CSize size;
size.cx = offset + rect.left;
size.cy = 0;
list.Scroll( size );
rect.left -= size.cx;
}
// Get Column alignment
LV_COLUMN lvcol;
lvcol.mask = LVCF_FMT;
list.GetColumn( nCol, &lvcol );
DWORD dwStyle ;
if((lvcol.fmt&LVCFMT_JUSTIFYMASK) == LVCFMT_LEFT)
dwStyle = ES_LEFT;
else if((lvcol.fmt&LVCFMT_JUSTIFYMASK) == LVCFMT_RIGHT)
dwStyle = ES_RIGHT;
else dwStyle = ES_CENTER;
//rect.left += offset+4;
//rect.right = rect.left + list.GetColumnWidth( nCol ) - 3 ;
rect.left += offset;
rect.right = rect.left + list.GetColumnWidth( nCol );
if( rect.right > rcClient.right) rect.right = rcClient.right;
dwStyle |= WS_BORDER|WS_CHILD|WS_VISIBLE|ES_AUTOHSCROLL;
CEdit *pEdit = new CCEdit(nItem, nCol, list.GetItemText( nItem, nCol ));
pEdit->Create( dwStyle, rect, this, IDC_BLAH);
return pEdit;
}
void CMetaView::OnNewMeta()
{
CListCtrl& list = GetListCtrl();
DWORD dwStyle = list.GetStyle() & LVS_TYPEMASK;
if(!(dwStyle && LVS_REPORT))
list.ModifyStyle(LVS_TYPEMASK, LVS_REPORT);
int count = list.GetItemCount();
int position = list.InsertItem(count, "", 3);
CEdit* edit = EditSubLabel(position, 0);
}
void CMetaView::OnUpdateNewMeta(CCmdUI* pCmdUI)
{
}
void CMetaView::OnRclick(NMHDR* pNMHDR, LRESULT* pResult)
{
*pResult = 0;
CListCtrl& list = GetListCtrl();
int count = list.GetSelectedCount();
// POSITION POS = list.GetFirstSelectedItemPosition();
// int i = list.GetNextSelectedItem(POS);
//CInquisitorDoc* pDoc = GetDocument();
// WINI::INode* node = pDoc->GetCurrentNode();
// node = node->GetChild(m_nRedirector[i]);
CMenu menu;
POINT pt;
GetCursorPos(&pt);
menu.CreatePopupMenu();
if(0 == count)
menu.AppendMenu(MF_ENABLED, ID_NEW_META, "Add Metadata");
else
menu.AppendMenu(MF_ENABLED, ID_DELETE, "Delete");
menu.TrackPopupMenu(TPM_LEFTALIGN, pt.x, pt.y,this);
} | bsd-3-clause |
rfavillejr/Thinktecture.IdentityServer.v2 | src/Libraries/Thinktecture.IdentityServer.Core/Models/DelegationSetting.cs | 869 | /*
* Copyright (c) Dominick Baier, Brock Allen. All rights reserved.
* see license.txt
*/
using System;
using System.ComponentModel.DataAnnotations;
namespace Thinktecture.IdentityServer.Models
{
public class DelegationSetting
{
[Required]
[Display(ResourceType = typeof (Resources.Models.DelegationSetting), Name = "Description", Description = "DescriptionDescription")]
public string Description { get; set; }
[Required]
[Display(ResourceType = typeof (Resources.Models.DelegationSetting), Name = "UserName", Description = "UserNameDescription")]
public string UserName { get; set; }
[Required]
[Display(ResourceType = typeof (Resources.Models.DelegationSetting), Name = "Realm", Description = "RealmDescription")]
[AbsoluteUri]
public Uri Realm { get; set; }
}
}
| bsd-3-clause |
nmittler/grpc-java | examples/android/routeguide/app/src/main/java/io/grpc/routeguideexample/RouteGuideUtil.java | 2421 | /*
* Copyright 2015, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.grpc.routeguideexample;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.List;
/**
* Common utilities for the RouteGuide demo.
*/
public class RouteGuideUtil {
private static final double COORD_FACTOR = 1e7;
/**
* Gets the latitude for the given point.
*/
public static double getLatitude(Point location) {
return location.getLatitude() / COORD_FACTOR;
}
/**
* Gets the longitude for the given point.
*/
public static double getLongitude(Point location) {
return location.getLongitude() / COORD_FACTOR;
}
/**
* Indicates whether the given feature exists (i.e. has a valid name).
*/
public static boolean exists(Feature feature) {
return feature != null && !feature.getName().isEmpty();
}
}
| bsd-3-clause |
vronin/fastlane | fastlane/lib/fastlane/actions/commit_version_bump.rb | 10821 | module Fastlane
module Actions
# Commits the current changes in the repo as a version bump, checking to make sure only files which contain version information have been changed.
class CommitVersionBumpAction < Action
def self.run(params)
require 'xcodeproj'
require 'pathname'
require 'set'
require 'shellwords'
xcodeproj_path = params[:xcodeproj] ? File.expand_path(File.join('.', params[:xcodeproj])) : nil
# find the repo root path
repo_path = Actions.sh('git rev-parse --show-toplevel').strip
repo_pathname = Pathname.new(repo_path)
if xcodeproj_path
# ensure that the xcodeproj passed in was OK
UI.user_error!("Could not find the specified xcodeproj: #{xcodeproj_path}") unless File.directory?(xcodeproj_path)
else
all_xcodeproj_paths = Dir[File.expand_path(File.join(repo_path, '**/*.xcodeproj'))]
# find an xcodeproj (ignoring the Cocoapods one)
xcodeproj_paths = Fastlane::Actions.ignore_cocoapods_path(all_xcodeproj_paths)
# no projects found: error
UI.user_error!('Could not find a .xcodeproj in the current repository\'s working directory.') if xcodeproj_paths.count == 0
# too many projects found: error
if xcodeproj_paths.count > 1
relative_projects = xcodeproj_paths.map { |e| Pathname.new(e).relative_path_from(repo_pathname).to_s }.join("\n")
UI.user_error!("Found multiple .xcodeproj projects in the current repository's working directory. Please specify your app's main project: \n#{relative_projects}")
end
# one project found: great
xcodeproj_path = xcodeproj_paths.first
end
# find the pbxproj path, relative to git directory
pbxproj_pathname = Pathname.new(File.join(xcodeproj_path, 'project.pbxproj'))
pbxproj_path = pbxproj_pathname.relative_path_from(repo_pathname).to_s
# find the info_plist files
# rubocop:disable Style/MultilineBlockChain
project = Xcodeproj::Project.open(xcodeproj_path)
info_plist_files = project.objects.select do |object|
object.isa == 'XCBuildConfiguration'
end.map(&:to_hash).map do |object_hash|
object_hash['buildSettings']
end.select do |build_settings|
build_settings.key?('INFOPLIST_FILE')
end.map do |build_settings|
build_settings['INFOPLIST_FILE']
end.uniq.map do |info_plist_path|
Pathname.new(File.expand_path(File.join(xcodeproj_path, '..', info_plist_path))).relative_path_from(repo_pathname).to_s
end
# rubocop:enable Style/MultilineBlockChain
# Removes .plist files that matched the given expression in the 'ignore' parameter
ignore_expression = params[:ignore]
if ignore_expression
info_plist_files.reject! do |info_plist_file|
info_plist_file.match(ignore_expression)
end
end
# create our list of files that we expect to have changed, they should all be relative to the project root, which should be equal to the git workdir root
expected_changed_files = []
expected_changed_files << pbxproj_path
expected_changed_files << info_plist_files
if params[:settings]
settings_plists_from_param(params[:settings]).each do |file|
settings_file_pathname = Pathname.new settings_bundle_file_path(project, file)
expected_changed_files << settings_file_pathname.relative_path_from(repo_pathname).to_s
end
end
expected_changed_files.flatten!.uniq!
# get the list of files that have actually changed in our git workdir
git_dirty_files = Actions.sh('git diff --name-only HEAD').split("\n") + Actions.sh('git ls-files --other --exclude-standard').split("\n")
# little user hint
UI.user_error!("No file changes picked up. Make sure you run the `increment_build_number` action first.") if git_dirty_files.empty?
# check if the files changed are the ones we expected to change (these should be only the files that have version info in them)
changed_files_as_expected = (Set.new(git_dirty_files.map(&:downcase)).subset? Set.new(expected_changed_files.map(&:downcase)))
unless changed_files_as_expected
unless params[:force]
error = [
"Found unexpected uncommitted changes in the working directory. Expected these files to have ",
"changed: \n#{expected_changed_files.join("\n")}.\nBut found these actual changes: ",
"#{git_dirty_files.join("\n")}.\nMake sure you have cleaned up the build artifacts and ",
"are only left with the changed version files at this stage in your lane, and don't touch the ",
"working directory while your lane is running. You can also use the :force option to bypass this ",
"check, and always commit a version bump regardless of the state of the working directory."
].join("\n")
UI.user_error!(error)
end
end
# get the absolute paths to the files
git_add_paths = expected_changed_files.map do |path|
updated = path.gsub("$(SRCROOT)", ".").gsub("${SRCROOT}", ".")
File.expand_path(File.join(repo_pathname, updated))
end
# then create a commit with a message
Actions.sh("git add #{git_add_paths.map(&:shellescape).join(' ')}")
begin
build_number = Actions.lane_context[Actions::SharedValues::BUILD_NUMBER]
params[:message] ||= (build_number ? "Version Bump to #{build_number}" : "Version Bump")
Actions.sh("git commit -m '#{params[:message]}'")
UI.success("Committed \"#{params[:message]}\" 💾.")
rescue => ex
UI.error(ex)
UI.important("Didn't commit any changes.")
end
end
def self.description
"Creates a 'Version Bump' commit. Run after `increment_build_number`"
end
def self.available_options
[
FastlaneCore::ConfigItem.new(key: :message,
env_name: "FL_COMMIT_BUMP_MESSAGE",
description: "The commit message when committing the version bump",
optional: true),
FastlaneCore::ConfigItem.new(key: :xcodeproj,
env_name: "FL_BUILD_NUMBER_PROJECT",
description: "The path to your project file (Not the workspace). If you have only one, this is optional",
optional: true,
verify_block: proc do |value|
UI.user_error!("Please pass the path to the project, not the workspace") if value.end_with? ".xcworkspace"
UI.user_error!("Could not find Xcode project") unless File.exist?(value)
end),
FastlaneCore::ConfigItem.new(key: :force,
env_name: "FL_FORCE_COMMIT",
description: "Forces the commit, even if other files than the ones containing the version number have been modified",
optional: true,
default_value: false,
is_string: false),
FastlaneCore::ConfigItem.new(key: :settings,
env_name: "FL_COMMIT_INCLUDE_SETTINGS",
description: "Include Settings.bundle/Root.plist with version bump",
optional: true,
default_value: false,
is_string: false),
FastlaneCore::ConfigItem.new(key: :ignore,
description: "A regular expression used to filter matched plist files to be modified",
optional: true,
default_value: nil,
is_string: false)
]
end
def self.details
[
"This action will create a 'Version Bump' commit in your repo. Useful in conjunction with `increment_build_number`.",
"",
"It checks the repo to make sure that only the relevant files have changed, these are the files that `increment_build_number` (`agvtool`) touches:",
"- All .plist files",
"- The `.xcodeproj/project.pbxproj` file",
"",
"Then commits those files to the repo.",
"",
"Customise the message with the `:message` option, defaults to 'Version Bump'",
"",
"If you have other uncommitted changes in your repo, this action will fail. If you started off in a clean repo, and used the _ipa_ and or _sigh_ actions, then you can use the `clean_build_artifacts` action to clean those temporary files up before running this action."
].join("\n")
end
def self.author
"lmirosevic"
end
def self.is_supported?(platform)
[:ios, :mac].include? platform
end
def self.example_code
[
'commit_version_bump',
'commit_version_bump(
message: "Version Bump", # create a commit with a custom message
xcodeproj: "./path/to/MyProject.xcodeproj", # optional, if you have multiple Xcode project files, you must specify your main project here
)'
]
end
def self.category
:source_control
end
class << self
def settings_plists_from_param(param)
if param.kind_of? String
# commit_version_bump xcodeproj: "MyProject.xcodeproj", settings: "About.plist"
return [param]
elsif param.kind_of? Array
# commit_version_bump xcodeproj: "MyProject.xcodeproj", settings: [ "Root.plist", "About.plist" ]
return param
end
# commit_version_bump xcodeproj: "MyProject.xcodeproj", settings: true # Root.plist
["Root.plist"]
end
def settings_bundle_file_path(project, settings_file_name)
settings_bundle = project.files.find { |f| f.path =~ /Settings.bundle/ }
raise "No Settings.bundle in project" if settings_bundle.nil?
project_parent = File.dirname project.path
File.join(project_parent, settings_bundle.path, settings_file_name)
end
end
end
end
end
| mit |
rdhelms/nightwatch-kittens | test/src/api/protocol/testSource.js | 1526 | var assert = require('assert');
var common = require('../../../common.js');
var MockServer = require('../../../lib/mockserver.js');
var Nightwatch = require('../../../lib/nightwatch.js');
var MochaTest = require('../../../lib/mochatest.js');
module.exports = MochaTest.add('client.source', {
beforeEach: function () {
this.client = Nightwatch.client();
this.protocol = common.require('api/protocol.js')(this.client);
},
'client.source() get command' : function(done) {
var command = this.protocol.source(function() {});
assert.equal(command.request.method, 'GET');
assert.equal(command.request.path, '/wd/hub/session/1352110219202/source');
command.on('result', function() {
done();
});
},
'client.source() get command callback' : function(done) {
MockServer.addMock({
url : "/wd/hub/session/1352110219202/source",
response: "{\"name\":\"getPageSource\",\"sessionId\":\"1352110219202\",\"status\":0,\"value\":\"<!DOCTYPE html><html><head><title>NightwatchJS</title></head><body><div id='some_id'>some div content</div></body></html>\"}",
statusCode : 200,
method: "GET"
});
this.protocol.source(function(result) {
assert.ok(true, 'Get callback called');
assert.equal(result.status, 0);
assert.equal(result.name, 'getPageSource');
assert.ok(result.value.indexOf('<title>NightwatchJS</title>') > -1, 'Found <title> tag in response');
assert.ok(true, 'GET source callback called');
done();
});
}
});
| mit |
luisbarrancos/appleseed | src/appleseed/foundation/meta/tests/test_fp.cpp | 7742 |
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// appleseed.foundation headers.
#include "foundation/math/fp.h"
#include "foundation/utility/test.h"
using namespace foundation;
TEST_SUITE(Foundation_Math_FP_Float)
{
const volatile float Zero = 0.0f;
TEST_CASE(PosInf_ReturnsPositiveInfinite)
{
const float PositiveInfinity = 1.0f / Zero;
EXPECT_EQ(PositiveInfinity, FP<float>::pos_inf());
}
TEST_CASE(NegInf_ReturnsNegativeInfinite)
{
const float NegativeInfinity = -1.0f / Zero;
EXPECT_EQ(NegativeInfinity, FP<float>::neg_inf());
}
TEST_CASE(Sign_GivenPositiveZero_ReturnsZero)
{
EXPECT_EQ(0, FP<float>::sign(+0.0f));
}
TEST_CASE(Sign_GivenNegativeZero_ReturnsOne)
{
EXPECT_EQ(1, FP<float>::sign(-0.0f));
}
TEST_CASE(Sign_GivenStrictlyPositiveValue_ReturnsZero)
{
EXPECT_EQ(0, FP<float>::sign(+42.0f));
}
TEST_CASE(Sign_GivenStrictlyNegativeValue_ReturnsOne)
{
EXPECT_EQ(1, FP<float>::sign(-42.0f));
}
TEST_CASE(IsSNan_GivenSNan_ReturnsTrue)
{
EXPECT_TRUE(FP<float>::is_snan(FP<float>::snan()));
}
TEST_CASE(IsQNan_GivenQNan_ReturnsTrue)
{
EXPECT_TRUE(FP<float>::is_qnan(FP<float>::qnan()));
}
TEST_CASE(Shift_GivenZeroAndShiftOfZero_ReturnsZero)
{
EXPECT_EQ(+0.0f, shift(+0.0f, 0));
EXPECT_EQ(-0.0F, shift(-0.0f, 0));
}
TEST_CASE(Shift_GivenZeroAndShiftOfPlusOne_ReturnsPosMin)
{
EXPECT_EQ(FP<float>::pos_min(), shift(0.0f, +1));
}
TEST_CASE(Shift_GivenZeroAndShiftOfMinusOne_ReturnsNegMin)
{
EXPECT_EQ(FP<float>::neg_min(), shift(0.0f, -1));
}
TEST_CASE(Shift_GivenOneAndShiftOfPlusOne_ReturnsValueSlightlyGreaterThanOne)
{
const float result = shift(1.0f, +1);
EXPECT_GT(1.0f, result);
EXPECT_FEQ(1.0f, result);
}
TEST_CASE(Shift_GivenOneAndShiftOfMinusOne_ReturnsValueSlightlyLesserThanOne)
{
const float result = shift(1.0f, -1);
EXPECT_LT(1.0f, result);
EXPECT_FEQ(1.0f, result);
}
TEST_CASE(Shift_GivenPosMinAndShiftOfMinusOne_ReturnsNegMin)
{
EXPECT_EQ(FP<float>::neg_min(), shift(FP<float>::pos_min(), -1));
}
TEST_CASE(Shift_GivenPosMinSuccessorAndShiftOfMinusTwo_ReturnsNegMin)
{
const float succ_pos_min = shift(FP<float>::pos_min(), 1);
EXPECT_EQ(FP<float>::neg_min(), shift(succ_pos_min, -2));
}
TEST_CASE(Shift_GivenNegMinAndShiftOfPlusOne_ReturnsPosMin)
{
EXPECT_EQ(FP<float>::pos_min(), shift(FP<float>::neg_min(), +1));
}
TEST_CASE(Shift_GivenNegMinPredecessorAndShiftOfPlusTwo_ReturnsPosMin)
{
const float pred_neg_min = shift(FP<float>::neg_min(), -1);
EXPECT_EQ(FP<float>::pos_min(), shift(pred_neg_min, +2));
}
TEST_CASE(Shift_GivenPosInfAndShiftOnePlusOne_ReturnsPosInf)
{
EXPECT_EQ(FP<float>::pos_inf(), shift(FP<float>::pos_inf(), +1));
}
TEST_CASE(Shift_GivenNegInfAndShiftOneMinusOne_ReturnsNegInf)
{
EXPECT_EQ(FP<float>::neg_inf(), shift(FP<float>::neg_inf(), -1));
}
TEST_CASE(Sign_GivenNegativeAndPositiveFloats_ReturnsOneAndZero)
{
const float Negative = -0.33f;
const float Positive = +0.33f;
EXPECT_EQ(1, FP<float>::sign(Negative));
EXPECT_EQ(0, FP<float>::sign(Positive));
}
TEST_CASE(Exponent_GivenFloat_ReturnsValidExponent)
{
// https://www.h-schmidt.net/FloatConverter/IEEE754.html used for
// exponent calculation.
const float Value = -0.01612f;
EXPECT_EQ(121, FP<float>::exponent(Value));
}
TEST_CASE(Mantissa_GivenFloat_ReturnsValidMantissa)
{
// https://www.h-schmidt.net/FloatConverter/IEEE754.html used for
// mantissa calculation.
const float Value = 0.1234598821f;
EXPECT_EQ(8181897, FP<float>::mantissa(Value));
}
TEST_CASE(Construct_GivenSignExponentMantissaOfAFloat_ReturnsTheSameNumber)
{
const float Initial = -0.15f;
EXPECT_EQ(
Initial,
FP<float>::construct(
FP<float>::sign(Initial),
FP<float>::exponent(Initial),
FP<float>::mantissa(Initial)));
}
}
TEST_SUITE(Foundation_Math_FP_Double)
{
const volatile double Zero = 0.0;
TEST_CASE(PosInf_ReturnsPositiveInfinite)
{
const double PositiveInfinity = 1.0 / Zero;
EXPECT_EQ(PositiveInfinity, FP<double>::pos_inf());
}
TEST_CASE(NegInf_ReturnsNegativeInfinite)
{
const double NegativeInfinity = -1.0 / Zero;
EXPECT_EQ(NegativeInfinity, FP<double>::neg_inf());
}
TEST_CASE(Sign_GivenPositiveZero_ReturnsZero)
{
EXPECT_EQ(0, FP<double>::sign(+0.0));
}
TEST_CASE(Sign_GivenNegativeZero_ReturnsOne)
{
EXPECT_EQ(1, FP<double>::sign(-0.0));
}
TEST_CASE(Sign_GivenStrictlyPositiveValue_ReturnsZero)
{
EXPECT_EQ(0, FP<double>::sign(+42.0));
}
TEST_CASE(Sign_GivenStrictlyNegativeValue_ReturnsOne)
{
EXPECT_EQ(1, FP<double>::sign(-42.0));
}
TEST_CASE(IsSNan_GivenSNan_ReturnsTrue)
{
EXPECT_TRUE(FP<double>::is_snan(FP<double>::snan()));
}
TEST_CASE(IsQNan_GivenQNan_ReturnsTrue)
{
EXPECT_TRUE(FP<double>::is_qnan(FP<double>::qnan()));
}
TEST_CASE(Sign_GivenNegativeAndPositiveFloats_ReturnsOneAndZero)
{
const double Negative = -0.33;
const double Positive = +0.33;
EXPECT_EQ(1, FP<double>::sign(Negative));
EXPECT_EQ(0, FP<double>::sign(Positive));
}
TEST_CASE(Exponent_GivenFloat_ReturnsValidExponent)
{
const double Value = -0.01612;
EXPECT_EQ(1017, FP<double>::exponent(Value));
}
TEST_CASE(Mantissa_GivenFloat_ReturnsValidMantissa)
{
const double Value = 0.1234598821;
EXPECT_EQ(4392622436961750, FP<double>::mantissa(Value));
}
TEST_CASE(Construct_GivenSignExponentMantissaOfAFloat_ReturnsTheSameNumber)
{
const double Initial = -0.15;
EXPECT_EQ(
Initial,
FP<double>::construct(
FP<double>::sign(Initial),
FP<double>::exponent(Initial),
FP<double>::mantissa(Initial)));
}
}
| mit |
bitxpert/marketform-client | config/environments/production.rb | 2489 | OauthClientDemo::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
| mit |
fgascon/living-room-display | node_modules/browserify/node_modules/browser-builtins/node_modules/crypto-browserify/index.js | 2778 | var Buffer = require('buffer').Buffer
var sha = require('./sha')
var sha256 = require('./sha256')
var rng = require('./rng')
var md5 = require('./md5')
var algorithms = {
sha1: {
hex: sha.hex_sha1,
base64: sha.b64_sha1,
binary: sha.str_sha1
},
sha256: {
hex: sha256.hex_sha256,
base64: sha256.b64_sha256,
binary: sha256.str_sha256
},
md5: {
hex: md5.hex_md5,
base64: md5.b64_md5,
binary: md5.bin_md5
}
}
var algorithmsHmac = {
sha1: {
hex: sha.hex_hmac_sha1,
base64: sha.b64_hmac_sha1,
binary: sha.str_hmac_sha1
},
sha256: {
hex: sha256.hex_hmac_sha256,
base64: sha256.b64_hmac_sha256,
binary: sha256.str_hmac_sha256
},
md5: {
hex: md5.hex_hmac_md5,
base64: md5.b64_hmac_md5,
binary: md5.bin_hmac_md5
}
}
function error () {
var m = [].slice.call(arguments).join(' ')
throw new Error([
m,
'we accept pull requests',
'http://github.com/dominictarr/crypto-browserify'
].join('\n'))
}
exports.createHash = function (alg) {
alg = alg || 'sha1'
if(!algorithms[alg])
error('algorithm:', alg, 'is not yet supported')
var s = ''
var _alg = algorithms[alg]
return {
update: function (data) {
s += data
return this
},
digest: function (enc) {
enc = enc || 'binary'
var fn
if(!(fn = _alg[enc]))
error('encoding:', enc , 'is not yet supported for algorithm', alg)
var r = fn(s)
s = null //not meant to use the hash after you've called digest.
return r
}
}
}
exports.createHmac = function (alg, key) {
if (!algorithmsHmac[alg])
error('algorithm:', alg, 'is not yet supported')
if (typeof key != 'string')
key = key.toString('binary')
var s = ''
var _alg = algorithmsHmac[alg]
return {
update: function (data) {
s += data
return this
},
digest: function (enc) {
enc = enc || 'binary'
var fn
if (!(fn = _alg[enc]))
error('encoding:', enc, 'is not yet support for algorithm', alg)
var r = fn(key, s)
s = null
return r
}
}
}
exports.randomBytes = function(size, callback) {
if (callback && callback.call) {
try {
callback.call(this, undefined, new Buffer(rng(size)));
} catch (err) { callback(err); }
} else {
return new Buffer(rng(size));
}
}
function each(a, f) {
for(var i in a)
f(a[i], i)
}
// the least I can do is make error messages for the rest of the node.js/crypto api.
each(['createCredentials'
, 'createCipher'
, 'createCipheriv'
, 'createDecipher'
, 'createDecipheriv'
, 'createSign'
, 'createVerify'
, 'createDiffieHellman'
, 'pbkdf2'], function (name) {
exports[name] = function () {
error('sorry,', name, 'is not implemented yet')
}
})
| mit |
Boter/SIT | tests/UnitTests/Serialization.cpp | 12900 | // Copyright (c) 2011-2016 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "gtest/gtest.h"
#include "Common/StdInputStream.h"
#include "Common/StdOutputStream.h"
#include "Serialization/BinaryInputStreamSerializer.h"
#include "Serialization/BinaryOutputStreamSerializer.h"
#include "Serialization/BinarySerializationTools.h"
using namespace Common;
using namespace CryptoNote;
TEST(BinarySerializer, uint16) {
std::stringstream ss;
uint16_t u16 = 0xfeff;
uint32_t u32 = 0x3fddfd48;
{
StdOutputStream os(ss);
BinaryOutputStreamSerializer s(os);
s(u32, "u32");
s(u16, "u16");
}
{
StdInputStream is(ss);
BinaryInputStreamSerializer s(is);
uint32_t t32 = 0;
uint16_t t16 = 0;
s(t32, "u32");
s(t16, "u16");
ASSERT_EQ(u32, t32);
ASSERT_EQ(u16, t16);
}
}
//#include <cstring>
//#include <cstdint>
//#include <cstdio>
//#include <iostream>
//#include <vector>
//#include <boost/foreach.hpp>
//#include "CryptoNoteCore/CryptoNoteBasic.h"
//#include "CryptoNoteCore/CryptoNoteBasicImpl.h"
//#include "Serialization/serialization.h"
//#include "Serialization/binary_archive.h"
//#include "Serialization/json_archive.h"
//#include "Serialization/variant.h"
//#include "Serialization/vector.h"
//#include "Serialization/binary_utils.h"
//#include "gtest/gtest.h"
//using namespace std;
//
//struct Struct
//{
// int32_t a;
// int32_t b;
// char blob[8];
//};
//
//template <class Archive>
//struct serializer<Archive, Struct>
//{
// static bool serialize(Archive &ar, Struct &s) {
// ar.begin_object();
// ar.tag("a");
// ar.serialize_int(s.a);
// ar.tag("b");
// ar.serialize_int(s.b);
// ar.tag("blob");
// ar.serialize_blob(s.blob, sizeof(s.blob));
// ar.end_object();
// return true;
// }
//};
//
//struct Struct1
//{
// vector<boost::variant<Struct, int32_t>> si;
// vector<int16_t> vi;
//
// BEGIN_SERIALIZE_OBJECT()
// FIELD(si)
// FIELD(vi)
// END_SERIALIZE()
// /*template <bool W, template <bool> class Archive>
// bool do_serialize(Archive<W> &ar)
// {
// ar.begin_object();
// ar.tag("si");
// ::do_serialize(ar, si);
// ar.tag("vi");
// ::do_serialize(ar, vi);
// ar.end_object();
// }*/
//};
//
//struct Blob
//{
// uint64_t a;
// uint32_t b;
//
// bool operator==(const Blob& rhs) const
// {
// return a == rhs.a;
// }
//};
//
//VARIANT_TAG(binary_archive, Struct, 0xe0);
//VARIANT_TAG(binary_archive, int, 0xe1);
//VARIANT_TAG(json_archive, Struct, "struct");
//VARIANT_TAG(json_archive, int, "int");
//
//BLOB_SERIALIZER(Blob);
//
//bool try_parse(const string &blob)
//{
// Struct1 s1;
// return serialization::parse_binary(blob, s1);
//}
//
//TEST(Serialization, BinaryArchiveInts) {
// uint64_t x = 0xff00000000, x1;
//
// ostringstream oss;
// binary_archive<true> oar(oss);
// oar.serialize_int(x);
// ASSERT_TRUE(oss.good());
// ASSERT_EQ(8, oss.str().size());
// ASSERT_EQ(string("\0\0\0\0\xff\0\0\0", 8), oss.str());
//
// istringstream iss(oss.str());
// binary_archive<false> iar(iss);
// iar.serialize_int(x1);
// ASSERT_EQ(8, iss.tellg());
// ASSERT_TRUE(iss.good());
//
// ASSERT_EQ(x, x1);
//}
//
//TEST(Serialization, BinaryArchiveVarInts) {
// uint64_t x = 0xff00000000, x1;
//
// ostringstream oss;
// binary_archive<true> oar(oss);
// oar.serialize_varint(x);
// ASSERT_TRUE(oss.good());
// ASSERT_EQ(6, oss.str().size());
// ASSERT_EQ(string("\x80\x80\x80\x80\xF0\x1F", 6), oss.str());
//
// istringstream iss(oss.str());
// binary_archive<false> iar(iss);
// iar.serialize_varint(x1);
// ASSERT_TRUE(iss.good());
// ASSERT_EQ(x, x1);
//}
//
//TEST(Serialization, Test1) {
// ostringstream str;
// binary_archive<true> ar(str);
//
// Struct1 s1;
// s1.si.push_back(0);
// {
// Struct s;
// s.a = 5;
// s.b = 65539;
// std::memcpy(s.blob, "12345678", 8);
// s1.si.push_back(s);
// }
// s1.si.push_back(1);
// s1.vi.push_back(10);
// s1.vi.push_back(22);
//
// string blob;
// ASSERT_TRUE(serialization::dump_binary(s1, blob));
// ASSERT_TRUE(try_parse(blob));
//
// ASSERT_EQ('\xE0', blob[6]);
// blob[6] = '\xE1';
// ASSERT_FALSE(try_parse(blob));
// blob[6] = '\xE2';
// ASSERT_FALSE(try_parse(blob));
//}
//
//TEST(Serialization, Overflow) {
// Blob x = { 0xff00000000 };
// Blob x1;
//
// string blob;
// ASSERT_TRUE(serialization::dump_binary(x, blob));
// ASSERT_EQ(sizeof(Blob), blob.size());
//
// ASSERT_TRUE(serialization::parse_binary(blob, x1));
// ASSERT_EQ(x, x1);
//
// vector<Blob> bigvector;
// ASSERT_FALSE(serialization::parse_binary(blob, bigvector));
// ASSERT_EQ(0, bigvector.size());
//}
//
//TEST(Serialization, serializes_vector_uint64_as_varint)
//{
// std::vector<uint64_t> v;
// string blob;
//
// ASSERT_TRUE(serialization::dump_binary(v, blob));
// ASSERT_EQ(1, blob.size());
//
// // +1 byte
// v.push_back(0);
// ASSERT_TRUE(serialization::dump_binary(v, blob));
// ASSERT_EQ(2, blob.size());
//
// // +1 byte
// v.push_back(1);
// ASSERT_TRUE(serialization::dump_binary(v, blob));
// ASSERT_EQ(3, blob.size());
//
// // +2 bytes
// v.push_back(0x80);
// ASSERT_TRUE(serialization::dump_binary(v, blob));
// ASSERT_EQ(5, blob.size());
//
// // +2 bytes
// v.push_back(0xFF);
// ASSERT_TRUE(serialization::dump_binary(v, blob));
// ASSERT_EQ(7, blob.size());
//
// // +2 bytes
// v.push_back(0x3FFF);
// ASSERT_TRUE(serialization::dump_binary(v, blob));
// ASSERT_EQ(9, blob.size());
//
// // +3 bytes
// v.push_back(0x40FF);
// ASSERT_TRUE(serialization::dump_binary(v, blob));
// ASSERT_EQ(12, blob.size());
//
// // +10 bytes
// v.push_back(0xFFFFFFFFFFFFFFFF);
// ASSERT_TRUE(serialization::dump_binary(v, blob));
// ASSERT_EQ(22, blob.size());
//}
//
//TEST(Serialization, serializes_vector_int64_as_fixed_int)
//{
// std::vector<int64_t> v;
// string blob;
//
// ASSERT_TRUE(serialization::dump_binary(v, blob));
// ASSERT_EQ(1, blob.size());
//
// // +8 bytes
// v.push_back(0);
// ASSERT_TRUE(serialization::dump_binary(v, blob));
// ASSERT_EQ(9, blob.size());
//
// // +8 bytes
// v.push_back(1);
// ASSERT_TRUE(serialization::dump_binary(v, blob));
// ASSERT_EQ(17, blob.size());
//
// // +8 bytes
// v.push_back(0x80);
// ASSERT_TRUE(serialization::dump_binary(v, blob));
// ASSERT_EQ(25, blob.size());
//
// // +8 bytes
// v.push_back(0xFF);
// ASSERT_TRUE(serialization::dump_binary(v, blob));
// ASSERT_EQ(33, blob.size());
//
// // +8 bytes
// v.push_back(0x3FFF);
// ASSERT_TRUE(serialization::dump_binary(v, blob));
// ASSERT_EQ(41, blob.size());
//
// // +8 bytes
// v.push_back(0x40FF);
// ASSERT_TRUE(serialization::dump_binary(v, blob));
// ASSERT_EQ(49, blob.size());
//
// // +8 bytes
// v.push_back(0xFFFFFFFFFFFFFFFF);
// ASSERT_TRUE(serialization::dump_binary(v, blob));
// ASSERT_EQ(57, blob.size());
//}
//
//namespace
//{
// template<typename T>
// std::vector<T> linearize_vector2(const std::vector< std::vector<T> >& vec_vec)
// {
// std::vector<T> res;
// BOOST_FOREACH(const auto& vec, vec_vec)
// {
// res.insert(res.end(), vec.begin(), vec.end());
// }
// return res;
// }
//}
//
//TEST(Serialization, serializes_transacion_signatures_correctly)
//{
// using namespace CryptoNote;
//
// Transaction tx;
// Transaction tx1;
// string blob;
//
// // Empty tx
// tx.clear();
// ASSERT_TRUE(serialization::dump_binary(tx, blob));
// ASSERT_EQ(5, blob.size()); // 5 bytes + 0 bytes extra + 0 bytes signatures
// ASSERT_TRUE(serialization::parse_binary(blob, tx1));
// ASSERT_EQ(tx, tx1);
// ASSERT_EQ(linearize_vector2(tx.signatures), linearize_vector2(tx1.signatures));
//
// // Miner tx without signatures
// TransactionInputGenerate txin_gen1;
// txin_gen1.height = 0;
// tx.clear();
// tx.vin.push_back(txin_gen1);
// ASSERT_TRUE(serialization::dump_binary(tx, blob));
// ASSERT_EQ(7, blob.size()); // 5 bytes + 2 bytes vin[0] + 0 bytes extra + 0 bytes signatures
// ASSERT_TRUE(serialization::parse_binary(blob, tx1));
// ASSERT_EQ(tx, tx1);
// ASSERT_EQ(linearize_vector2(tx.signatures), linearize_vector2(tx1.signatures));
//
// // Miner tx with empty signatures 2nd vector
// tx.signatures.resize(1);
// ASSERT_TRUE(serialization::dump_binary(tx, blob));
// ASSERT_EQ(7, blob.size()); // 5 bytes + 2 bytes vin[0] + 0 bytes extra + 0 bytes signatures
// ASSERT_TRUE(serialization::parse_binary(blob, tx1));
// ASSERT_EQ(tx, tx1);
// ASSERT_EQ(linearize_vector2(tx.signatures), linearize_vector2(tx1.signatures));
//
// // Miner tx with one signature
// tx.signatures[0].resize(1);
// ASSERT_FALSE(serialization::dump_binary(tx, blob));
//
// // Miner tx with 2 empty vectors
// tx.signatures.resize(2);
// tx.signatures[0].resize(0);
// tx.signatures[1].resize(0);
// ASSERT_FALSE(serialization::dump_binary(tx, blob));
//
// // Miner tx with 2 signatures
// tx.signatures[0].resize(1);
// tx.signatures[1].resize(1);
// ASSERT_FALSE(serialization::dump_binary(tx, blob));
//
// // Two TransactionInputGenerate, no signatures
// tx.vin.push_back(txin_gen1);
// tx.signatures.resize(0);
// ASSERT_TRUE(serialization::dump_binary(tx, blob));
// ASSERT_EQ(9, blob.size()); // 5 bytes + 2 * 2 bytes vins + 0 bytes extra + 0 bytes signatures
// ASSERT_TRUE(serialization::parse_binary(blob, tx1));
// ASSERT_EQ(tx, tx1);
// ASSERT_EQ(linearize_vector2(tx.signatures), linearize_vector2(tx1.signatures));
//
// // Two TransactionInputGenerate, signatures vector contains only one empty element
// tx.signatures.resize(1);
// ASSERT_FALSE(serialization::dump_binary(tx, blob));
//
// // Two TransactionInputGenerate, signatures vector contains two empty elements
// tx.signatures.resize(2);
// ASSERT_TRUE(serialization::dump_binary(tx, blob));
// ASSERT_EQ(9, blob.size()); // 5 bytes + 2 * 2 bytes vins + 0 bytes extra + 0 bytes signatures
// ASSERT_TRUE(serialization::parse_binary(blob, tx1));
// ASSERT_EQ(tx, tx1);
// ASSERT_EQ(linearize_vector2(tx.signatures), linearize_vector2(tx1.signatures));
//
// // Two TransactionInputGenerate, signatures vector contains three empty elements
// tx.signatures.resize(3);
// ASSERT_FALSE(serialization::dump_binary(tx, blob));
//
// // Two TransactionInputGenerate, signatures vector contains two non empty elements
// tx.signatures.resize(2);
// tx.signatures[0].resize(1);
// tx.signatures[1].resize(1);
// ASSERT_FALSE(serialization::dump_binary(tx, blob));
//
// // A few bytes instead of signature
// tx.vin.clear();
// tx.vin.push_back(txin_gen1);
// tx.signatures.clear();
// ASSERT_TRUE(serialization::dump_binary(tx, blob));
// blob.append(std::string(sizeof(Crypto::Signature) / 2, 'x'));
// ASSERT_FALSE(serialization::parse_binary(blob, tx1));
//
// // blob contains one signature
// blob.append(std::string(sizeof(Crypto::Signature) / 2, 'y'));
// ASSERT_FALSE(serialization::parse_binary(blob, tx1));
//
// // Not enough signature vectors for all inputs
// TransactionInputToKey txin_to_key1;
// txin_to_key1.keyOffsets.resize(2);
// tx.vin.clear();
// tx.vin.push_back(txin_to_key1);
// tx.vin.push_back(txin_to_key1);
// tx.signatures.resize(1);
// tx.signatures[0].resize(2);
// ASSERT_FALSE(serialization::dump_binary(tx, blob));
//
// // Too much signatures for two inputs
// tx.signatures.resize(3);
// tx.signatures[0].resize(2);
// tx.signatures[1].resize(2);
// tx.signatures[2].resize(2);
// ASSERT_FALSE(serialization::dump_binary(tx, blob));
//
// // First signatures vector contains too little elements
// tx.signatures.resize(2);
// tx.signatures[0].resize(1);
// tx.signatures[1].resize(2);
// ASSERT_FALSE(serialization::dump_binary(tx, blob));
//
// // First signatures vector contains too much elements
// tx.signatures.resize(2);
// tx.signatures[0].resize(3);
// tx.signatures[1].resize(2);
// ASSERT_FALSE(serialization::dump_binary(tx, blob));
//
// // There are signatures for each input
// tx.signatures.resize(2);
// tx.signatures[0].resize(2);
// tx.signatures[1].resize(2);
// ASSERT_TRUE(serialization::dump_binary(tx, blob));
// ASSERT_TRUE(serialization::parse_binary(blob, tx1));
// ASSERT_EQ(tx, tx1);
// ASSERT_EQ(linearize_vector2(tx.signatures), linearize_vector2(tx1.signatures));
//
// // Blob doesn't contain enough data
// blob.resize(blob.size() - sizeof(Crypto::Signature) / 2);
// ASSERT_FALSE(serialization::parse_binary(blob, tx1));
//
// // Blob contains too much data
// blob.resize(blob.size() + sizeof(Crypto::Signature));
// ASSERT_FALSE(serialization::parse_binary(blob, tx1));
//
// // Blob contains one excess signature
// blob.resize(blob.size() + sizeof(Crypto::Signature) / 2);
// ASSERT_FALSE(serialization::parse_binary(blob, tx1));
//}
| mit |
sapk-fork/gitea | vendor/github.com/olivere/elastic/v7/search_shards.go | 7894 | // Copyright 2012-present Oliver Eilhard. All rights reserved.
// Use of this source code is governed by a MIT-license.
// See http://olivere.mit-license.org/license.txt for details.
package elastic
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/olivere/elastic/v7/uritemplates"
)
// SearchShardsService returns the indices and shards that a search request would be executed against.
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-shards.html
type SearchShardsService struct {
client *Client
pretty *bool // pretty format the returned JSON response
human *bool // return human readable values for statistics
errorTrace *bool // include the stack trace of returned errors
filterPath []string // list of filters used to reduce the response
headers http.Header // custom request-level HTTP headers
index []string
routing string
local *bool
preference string
ignoreUnavailable *bool
allowNoIndices *bool
expandWildcards string
}
// NewSearchShardsService creates a new SearchShardsService.
func NewSearchShardsService(client *Client) *SearchShardsService {
return &SearchShardsService{
client: client,
}
}
// Pretty tells Elasticsearch whether to return a formatted JSON response.
func (s *SearchShardsService) Pretty(pretty bool) *SearchShardsService {
s.pretty = &pretty
return s
}
// Human specifies whether human readable values should be returned in
// the JSON response, e.g. "7.5mb".
func (s *SearchShardsService) Human(human bool) *SearchShardsService {
s.human = &human
return s
}
// ErrorTrace specifies whether to include the stack trace of returned errors.
func (s *SearchShardsService) ErrorTrace(errorTrace bool) *SearchShardsService {
s.errorTrace = &errorTrace
return s
}
// FilterPath specifies a list of filters used to reduce the response.
func (s *SearchShardsService) FilterPath(filterPath ...string) *SearchShardsService {
s.filterPath = filterPath
return s
}
// Header adds a header to the request.
func (s *SearchShardsService) Header(name string, value string) *SearchShardsService {
if s.headers == nil {
s.headers = http.Header{}
}
s.headers.Add(name, value)
return s
}
// Headers specifies the headers of the request.
func (s *SearchShardsService) Headers(headers http.Header) *SearchShardsService {
s.headers = headers
return s
}
// Index sets the names of the indices to restrict the results.
func (s *SearchShardsService) Index(index ...string) *SearchShardsService {
s.index = append(s.index, index...)
return s
}
//A boolean value whether to read the cluster state locally in order to
//determine where shards are allocated instead of using the Master node’s cluster state.
func (s *SearchShardsService) Local(local bool) *SearchShardsService {
s.local = &local
return s
}
// Routing sets a specific routing value.
func (s *SearchShardsService) Routing(routing string) *SearchShardsService {
s.routing = routing
return s
}
// Preference specifies the node or shard the operation should be performed on (default: random).
func (s *SearchShardsService) Preference(preference string) *SearchShardsService {
s.preference = preference
return s
}
// IgnoreUnavailable indicates whether the specified concrete indices
// should be ignored when unavailable (missing or closed).
func (s *SearchShardsService) IgnoreUnavailable(ignoreUnavailable bool) *SearchShardsService {
s.ignoreUnavailable = &ignoreUnavailable
return s
}
// AllowNoIndices indicates whether to ignore if a wildcard indices
// expression resolves into no concrete indices. (This includes `_all` string
// or when no indices have been specified).
func (s *SearchShardsService) AllowNoIndices(allowNoIndices bool) *SearchShardsService {
s.allowNoIndices = &allowNoIndices
return s
}
// ExpandWildcards indicates whether to expand wildcard expression to
// concrete indices that are open, closed or both.
func (s *SearchShardsService) ExpandWildcards(expandWildcards string) *SearchShardsService {
s.expandWildcards = expandWildcards
return s
}
// buildURL builds the URL for the operation.
func (s *SearchShardsService) buildURL() (string, url.Values, error) {
// Build URL
path, err := uritemplates.Expand("/{index}/_search_shards", map[string]string{
"index": strings.Join(s.index, ","),
})
if err != nil {
return "", url.Values{}, err
}
// Add query string parameters
params := url.Values{}
if v := s.pretty; v != nil {
params.Set("pretty", fmt.Sprint(*v))
}
if v := s.human; v != nil {
params.Set("human", fmt.Sprint(*v))
}
if v := s.errorTrace; v != nil {
params.Set("error_trace", fmt.Sprint(*v))
}
if len(s.filterPath) > 0 {
params.Set("filter_path", strings.Join(s.filterPath, ","))
}
if s.preference != "" {
params.Set("preference", s.preference)
}
if s.local != nil {
params.Set("local", fmt.Sprintf("%v", *s.local))
}
if s.routing != "" {
params.Set("routing", s.routing)
}
if s.allowNoIndices != nil {
params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices))
}
if s.expandWildcards != "" {
params.Set("expand_wildcards", s.expandWildcards)
}
if s.ignoreUnavailable != nil {
params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable))
}
return path, params, nil
}
// Validate checks if the operation is valid.
func (s *SearchShardsService) Validate() error {
var invalid []string
if len(s.index) < 1 {
invalid = append(invalid, "Index")
}
if len(invalid) > 0 {
return fmt.Errorf("missing required fields: %v", invalid)
}
return nil
}
// Do executes the operation.
func (s *SearchShardsService) Do(ctx context.Context) (*SearchShardsResponse, error) {
// Check pre-conditions
if err := s.Validate(); err != nil {
return nil, err
}
// Get URL for request
path, params, err := s.buildURL()
if err != nil {
return nil, err
}
// Get HTTP response
res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
Method: "GET",
Path: path,
Params: params,
Headers: s.headers,
})
if err != nil {
return nil, err
}
// Return operation response
ret := new(SearchShardsResponse)
if err := s.client.decoder.Decode(res.Body, ret); err != nil {
return nil, err
}
return ret, nil
}
// SearchShardsResponse is the response of SearchShardsService.Do.
type SearchShardsResponse struct {
Nodes map[string]interface{} `json:"nodes"`
Indices map[string]interface{} `json:"indices"`
Shards [][]*SearchShardsResponseShardsInfo `json:"shards"`
}
type SearchShardsResponseShardsInfo struct {
Index string `json:"index"`
Node string `json:"node"`
Primary bool `json:"primary"`
Shard uint `json:"shard"`
State string `json:"state"`
AllocationId *AllocationId `json:"allocation_id,omitempty"`
RelocatingNode string `json:"relocating_node"`
ExpectedShardSizeInBytes int64 `json:"expected_shard_size_in_bytes,omitempty"`
RecoverySource *RecoverySource `json:"recovery_source,omitempty"`
UnassignedInfo *UnassignedInfo `json:"unassigned_info,omitempty"`
}
type RecoverySource struct {
Type string `json:"type"`
// TODO add missing fields here based on the Type
}
type AllocationId struct {
Id string `json:"id"`
RelocationId string `json:"relocation_id,omitempty"`
}
type UnassignedInfo struct {
Reason string `json:"reason"`
At *time.Time `json:"at,omitempty"`
FailedAttempts int `json:"failed_attempts,omitempty"`
Delayed bool `json:"delayed"`
Details string `json:"details,omitempty"`
AllocationStatus string `json:"allocation_status"`
}
| mit |
Cosmius/KanColleViewer | source/Analyzers/KanColleViewer.PluginAnalyzer/InvalidGuidMetadataAnalyzer.cs | 2503 | using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Grabacr07.KanColleViewer.PluginAnalyzer
{
/// <summary>
/// 不正な GUID の ExportMetadata を検出する DiagnosticAnalyzer です。
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class InvalidGuidMetadataAnalyzer : DiagnosticAnalyzer
{
public static readonly string DiagnosticId
= "KanColleViewer_PluginAnalyzer_InvalidGuidMetadata";
internal static readonly LocalizableString InvalidGuidMetadataMessageFormat
= new LocalizableResourceString(nameof(Resources.InvalidGuidMetadataMessageFormat), Resources.ResourceManager, typeof(Resources));
internal const string Category = "Compiler";
internal static DiagnosticDescriptor InvalidGuidMetadataRule
= new DiagnosticDescriptor(DiagnosticId, InvalidGuidMetadataMessageFormat, InvalidGuidMetadataMessageFormat, Category, DiagnosticSeverity.Warning, true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(InvalidGuidMetadataRule);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationAction(AnalyzeCompilation);
}
private static void AnalyzeCompilation(CompilationAnalysisContext context)
{
var compilation = context.Compilation;
var allPlugins = compilation.SyntaxTrees
.Select(x => x.GetCompilationUnitRoot())
.SelectMany(x => x.FindSyntax<ClassDeclarationSyntax>())
.Where(x => x.IsPluginClass())
.ToArray();
var plugins = allPlugins.Where(x => x.IsExportIPlugin()).ToArray();
foreach (var p in allPlugins)
{
var semanticModel = compilation.GetSemanticModel(p.SyntaxTree);
var syntax = p.GetGuidMetadataValueSyntax();
if (syntax == null) continue; //GUID な Metadata がない場合はスルー
// GUID として解釈できない値か、IPlugin で未定義の GUID が指定されてたらアウト
var guidMetadata = syntax.GetGuidMetadata(semanticModel);
if (!guidMetadata.HasValue
|| plugins.All(x => x.GetGuidMetadataValueSyntax()?.GetGuidMetadata(compilation.GetSemanticModel(x.SyntaxTree)) != guidMetadata))
{
context.ReportDiagnostic(Diagnostic.Create(InvalidGuidMetadataRule, p.GetLocation()));
}
}
}
}
}
| mit |
xeraseth/Rails-Mongo | config/routes.rb | 1624 | Rails.application.routes.draw do
resources :products
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
| mit |
mkaminsky11/imgurize | node_modules/blessed/lib/widgets/log.js | 1836 | /**
* log.js - log element for blessed
* Copyright (c) 2013-2015, Christopher Jeffrey and contributors (MIT License).
* https://github.com/chjj/blessed
*/
/**
* Modules
*/
var util = require('util');
var nextTick = global.setImmediate || process.nextTick.bind(process);
var helpers = require('../helpers');
var Node = require('./node');
var ScrollableText = require('./scrollabletext');
/**
* Log
*/
function Log(options) {
var self = this;
if (!(this instanceof Node)) {
return new Log(options);
}
options = options || {};
ScrollableText.call(this, options);
this.scrollback = options.scrollback != null
? options.scrollback
: Infinity;
this.scrollOnInput = options.scrollOnInput;
this.on('set content', function() {
if (!self._userScrolled || self.scrollOnInput) {
nextTick(function() {
self.setScrollPerc(100);
self._userScrolled = false;
self.screen.render();
});
}
});
}
Log.prototype.__proto__ = ScrollableText.prototype;
Log.prototype.type = 'log';
Log.prototype.log =
Log.prototype.add = function() {
var args = Array.prototype.slice.call(arguments);
if (typeof args[0] === 'object') {
args[0] = util.inspect(args[0], true, 20, true);
}
var text = util.format.apply(util, args);
this.emit('log', text);
var ret = this.pushLine(text);
if (this._clines.fake.length > this.scrollback) {
this.shiftLine(0, (this.scrollback / 3) | 0);
}
return ret;
};
Log.prototype._scroll = Log.prototype.scroll;
Log.prototype.scroll = function(offset, always) {
if (offset === 0) return this._scroll(offset, always);
this._userScrolled = true;
var ret = this._scroll(offset, always);
if (this.getScrollPerc() === 100) {
this._userScrolled = false;
}
return ret;
};
/**
* Expose
*/
module.exports = Log;
| mit |
shutchings/azure-sdk-for-net | src/SDKs/DataFactory/Management.DataFactory/Generated/Models/PipelineRunQueryFilterOperator.cs | 761 | // <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.DataFactory.Models
{
/// <summary>
/// Defines values for PipelineRunQueryFilterOperator.
/// </summary>
public static class PipelineRunQueryFilterOperator
{
public const string Equals = "Equals";
public const string NotEquals = "NotEquals";
public const string In = "In";
public const string NotIn = "NotIn";
}
}
| mit |
hyounesy/ALEA | src/igv/src/org/broad/igv/tools/WigSummer.java | 3691 | /*
* The MIT License (MIT)
*
* Copyright (c) 2007-2015 Broad Institute
*
* 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.
*/
package org.broad.igv.tools;
import java.io.*;
import java.util.List;
/**
* Sum the values from a list of wig files and output a new wig file with the totals. The wig files have to have
* exactly the same coordinates row per row.
* <p/>
* TODO: NOTE -- this only works with variable step at the moment. The first line in each file must be variableStep
*
* @author jrobinso
* @date Mar 16, 2011
*/
public class WigSummer {
public static void sumWigs(List<File> inputs, File output) throws IOException {
PrintWriter out = null;
BufferedReader[] in = new BufferedReader[inputs.size()];
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(output)));
for (int i = 0; i < inputs.size(); i++) {
in[i] = new BufferedReader(new FileReader(inputs.get(i)));
}
int lineNumber = 1;
String firstLine = null;
for (BufferedReader reader : in) {
if (firstLine == null) {
firstLine = reader.readLine().trim();
if (!firstLine.startsWith("variableStep")) {
throw new RuntimeException("First line must be a variableStep line");
}
} else {
String tmp = reader.readLine().trim();
if (!tmp.equals(firstLine)) {
throw new RuntimeException("First line of all input files must be equal");
}
}
out.println(firstLine);
lineNumber++;
}
String tmp = null;
while ((tmp = in[0].readLine()) != null) {
String[] tokens = tmp.split("\t");
int position = Integer.parseInt(tokens[0]);
float v = Float.parseFloat(tokens[1]);
for (int i = 1; i < in.length; i++) {
tmp = in[i].readLine();
tokens = tmp.split("\t");
int p = Integer.parseInt(tokens[0]);
if (p != position) {
throw new RuntimeException("Positions not all equal at line number " + lineNumber);
}
v += Float.parseFloat(tokens[1]);
}
out.println(position + "\t" + v);
}
} finally {
out.close();
for(BufferedReader reader : in) {
reader.close();
}
}
}
}
| mit |
kskalski/Netjs | Dependencies/NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/ResolveVisitor.cs | 151751 | // Copyright (c) AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using ICSharpCode.NRefactory.CSharp.Analysis;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
namespace ICSharpCode.NRefactory.CSharp.Resolver
{
/// <summary>
/// Traverses the DOM and resolves expressions.
/// </summary>
/// <remarks>
/// The ResolveVisitor does two jobs at the same time: it tracks the resolve context (properties on CSharpResolver)
/// and it resolves the expressions visited.
/// To allow using the context tracking without having to resolve every expression in the file (e.g. when you want to resolve
/// only a single node deep within the DOM), you can use the <see cref="IResolveVisitorNavigator"/> interface.
/// The navigator allows you to switch the between scanning mode and resolving mode.
/// In scanning mode, the context is tracked (local variables registered etc.), but nodes are not resolved.
/// While scanning, the navigator will get asked about every node that the resolve visitor is about to enter.
/// This allows the navigator whether to keep scanning, whether switch to resolving mode, or whether to completely skip the
/// subtree rooted at that node.
///
/// In resolving mode, the context is tracked and nodes will be resolved.
/// The resolve visitor may decide that it needs to resolve other nodes as well in order to resolve the current node.
/// In this case, those nodes will be resolved automatically, without asking the navigator interface.
/// For child nodes that are not essential to resolving, the resolve visitor will switch back to scanning mode (and thus will
/// ask the navigator for further instructions).
///
/// Moreover, there is the <c>ResolveAll</c> mode - it works similar to resolving mode, but will not switch back to scanning mode.
/// The whole subtree will be resolved without notifying the navigator.
/// </remarks>
sealed class ResolveVisitor : IAstVisitor<ResolveResult>
{
// The ResolveVisitor is also responsible for handling lambda expressions.
static readonly ResolveResult errorResult = ErrorResolveResult.UnknownError;
CSharpResolver resolver;
/// <summary>Resolve result of the current LINQ query.</summary>
/// <remarks>We do not have to put this into the stored state (resolver) because
/// query expressions are always resolved in a single operation.</remarks>
ResolveResult currentQueryResult;
readonly CSharpUnresolvedFile unresolvedFile;
readonly Dictionary<AstNode, ResolveResult> resolveResultCache = new Dictionary<AstNode, ResolveResult>();
readonly Dictionary<AstNode, CSharpResolver> resolverBeforeDict = new Dictionary<AstNode, CSharpResolver>();
readonly Dictionary<AstNode, CSharpResolver> resolverAfterDict = new Dictionary<AstNode, CSharpResolver>();
readonly Dictionary<Expression, ConversionWithTargetType> conversionDict = new Dictionary<Expression, ConversionWithTargetType>();
internal struct ConversionWithTargetType
{
public readonly Conversion Conversion;
public readonly IType TargetType;
public ConversionWithTargetType(Conversion conversion, IType targetType)
{
this.Conversion = conversion;
this.TargetType = targetType;
}
}
IResolveVisitorNavigator navigator;
bool resolverEnabled;
List<LambdaBase> undecidedLambdas;
internal CancellationToken cancellationToken;
#region Constructor
static readonly IResolveVisitorNavigator skipAllNavigator = new ConstantModeResolveVisitorNavigator(ResolveVisitorNavigationMode.Skip, null);
/// <summary>
/// Creates a new ResolveVisitor instance.
/// </summary>
public ResolveVisitor(CSharpResolver resolver, CSharpUnresolvedFile unresolvedFile)
{
if (resolver == null)
throw new ArgumentNullException("resolver");
this.resolver = resolver;
this.unresolvedFile = unresolvedFile;
this.navigator = skipAllNavigator;
}
internal void SetNavigator(IResolveVisitorNavigator navigator)
{
this.navigator = navigator ?? skipAllNavigator;
}
ResolveResult voidResult {
get {
return new ResolveResult(resolver.Compilation.FindType(KnownTypeCode.Void));
}
}
#endregion
#region ResetContext
/// <summary>
/// Resets the visitor to the stored position, runs the action, and then reverts the visitor to the previous position.
/// </summary>
void ResetContext(CSharpResolver storedContext, Action action)
{
var oldResolverEnabled = this.resolverEnabled;
var oldResolver = this.resolver;
var oldQueryResult = this.currentQueryResult;
try {
this.resolverEnabled = false;
this.resolver = storedContext;
this.currentQueryResult = null;
action();
} finally {
this.resolverEnabled = oldResolverEnabled;
this.resolver = oldResolver;
this.currentQueryResult = oldQueryResult;
}
}
#endregion
#region Scan / Resolve
/// <summary>
/// Scans the AST rooted at the given node.
/// </summary>
public void Scan(AstNode node)
{
if (node == null || node.IsNull)
return;
switch (node.NodeType) {
case NodeType.Token:
case NodeType.Whitespace:
return; // skip tokens, identifiers, comments, etc.
}
// don't Scan again if the node was already resolved
if (resolveResultCache.ContainsKey(node)) {
// Restore state change caused by this node:
CSharpResolver newResolver;
if (resolverAfterDict.TryGetValue(node, out newResolver))
resolver = newResolver;
return;
}
var mode = navigator.Scan(node);
switch (mode) {
case ResolveVisitorNavigationMode.Skip:
if (node is VariableDeclarationStatement || node is SwitchSection) {
// Enforce scanning of variable declarations.
goto case ResolveVisitorNavigationMode.Scan;
}
StoreCurrentState(node);
break;
case ResolveVisitorNavigationMode.Scan:
bool oldResolverEnabled = resolverEnabled;
var oldResolver = resolver;
resolverEnabled = false;
StoreCurrentState(node);
ResolveResult result = node.AcceptVisitor(this);
if (result != null) {
// If the node was resolved, store the result even though it wasn't requested.
// This is necessary so that Visit-methods that decide to always resolve are
// guaranteed to get called only once.
// This is used for lambda registration.
StoreResult(node, result);
if (resolver != oldResolver) {
// The node changed the resolver state:
resolverAfterDict.Add(node, resolver);
}
cancellationToken.ThrowIfCancellationRequested();
}
resolverEnabled = oldResolverEnabled;
break;
case ResolveVisitorNavigationMode.Resolve:
Resolve(node);
break;
default:
throw new InvalidOperationException("Invalid value for ResolveVisitorNavigationMode");
}
}
/// <summary>
/// Equivalent to 'Scan', but also resolves the node at the same time.
/// This method should be only used if the CSharpResolver passed to the ResolveVisitor was manually set
/// to the correct state.
/// Otherwise, use <c>resolver.Scan(syntaxTree); var result = resolver.GetResolveResult(node);</c>
/// instead.
/// --
/// This method now is internal, because it is difficult to use correctly.
/// Users of the public API should use Scan()+GetResolveResult() instead.
/// </summary>
internal ResolveResult Resolve(AstNode node)
{
if (node == null || node.IsNull)
return errorResult;
bool oldResolverEnabled = resolverEnabled;
resolverEnabled = true;
ResolveResult result;
if (!resolveResultCache.TryGetValue(node, out result)) {
cancellationToken.ThrowIfCancellationRequested();
StoreCurrentState(node);
var oldResolver = resolver;
result = node.AcceptVisitor(this) ?? errorResult;
StoreResult(node, result);
if (resolver != oldResolver) {
// The node changed the resolver state:
resolverAfterDict.Add(node, resolver);
}
}
resolverEnabled = oldResolverEnabled;
return result;
}
IType ResolveType(AstType type)
{
return Resolve(type).Type;
}
void StoreCurrentState(AstNode node)
{
// It's possible that we re-visit an expression that we scanned over earlier,
// so we might have to overwrite an existing state.
#if DEBUG
CSharpResolver oldResolver;
if (resolverBeforeDict.TryGetValue(node, out oldResolver)) {
Debug.Assert(oldResolver.LocalVariables.SequenceEqual(resolver.LocalVariables));
}
#endif
resolverBeforeDict[node] = resolver;
}
void StoreResult(AstNode node, ResolveResult result)
{
Debug.Assert(result != null);
if (node.IsNull)
return;
Log.WriteLine("Resolved '{0}' to {1}", node, result);
Debug.Assert(!CSharpAstResolver.IsUnresolvableNode(node));
// The state should be stored before the result is.
Debug.Assert(resolverBeforeDict.ContainsKey(node));
// Don't store results twice.
Debug.Assert(!resolveResultCache.ContainsKey(node));
resolveResultCache[node] = result;
if (navigator != null)
navigator.Resolved(node, result);
}
void ScanChildren(AstNode node)
{
for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) {
Scan(child);
}
}
#endregion
#region Process Conversions
sealed class AnonymousFunctionConversion : Conversion
{
public readonly IType ReturnType;
public readonly ExplicitlyTypedLambda ExplicitlyTypedLambda;
public readonly LambdaTypeHypothesis Hypothesis;
readonly bool isValid;
public AnonymousFunctionConversion(IType returnType, LambdaTypeHypothesis hypothesis, bool isValid)
{
if (returnType == null)
throw new ArgumentNullException("returnType");
this.ReturnType = returnType;
this.Hypothesis = hypothesis;
this.isValid = isValid;
}
public AnonymousFunctionConversion(IType returnType, ExplicitlyTypedLambda explicitlyTypedLambda, bool isValid)
{
if (returnType == null)
throw new ArgumentNullException("returnType");
this.ReturnType = returnType;
this.ExplicitlyTypedLambda = explicitlyTypedLambda;
this.isValid = isValid;
}
public override bool IsValid {
get { return isValid; }
}
public override bool IsImplicit {
get { return true; }
}
public override bool IsAnonymousFunctionConversion {
get { return true; }
}
}
/// <summary>
/// Convert 'rr' to the target type using the specified conversion.
/// </summary>
void ProcessConversion(Expression expr, ResolveResult rr, Conversion conversion, IType targetType)
{
AnonymousFunctionConversion afc = conversion as AnonymousFunctionConversion;
if (afc != null) {
Log.WriteLine("Processing conversion of anonymous function to " + targetType + "...");
Log.Indent();
if (afc.Hypothesis != null)
afc.Hypothesis.MergeInto(this, afc.ReturnType);
if (afc.ExplicitlyTypedLambda != null)
afc.ExplicitlyTypedLambda.ApplyReturnType(this, afc.ReturnType);
Log.Unindent();
}
if (expr != null && !expr.IsNull && conversion != Conversion.IdentityConversion) {
navigator.ProcessConversion(expr, rr, conversion, targetType);
conversionDict[expr] = new ConversionWithTargetType(conversion, targetType);
}
}
void ImportConversions(ResolveVisitor childVisitor)
{
foreach (var pair in childVisitor.conversionDict) {
conversionDict.Add(pair.Key, pair.Value);
navigator.ProcessConversion(pair.Key, resolveResultCache[pair.Key], pair.Value.Conversion, pair.Value.TargetType);
}
}
/// <summary>
/// Convert 'rr' to the target type.
/// </summary>
void ProcessConversion(Expression expr, ResolveResult rr, IType targetType)
{
if (expr == null || expr.IsNull)
return;
ProcessConversion(expr, rr, resolver.conversions.ImplicitConversion(rr, targetType), targetType);
}
/// <summary>
/// Resolves the specified expression and processes the conversion to targetType.
/// </summary>
void ResolveAndProcessConversion(Expression expr, IType targetType)
{
if (targetType.Kind == TypeKind.Unknown || targetType.Kind == TypeKind.Void) {
// no need to resolve the expression right now
Scan(expr);
} else {
ProcessConversion(expr, Resolve(expr), targetType);
}
}
void ProcessConversionResult(Expression expr, ConversionResolveResult rr)
{
if (rr != null)
ProcessConversion(expr, rr.Input, rr.Conversion, rr.Type);
}
void ProcessConversionResults(IEnumerable<Expression> expr, IEnumerable<ResolveResult> conversionResolveResults)
{
Debug.Assert(expr.Count() == conversionResolveResults.Count());
using (var e1 = expr.GetEnumerator()) {
using (var e2 = conversionResolveResults.GetEnumerator()) {
while (e1.MoveNext() && e2.MoveNext()) {
ProcessConversionResult(e1.Current, e2.Current as ConversionResolveResult);
}
}
}
}
void MarkUnknownNamedArguments(IEnumerable<Expression> arguments)
{
foreach (var nae in arguments.OfType<NamedArgumentExpression>()) {
StoreCurrentState(nae);
StoreResult(nae, new NamedArgumentResolveResult(nae.Name, resolveResultCache[nae.Expression]));
}
}
void ProcessInvocationResult(Expression target, IEnumerable<Expression> arguments, ResolveResult invocation)
{
if (invocation is CSharpInvocationResolveResult || invocation is DynamicInvocationResolveResult) {
int i = 0;
IList<ResolveResult> argumentsRR;
if (invocation is CSharpInvocationResolveResult) {
var csi = (CSharpInvocationResolveResult)invocation;
if (csi.IsExtensionMethodInvocation) {
Debug.Assert(arguments.Count() + 1 == csi.Arguments.Count);
ProcessConversionResult(target, csi.Arguments[0] as ConversionResolveResult);
i = 1;
} else {
Debug.Assert(arguments.Count() == csi.Arguments.Count);
}
argumentsRR = csi.Arguments;
}
else {
argumentsRR = ((DynamicInvocationResolveResult)invocation).Arguments;
}
foreach (Expression arg in arguments) {
ResolveResult argRR = argumentsRR[i++];
NamedArgumentExpression nae = arg as NamedArgumentExpression;
NamedArgumentResolveResult nrr = argRR as NamedArgumentResolveResult;
Debug.Assert((nae == null) == (nrr == null));
if (nae != null && nrr != null) {
StoreCurrentState(nae);
StoreResult(nae, nrr);
ProcessConversionResult(nae.Expression, nrr.Argument as ConversionResolveResult);
} else {
ProcessConversionResult(arg, argRR as ConversionResolveResult);
}
}
}
else {
MarkUnknownNamedArguments(arguments);
}
}
#endregion
#region GetResolveResult
/// <summary>
/// Gets the resolve result for the specified node.
/// If the node was not resolved by the navigator, this method will resolve it.
/// </summary>
public ResolveResult GetResolveResult(AstNode node)
{
Debug.Assert(!CSharpAstResolver.IsUnresolvableNode(node));
MergeUndecidedLambdas();
ResolveResult result;
if (resolveResultCache.TryGetValue(node, out result))
return result;
AstNode parent;
CSharpResolver storedResolver = GetPreviouslyScannedContext(node, out parent);
ResetContext(
storedResolver,
delegate {
navigator = new NodeListResolveVisitorNavigator(node);
Debug.Assert(!resolverEnabled);
Scan(parent);
navigator = skipAllNavigator;
});
MergeUndecidedLambdas();
return resolveResultCache[node];
}
CSharpResolver GetPreviouslyScannedContext(AstNode node, out AstNode parent)
{
parent = node;
CSharpResolver storedResolver;
while (!resolverBeforeDict.TryGetValue(parent, out storedResolver)) {
parent = parent.Parent;
if (parent == null)
throw new InvalidOperationException("Could not find a resolver state for any parent of the specified node. Are you trying to resolve a node that is not a descendant of the CSharpAstResolver's root node?");
}
return storedResolver;
}
/// <summary>
/// Gets the resolver state in front of the specified node.
/// If the node was not visited by a previous scanning process, the
/// AST will be scanned again to determine the state.
/// </summary>
public CSharpResolver GetResolverStateBefore(AstNode node)
{
MergeUndecidedLambdas();
CSharpResolver r;
if (resolverBeforeDict.TryGetValue(node, out r))
return r;
AstNode parent;
CSharpResolver storedResolver = GetPreviouslyScannedContext(node, out parent);
ResetContext(
storedResolver,
delegate {
navigator = new NodeListResolveVisitorNavigator(new[] { node }, scanOnly: true);
Debug.Assert(!resolverEnabled);
// parent might already be resolved if 'node' is an unresolvable node
Scan(parent);
navigator = skipAllNavigator;
});
MergeUndecidedLambdas();
while (node != null) {
if (resolverBeforeDict.TryGetValue(node, out r))
return r;
node = node.Parent;
}
return null;
}
public CSharpResolver GetResolverStateAfter(AstNode node)
{
// Resolve the node to fill the resolverAfterDict
GetResolveResult(node);
CSharpResolver result;
if (resolverAfterDict.TryGetValue(node, out result))
return result;
else
return GetResolverStateBefore(node);
}
public ConversionWithTargetType GetConversionWithTargetType(Expression expr)
{
GetResolverStateBefore(expr);
ResolveParentForConversion(expr);
ConversionWithTargetType result;
if (conversionDict.TryGetValue(expr, out result)) {
return result;
} else {
ResolveResult rr = GetResolveResult(expr);
return new ConversionWithTargetType(Conversion.IdentityConversion, rr.Type);
}
}
#endregion
#region Track UsingScope
ResolveResult IAstVisitor<ResolveResult>.VisitSyntaxTree(SyntaxTree unit)
{
CSharpResolver previousResolver = resolver;
try {
if (unresolvedFile != null) {
resolver = resolver.WithCurrentUsingScope(unresolvedFile.RootUsingScope.Resolve(resolver.Compilation));
} else {
var cv = new TypeSystemConvertVisitor(unit.FileName ?? string.Empty);
ApplyVisitorToUsings(cv, unit.Children);
PushUsingScope(cv.UnresolvedFile.RootUsingScope);
}
ScanChildren(unit);
return voidResult;
} finally {
resolver = previousResolver;
}
}
void ApplyVisitorToUsings(TypeSystemConvertVisitor visitor, IEnumerable<AstNode> children)
{
foreach (var child in children) {
if (child is ExternAliasDeclaration || child is UsingDeclaration || child is UsingAliasDeclaration) {
child.AcceptVisitor(visitor);
}
}
}
void PushUsingScope(UsingScope usingScope)
{
usingScope.Freeze();
resolver = resolver.WithCurrentUsingScope(new ResolvedUsingScope(resolver.CurrentTypeResolveContext, usingScope));
}
ResolveResult IAstVisitor<ResolveResult>.VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
{
CSharpResolver previousResolver = resolver;
try {
if (unresolvedFile != null) {
resolver = resolver.WithCurrentUsingScope(unresolvedFile.GetUsingScope(namespaceDeclaration.StartLocation).Resolve(resolver.Compilation));
} else {
string fileName = namespaceDeclaration.GetRegion().FileName ?? string.Empty;
// Fetch parent using scope
// Create root using scope if necessary
if (resolver.CurrentUsingScope == null)
PushUsingScope(new UsingScope());
// Create child using scope
DomRegion region = namespaceDeclaration.GetRegion();
var identifiers = namespaceDeclaration.Identifiers.ToList();
// For all but the last identifier:
UsingScope usingScope;
for (int i = 0; i < identifiers.Count - 1; i++) {
usingScope = new UsingScope(resolver.CurrentUsingScope.UnresolvedUsingScope, identifiers[i].Name);
usingScope.Region = region;
PushUsingScope(usingScope);
}
// Last using scope:
usingScope = new UsingScope(resolver.CurrentUsingScope.UnresolvedUsingScope, identifiers.Last().Name);
usingScope.Region = region;
var cv = new TypeSystemConvertVisitor(new CSharpUnresolvedFile(region.FileName ?? string.Empty), usingScope);
ApplyVisitorToUsings(cv, namespaceDeclaration.Children);
PushUsingScope(usingScope);
}
ScanChildren(namespaceDeclaration);
// merge undecided lambdas before leaving the using scope so that
// the resolver can make better use of its cache
MergeUndecidedLambdas();
if (resolver.CurrentUsingScope != null && resolver.CurrentUsingScope.Namespace != null)
return new NamespaceResolveResult(resolver.CurrentUsingScope.Namespace);
else
return null;
} finally {
resolver = previousResolver;
}
}
#endregion
#region Track CurrentTypeDefinition
ResolveResult VisitTypeOrDelegate(AstNode typeDeclaration, string name, int typeParameterCount)
{
CSharpResolver previousResolver = resolver;
try {
ITypeDefinition newTypeDefinition = null;
if (resolver.CurrentTypeDefinition != null) {
int totalTypeParameterCount = resolver.CurrentTypeDefinition.TypeParameterCount + typeParameterCount;
foreach (ITypeDefinition nestedType in resolver.CurrentTypeDefinition.NestedTypes) {
if (nestedType.Name == name && nestedType.TypeParameterCount == totalTypeParameterCount) {
newTypeDefinition = nestedType;
break;
}
}
} else if (resolver.CurrentUsingScope != null) {
newTypeDefinition = resolver.CurrentUsingScope.Namespace.GetTypeDefinition(name, typeParameterCount);
}
if (newTypeDefinition != null)
resolver = resolver.WithCurrentTypeDefinition(newTypeDefinition);
ScanChildren(typeDeclaration);
// merge undecided lambdas before leaving the type definition so that
// the resolver can make better use of its cache
MergeUndecidedLambdas();
return newTypeDefinition != null ? new TypeResolveResult(newTypeDefinition) : errorResult;
} finally {
resolver = previousResolver;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitTypeDeclaration(TypeDeclaration typeDeclaration)
{
return VisitTypeOrDelegate(typeDeclaration, typeDeclaration.Name, typeDeclaration.TypeParameters.Count);
}
ResolveResult IAstVisitor<ResolveResult>.VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration)
{
return VisitTypeOrDelegate(delegateDeclaration, delegateDeclaration.Name, delegateDeclaration.TypeParameters.Count);
}
#endregion
#region Track CurrentMember
ResolveResult IAstVisitor<ResolveResult>.VisitFieldDeclaration(FieldDeclaration fieldDeclaration)
{
return VisitFieldOrEventDeclaration(fieldDeclaration, EntityType.Field);
}
ResolveResult IAstVisitor<ResolveResult>.VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration)
{
return VisitFieldOrEventDeclaration(fixedFieldDeclaration, EntityType.Field);
}
ResolveResult IAstVisitor<ResolveResult>.VisitEventDeclaration(EventDeclaration eventDeclaration)
{
return VisitFieldOrEventDeclaration(eventDeclaration, EntityType.Event);
}
ResolveResult VisitFieldOrEventDeclaration(EntityDeclaration fieldOrEventDeclaration, EntityType entityType)
{
//int initializerCount = fieldOrEventDeclaration.GetChildrenByRole(Roles.Variable).Count;
CSharpResolver oldResolver = resolver;
for (AstNode node = fieldOrEventDeclaration.FirstChild; node != null; node = node.NextSibling) {
if (node.Role == Roles.Variable) {
IMember member;
if (unresolvedFile != null) {
member = GetMemberFromLocation(node);
} else {
string name = ((VariableInitializer)node).Name;
member = AbstractUnresolvedMember.Resolve(resolver.CurrentTypeResolveContext, entityType, name);
}
resolver = resolver.WithCurrentMember(member);
Scan(node);
resolver = oldResolver;
} else {
Scan(node);
}
}
return voidResult;
}
IMember GetMemberFromLocation(AstNode node)
{
ITypeDefinition typeDef = resolver.CurrentTypeDefinition;
if (typeDef == null)
return null;
TextLocation location = TypeSystemConvertVisitor.GetStartLocationAfterAttributes(node);
return typeDef.GetMembers(
delegate (IUnresolvedMember m) {
if (m.UnresolvedFile != unresolvedFile)
return false;
DomRegion region = m.Region;
return !region.IsEmpty && region.Begin <= location && region.End > location;
},
GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions
).FirstOrDefault();
}
ResolveResult IAstVisitor<ResolveResult>.VisitVariableInitializer(VariableInitializer variableInitializer)
{
// Within the variable initializer, the newly declared variable is not yet available:
var resolverWithVariable = resolver;
if (variableInitializer.Parent is VariableDeclarationStatement)
resolver = resolver.PopLastVariable();
ArrayInitializerExpression aie = variableInitializer.Initializer as ArrayInitializerExpression;
if (resolverEnabled || aie != null) {
ResolveResult result = errorResult;
if (variableInitializer.Parent is FieldDeclaration || variableInitializer.Parent is EventDeclaration) {
if (resolver.CurrentMember != null) {
result = new MemberResolveResult(null, resolver.CurrentMember, false);
}
} else {
string identifier = variableInitializer.Name;
foreach (IVariable v in resolverWithVariable.LocalVariables) {
if (v.Name == identifier) {
result = new LocalResolveResult(v);
break;
}
}
}
ArrayType arrayType = result.Type as ArrayType;
if (aie != null && arrayType != null) {
StoreCurrentState(aie);
List<Expression> initializerElements = new List<Expression>();
UnpackArrayInitializer(initializerElements, aie, arrayType.Dimensions, true);
ResolveResult[] initializerElementResults = new ResolveResult[initializerElements.Count];
for (int i = 0; i < initializerElementResults.Length; i++) {
initializerElementResults[i] = Resolve(initializerElements[i]);
}
var arrayCreation = resolver.ResolveArrayCreation(arrayType.ElementType, arrayType.Dimensions, null, initializerElementResults);
StoreResult(aie, arrayCreation);
ProcessConversionResults(initializerElements, arrayCreation.InitializerElements);
} else if (variableInitializer.Parent is FixedStatement) {
var initRR = Resolve(variableInitializer.Initializer);
PointerType pointerType;
if (initRR.Type.Kind == TypeKind.Array) {
pointerType = new PointerType(((ArrayType)initRR.Type).ElementType);
} else if (ReflectionHelper.GetTypeCode(initRR.Type) == TypeCode.String) {
pointerType = new PointerType(resolver.Compilation.FindType(KnownTypeCode.Char));
} else {
pointerType = null;
ProcessConversion(variableInitializer.Initializer, initRR, result.Type);
}
if (pointerType != null) {
var conversion = resolver.conversions.ImplicitConversion(pointerType, result.Type);
if (conversion.IsIdentityConversion)
conversion = Conversion.ImplicitPointerConversion;
ProcessConversion(variableInitializer.Initializer, initRR, conversion, result.Type);
}
} else {
ResolveAndProcessConversion(variableInitializer.Initializer, result.Type);
}
resolver = resolverWithVariable;
return result;
} else {
Scan(variableInitializer.Initializer);
resolver = resolverWithVariable;
return null;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer)
{
if (resolverEnabled) {
ResolveResult result = errorResult;
if (resolver.CurrentMember != null) {
result = new MemberResolveResult(null, resolver.CurrentMember, false);
}
ResolveAndProcessConversion(fixedVariableInitializer.CountExpression, resolver.Compilation.FindType(KnownTypeCode.Int32));
return result;
} else {
ScanChildren(fixedVariableInitializer);
return null;
}
}
ResolveResult VisitMethodMember(EntityDeclaration memberDeclaration)
{
CSharpResolver oldResolver = resolver;
try {
IMember member;
if (unresolvedFile != null) {
member = GetMemberFromLocation(memberDeclaration);
} else {
// Re-discover the method:
EntityType entityType = memberDeclaration.EntityType;
var parameterTypes = TypeSystemConvertVisitor.GetParameterTypes(memberDeclaration.GetChildrenByRole(Roles.Parameter));
if (entityType == EntityType.Constructor) {
string name = memberDeclaration.HasModifier(Modifiers.Static) ? ".cctor" : ".ctor";
member = AbstractUnresolvedMember.Resolve(
resolver.CurrentTypeResolveContext, entityType, name,
parameterTypeReferences: parameterTypes);
} else if (entityType == EntityType.Destructor) {
member = AbstractUnresolvedMember.Resolve(resolver.CurrentTypeResolveContext, entityType, "Finalize");
} else {
string[] typeParameterNames = memberDeclaration.GetChildrenByRole(Roles.TypeParameter).Select(tp => tp.Name).ToArray();
AstType explicitInterfaceAstType = memberDeclaration.GetChildByRole(EntityDeclaration.PrivateImplementationTypeRole);
ITypeReference explicitInterfaceType = null;
if (!explicitInterfaceAstType.IsNull) {
explicitInterfaceType = explicitInterfaceAstType.ToTypeReference();
}
member = AbstractUnresolvedMember.Resolve(
resolver.CurrentTypeResolveContext, entityType, memberDeclaration.Name,
explicitInterfaceType, typeParameterNames, parameterTypes);
}
}
resolver = resolver.WithCurrentMember(member);
ScanChildren(memberDeclaration);
if (member != null)
return new MemberResolveResult(null, member, false);
else
return errorResult;
} finally {
resolver = oldResolver;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitMethodDeclaration(MethodDeclaration methodDeclaration)
{
return VisitMethodMember(methodDeclaration);
}
ResolveResult IAstVisitor<ResolveResult>.VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration)
{
return VisitMethodMember(operatorDeclaration);
}
ResolveResult IAstVisitor<ResolveResult>.VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
{
return VisitMethodMember(constructorDeclaration);
}
ResolveResult IAstVisitor<ResolveResult>.VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration)
{
return VisitMethodMember(destructorDeclaration);
}
// handle properties/indexers
ResolveResult VisitPropertyMember(EntityDeclaration propertyOrIndexerDeclaration)
{
CSharpResolver oldResolver = resolver;
try {
IMember member;
if (unresolvedFile != null) {
member = GetMemberFromLocation(propertyOrIndexerDeclaration);
} else {
// Re-discover the property:
string name = propertyOrIndexerDeclaration.Name;
var parameterTypeReferences = TypeSystemConvertVisitor.GetParameterTypes(propertyOrIndexerDeclaration.GetChildrenByRole(Roles.Parameter));
AstType explicitInterfaceAstType = propertyOrIndexerDeclaration.GetChildByRole(EntityDeclaration.PrivateImplementationTypeRole);
ITypeReference explicitInterfaceType = null;
if (!explicitInterfaceAstType.IsNull) {
explicitInterfaceType = explicitInterfaceAstType.ToTypeReference();
}
member = AbstractUnresolvedMember.Resolve(
resolver.CurrentTypeResolveContext, propertyOrIndexerDeclaration.EntityType, name,
explicitInterfaceType, parameterTypeReferences: parameterTypeReferences);
}
// We need to use the property as current member so that indexer parameters can be resolved correctly.
resolver = resolver.WithCurrentMember(member);
var resolverWithPropertyAsMember = resolver;
for (AstNode node = propertyOrIndexerDeclaration.FirstChild; node != null; node = node.NextSibling) {
if (node.Role == PropertyDeclaration.GetterRole && member is IProperty) {
resolver = resolver.WithCurrentMember(((IProperty)member).Getter);
Scan(node);
resolver = resolverWithPropertyAsMember;
} else if (node.Role == PropertyDeclaration.SetterRole && member is IProperty) {
resolver = resolver.WithCurrentMember(((IProperty)member).Setter);
Scan(node);
resolver = resolverWithPropertyAsMember;
} else {
Scan(node);
}
}
if (member != null)
return new MemberResolveResult(null, member, false);
else
return errorResult;
} finally {
resolver = oldResolver;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration)
{
return VisitPropertyMember(propertyDeclaration);
}
ResolveResult IAstVisitor<ResolveResult>.VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
{
return VisitPropertyMember(indexerDeclaration);
}
ResolveResult IAstVisitor<ResolveResult>.VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration)
{
CSharpResolver oldResolver = resolver;
try {
IMember member;
if (unresolvedFile != null) {
member = GetMemberFromLocation(eventDeclaration);
} else {
string name = eventDeclaration.Name;
AstType explicitInterfaceAstType = eventDeclaration.PrivateImplementationType;
if (explicitInterfaceAstType.IsNull) {
member = AbstractUnresolvedMember.Resolve(resolver.CurrentTypeResolveContext, EntityType.Event, name);
} else {
member = AbstractUnresolvedMember.Resolve(resolver.CurrentTypeResolveContext, EntityType.Event, name,
explicitInterfaceAstType.ToTypeReference());
}
}
resolver = resolver.WithCurrentMember(member);
var resolverWithEventAsMember = resolver;
for (AstNode node = eventDeclaration.FirstChild; node != null; node = node.NextSibling) {
if (node.Role == CustomEventDeclaration.AddAccessorRole && member is IEvent) {
resolver = resolver.WithCurrentMember(((IEvent)member).AddAccessor);
Scan(node);
resolver = resolverWithEventAsMember;
} else if (node.Role == CustomEventDeclaration.RemoveAccessorRole && member is IEvent) {
resolver = resolver.WithCurrentMember(((IEvent)member).RemoveAccessor);
Scan(node);
resolver = resolverWithEventAsMember;
} else {
Scan(node);
}
}
if (member != null)
return new MemberResolveResult(null, member, false);
else
return errorResult;
} finally {
resolver = oldResolver;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitParameterDeclaration(ParameterDeclaration parameterDeclaration)
{
ScanChildren(parameterDeclaration);
if (resolverEnabled) {
string name = parameterDeclaration.Name;
if (parameterDeclaration.Parent is DocumentationReference) {
// create a dummy parameter
IType type = ResolveType(parameterDeclaration.Type);
switch (parameterDeclaration.ParameterModifier) {
case ParameterModifier.Ref:
case ParameterModifier.Out:
type = new ByReferenceType(type);
break;
}
return new LocalResolveResult(new DefaultParameter(
type, name,
isRef: parameterDeclaration.ParameterModifier == ParameterModifier.Ref,
isOut: parameterDeclaration.ParameterModifier == ParameterModifier.Out,
isParams: parameterDeclaration.ParameterModifier == ParameterModifier.Params));
}
// Look in lambda parameters:
foreach (IParameter p in resolver.LocalVariables.OfType<IParameter>()) {
if (p.Name == name)
return new LocalResolveResult(p);
}
IParameterizedMember pm = resolver.CurrentMember as IParameterizedMember;
if (pm == null && resolver.CurrentTypeDefinition != null) {
// Also consider delegate parameters:
pm = resolver.CurrentTypeDefinition.GetDelegateInvokeMethod();
// pm will be null if the current type isn't a delegate
}
if (pm != null) {
foreach (IParameter p in pm.Parameters) {
if (p.Name == name) {
return new LocalResolveResult(p);
}
}
}
return errorResult;
} else {
return null;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration)
{
ScanChildren(typeParameterDeclaration);
if (resolverEnabled) {
string name = typeParameterDeclaration.Name;
IMethod m = resolver.CurrentMember as IMethod;
if (m != null) {
foreach (var tp in m.TypeParameters) {
if (tp.Name == name)
return new TypeResolveResult(tp);
}
}
if (resolver.CurrentTypeDefinition != null) {
var typeParameters = resolver.CurrentTypeDefinition.TypeParameters;
// look backwards so that TPs in the current type take precedence over those copied from outer types
for (int i = typeParameters.Count - 1; i >= 0; i--) {
if (typeParameters[i].Name == name)
return new TypeResolveResult(typeParameters[i]);
}
}
return errorResult;
} else {
return null;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration)
{
CSharpResolver oldResolver = resolver;
try {
// Scan enum member attributes before setting resolver.CurrentMember, so that
// enum values used as attribute arguments have the correct type.
// (within an enum member, all other enum members are treated as having their underlying type)
foreach (var attributeSection in enumMemberDeclaration.Attributes)
Scan(attributeSection);
IMember member = null;
if (unresolvedFile != null) {
member = GetMemberFromLocation(enumMemberDeclaration);
} else if (resolver.CurrentTypeDefinition != null) {
string name = enumMemberDeclaration.Name;
member = resolver.CurrentTypeDefinition.GetFields(f => f.Name == name, GetMemberOptions.IgnoreInheritedMembers).FirstOrDefault();
}
resolver = resolver.WithCurrentMember(member);
if (resolverEnabled && resolver.CurrentTypeDefinition != null) {
ResolveAndProcessConversion(enumMemberDeclaration.Initializer, resolver.CurrentTypeDefinition.EnumUnderlyingType);
if (resolverEnabled && member != null)
return new MemberResolveResult(null, member, false);
else
return errorResult;
} else {
Scan(enumMemberDeclaration.Initializer);
return null;
}
} finally {
resolver = oldResolver;
}
}
#endregion
#region Track CheckForOverflow
ResolveResult IAstVisitor<ResolveResult>.VisitCheckedExpression(CheckedExpression checkedExpression)
{
CSharpResolver oldResolver = resolver;
try {
resolver = resolver.WithCheckForOverflow(true);
if (resolverEnabled) {
return Resolve(checkedExpression.Expression);
} else {
ScanChildren(checkedExpression);
return null;
}
} finally {
resolver = oldResolver;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitUncheckedExpression(UncheckedExpression uncheckedExpression)
{
CSharpResolver oldResolver = resolver;
try {
resolver = resolver.WithCheckForOverflow(false);
if (resolverEnabled) {
return Resolve(uncheckedExpression.Expression);
} else {
ScanChildren(uncheckedExpression);
return null;
}
} finally {
resolver = oldResolver;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitCheckedStatement(CheckedStatement checkedStatement)
{
CSharpResolver oldResolver = resolver;
try {
resolver = resolver.WithCheckForOverflow(true);
ScanChildren(checkedStatement);
return voidResult;
} finally {
resolver = oldResolver;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitUncheckedStatement(UncheckedStatement uncheckedStatement)
{
CSharpResolver oldResolver = resolver;
try {
resolver = resolver.WithCheckForOverflow(false);
ScanChildren(uncheckedStatement);
return voidResult;
} finally {
resolver = oldResolver;
}
}
#endregion
#region Visit AnonymousTypeCreateExpression
static string GetAnonymousTypePropertyName(Expression expr, out Expression resolveExpr)
{
if (expr is NamedExpression) {
var namedArgExpr = (NamedExpression)expr;
resolveExpr = namedArgExpr.Expression;
return namedArgExpr.Name;
}
// no name given, so it's a projection initializer
if (expr is MemberReferenceExpression) {
resolveExpr = expr;
return ((MemberReferenceExpression)expr).MemberName;
}
if (expr is IdentifierExpression) {
resolveExpr = expr;
return ((IdentifierExpression)expr).Identifier;
}
resolveExpr = null;
return null;
}
class AnonymousTypeMember
{
public readonly Expression Expression;
public readonly ResolveResult Initializer;
public AnonymousTypeMember(Expression expression, ResolveResult initializer)
{
this.Expression = expression;
this.Initializer = initializer;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression)
{
// 7.6.10.6 Anonymous object creation expressions
List<IUnresolvedProperty> unresolvedProperties = new List<IUnresolvedProperty>();
List<AnonymousTypeMember> members = new List<AnonymousTypeMember>();
foreach (var expr in anonymousTypeCreateExpression.Initializers) {
Expression resolveExpr;
var name = GetAnonymousTypePropertyName(expr, out resolveExpr);
if (resolveExpr != null) {
var initRR = Resolve(resolveExpr);
var returnTypeRef = initRR.Type.ToTypeReference();
var property = new DefaultUnresolvedProperty {
Name = name,
Accessibility = Accessibility.Public,
ReturnType = returnTypeRef,
Getter = new DefaultUnresolvedMethod {
Name = "get_" + name,
Accessibility = Accessibility.Public,
ReturnType = returnTypeRef
}
};
unresolvedProperties.Add(property);
members.Add(new AnonymousTypeMember(expr, initRR));
} else {
Scan(expr);
}
}
var anonymousType = new AnonymousType(resolver.Compilation, unresolvedProperties);
var properties = anonymousType.GetProperties().ToList();
Debug.Assert(properties.Count == members.Count);
List<ResolveResult> assignments = new List<ResolveResult>();
for (int i = 0; i < members.Count; i++) {
ResolveResult lhs = new MemberResolveResult(new InitializedObjectResolveResult(anonymousType), properties[i]);
ResolveResult rhs = members[i].Initializer;
ResolveResult assignment = resolver.ResolveAssignment(AssignmentOperatorType.Assign, lhs, rhs);
var ne = members[i].Expression as NamedExpression;
if (ne != null) {
StoreCurrentState(ne);
// ne.Expression was already resolved by the first loop
StoreResult(ne, lhs);
}
assignments.Add(assignment);
}
var anonymousCtor = DefaultResolvedMethod.GetDummyConstructor(resolver.Compilation, anonymousType);
return new InvocationResolveResult(null, anonymousCtor, initializerStatements: assignments);
}
#endregion
#region Visit Expressions
ResolveResult IAstVisitor<ResolveResult>.VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression)
{
int dimensions = arrayCreateExpression.Arguments.Count;
ResolveResult[] sizeArguments;
IEnumerable<ArraySpecifier> additionalArraySpecifiers;
if (dimensions == 0) {
var firstSpecifier = arrayCreateExpression.AdditionalArraySpecifiers.FirstOrDefault();
if (firstSpecifier != null) {
dimensions = firstSpecifier.Dimensions;
additionalArraySpecifiers = arrayCreateExpression.AdditionalArraySpecifiers.Skip(1);
} else {
dimensions = 0;
additionalArraySpecifiers = arrayCreateExpression.AdditionalArraySpecifiers;
}
sizeArguments = null;
} else {
sizeArguments = new ResolveResult[dimensions];
int pos = 0;
foreach (var node in arrayCreateExpression.Arguments)
sizeArguments[pos++] = Resolve(node);
additionalArraySpecifiers = arrayCreateExpression.AdditionalArraySpecifiers;
}
List<Expression> initializerElements;
ResolveResult[] initializerElementResults;
if (arrayCreateExpression.Initializer.IsNull) {
initializerElements = null;
initializerElementResults = null;
} else {
StoreCurrentState(arrayCreateExpression.Initializer);
initializerElements = new List<Expression>();
UnpackArrayInitializer(initializerElements, arrayCreateExpression.Initializer, dimensions, true);
initializerElementResults = new ResolveResult[initializerElements.Count];
for (int i = 0; i < initializerElementResults.Length; i++) {
initializerElementResults[i] = Resolve(initializerElements[i]);
}
StoreResult(arrayCreateExpression.Initializer, voidResult);
}
ArrayCreateResolveResult acrr;
if (arrayCreateExpression.Type.IsNull) {
acrr = resolver.ResolveArrayCreation(null, dimensions, sizeArguments, initializerElementResults);
} else {
IType elementType = ResolveType(arrayCreateExpression.Type);
foreach (var spec in additionalArraySpecifiers.Reverse()) {
elementType = new ArrayType(resolver.Compilation, elementType, spec.Dimensions);
}
acrr = resolver.ResolveArrayCreation(elementType, dimensions, sizeArguments, initializerElementResults);
}
return acrr;
}
void UnpackArrayInitializer(List<Expression> elementList, ArrayInitializerExpression initializer, int dimensions, bool resolveNestedInitializesToVoid)
{
Debug.Assert(dimensions >= 1);
if (dimensions > 1) {
foreach (var node in initializer.Elements) {
ArrayInitializerExpression aie = node as ArrayInitializerExpression;
if (aie != null) {
if (resolveNestedInitializesToVoid) {
StoreCurrentState(aie);
StoreResult(aie, voidResult);
}
UnpackArrayInitializer(elementList, aie, dimensions - 1, resolveNestedInitializesToVoid);
} else {
elementList.Add(node);
}
}
} else {
foreach (var expr in initializer.Elements)
elementList.Add(expr);
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression)
{
// Array initializers are handled by their parent expression.
ScanChildren(arrayInitializerExpression);
return errorResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitAsExpression(AsExpression asExpression)
{
if (resolverEnabled) {
ResolveResult input = Resolve(asExpression.Expression);
var targetType = ResolveType(asExpression.Type);
return new ConversionResolveResult(targetType, input, Conversion.TryCast, resolver.CheckForOverflow);
} else {
ScanChildren(asExpression);
return null;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitAssignmentExpression(AssignmentExpression assignmentExpression)
{
if (resolverEnabled) {
Expression left = assignmentExpression.Left;
Expression right = assignmentExpression.Right;
ResolveResult leftResult = Resolve(left);
ResolveResult rightResult = Resolve(right);
ResolveResult rr = resolver.ResolveAssignment(assignmentExpression.Operator, leftResult, rightResult);
ProcessConversionsInBinaryOperatorResult(left, right, rr);
return rr;
} else {
ScanChildren(assignmentExpression);
return null;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression)
{
if (resolverEnabled) {
return resolver.ResolveBaseReference();
} else {
ScanChildren(baseReferenceExpression);
return null;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression)
{
if (resolverEnabled) {
Expression left = binaryOperatorExpression.Left;
Expression right = binaryOperatorExpression.Right;
ResolveResult leftResult = Resolve(left);
ResolveResult rightResult = Resolve(right);
ResolveResult rr = resolver.ResolveBinaryOperator(binaryOperatorExpression.Operator, leftResult, rightResult);
ProcessConversionsInBinaryOperatorResult(left, right, rr);
return rr;
} else {
ScanChildren(binaryOperatorExpression);
return null;
}
}
ResolveResult ProcessConversionsInBinaryOperatorResult(Expression left, Expression right, ResolveResult rr)
{
OperatorResolveResult orr = rr as OperatorResolveResult;
if (orr != null && orr.Operands.Count == 2) {
ProcessConversionResult(left, orr.Operands[0] as ConversionResolveResult);
ProcessConversionResult(right, orr.Operands[1] as ConversionResolveResult);
} else {
InvocationResolveResult irr = rr as InvocationResolveResult;
if (irr != null && irr.Arguments.Count == 2) {
ProcessConversionResult(left, irr.Arguments[0] as ConversionResolveResult);
ProcessConversionResult(right, irr.Arguments[1] as ConversionResolveResult);
}
}
return rr;
}
ResolveResult IAstVisitor<ResolveResult>.VisitCastExpression(CastExpression castExpression)
{
if (resolverEnabled) {
IType targetType = ResolveType(castExpression.Type);
Expression expr = castExpression.Expression;
ResolveResult rr = resolver.ResolveCast(targetType, Resolve(expr));
ProcessConversionResult(expr, rr as ConversionResolveResult);
return rr;
} else {
ScanChildren(castExpression);
return null;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitConditionalExpression(ConditionalExpression conditionalExpression)
{
if (resolverEnabled) {
Expression condition = conditionalExpression.Condition;
Expression trueExpr = conditionalExpression.TrueExpression;
Expression falseExpr = conditionalExpression.FalseExpression;
ResolveResult rr = resolver.ResolveConditional(Resolve(condition), Resolve(trueExpr), Resolve(falseExpr));
OperatorResolveResult corr = rr as OperatorResolveResult;
if (corr != null && corr.Operands.Count == 3) {
ProcessConversionResult(condition, corr.Operands[0] as ConversionResolveResult);
ProcessConversionResult(trueExpr, corr.Operands[1] as ConversionResolveResult);
ProcessConversionResult(falseExpr, corr.Operands[2] as ConversionResolveResult);
}
return rr;
} else {
ScanChildren(conditionalExpression);
return null;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression)
{
if (resolverEnabled) {
return resolver.ResolveDefaultValue(ResolveType(defaultValueExpression.Type));
} else {
ScanChildren(defaultValueExpression);
return null;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitDirectionExpression(DirectionExpression directionExpression)
{
if (resolverEnabled) {
ResolveResult rr = Resolve(directionExpression.Expression);
return new ByReferenceResolveResult(rr, directionExpression.FieldDirection == FieldDirection.Out);
} else {
ScanChildren(directionExpression);
return null;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitEmptyExpression(EmptyExpression emptyExpression)
{
return errorResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitIndexerExpression(IndexerExpression indexerExpression)
{
if (resolverEnabled || NeedsResolvingDueToNamedArguments(indexerExpression)) {
Expression target = indexerExpression.Target;
ResolveResult targetResult = Resolve(target);
string[] argumentNames;
ResolveResult[] arguments = GetArguments(indexerExpression.Arguments, out argumentNames);
ResolveResult rr = resolver.ResolveIndexer(targetResult, arguments, argumentNames);
ArrayAccessResolveResult aarr = rr as ArrayAccessResolveResult;
if (aarr != null) {
MarkUnknownNamedArguments(indexerExpression.Arguments);
ProcessConversionResults(indexerExpression.Arguments, aarr.Indexes);
} else {
ProcessInvocationResult(target, indexerExpression.Arguments, rr);
}
return rr;
} else {
ScanChildren(indexerExpression);
return null;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitIsExpression(IsExpression isExpression)
{
if (resolverEnabled) {
ResolveResult input = Resolve(isExpression.Expression);
IType targetType = ResolveType(isExpression.Type);
IType booleanType = resolver.Compilation.FindType(KnownTypeCode.Boolean);
return new TypeIsResolveResult(input, targetType, booleanType);
} else {
ScanChildren(isExpression);
return null;
}
}
// NamedArgumentExpression is "identifier: Expression"
ResolveResult IAstVisitor<ResolveResult>.VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression)
{
// The parent expression takes care of handling NamedArgumentExpressions
// by calling GetArguments().
// This method gets called only when scanning, or when the named argument is used
// in an invalid context.
if (resolverEnabled) {
return new NamedArgumentResolveResult(namedArgumentExpression.Name, Resolve(namedArgumentExpression.Expression));
} else {
Scan(namedArgumentExpression.Expression);
return null;
}
}
// NamedExpression is "identifier = Expression" in object initializers and attributes
ResolveResult IAstVisitor<ResolveResult>.VisitNamedExpression(NamedExpression namedExpression)
{
// The parent expression takes care of handling NamedExpression
// by calling HandleObjectInitializer() or HandleNamedExpression().
// This method gets called only when scanning, or when the named expression is used
// in an invalid context.
ScanChildren(namedExpression);
return null;
}
void HandleNamedExpression(NamedExpression namedExpression, List<ResolveResult> initializerStatements)
{
StoreCurrentState(namedExpression);
Expression rhs = namedExpression.Expression;
ResolveResult lhsRR = resolver.ResolveIdentifierInObjectInitializer(namedExpression.Name);
if (rhs is ArrayInitializerExpression) {
HandleObjectInitializer(lhsRR, (ArrayInitializerExpression)rhs, initializerStatements);
} else {
var rhsRR = Resolve(rhs);
var rr = resolver.ResolveAssignment(AssignmentOperatorType.Assign, lhsRR, rhsRR) as OperatorResolveResult;
if (rr != null) {
ProcessConversionResult(rhs, rr.Operands[1] as ConversionResolveResult);
initializerStatements.Add(rr);
}
}
StoreResult(namedExpression, lhsRR);
}
ResolveResult IAstVisitor<ResolveResult>.VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression)
{
return resolver.ResolvePrimitive(null);
}
ResolveResult IAstVisitor<ResolveResult>.VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression)
{
var typeResolveResult = Resolve(objectCreateExpression.Type);
if (typeResolveResult.IsError) {
ScanChildren (objectCreateExpression);
return typeResolveResult;
}
IType type = typeResolveResult.Type;
List<ResolveResult> initializerStatements = null;
var initializer = objectCreateExpression.Initializer;
if (!initializer.IsNull) {
initializerStatements = new List<ResolveResult>();
HandleObjectInitializer(new InitializedObjectResolveResult(type), initializer, initializerStatements);
}
string[] argumentNames;
ResolveResult[] arguments = GetArguments(objectCreateExpression.Arguments, out argumentNames);
ResolveResult rr = resolver.ResolveObjectCreation(type, arguments, argumentNames, false, initializerStatements);
if (arguments.Length == 1 && rr.Type.Kind == TypeKind.Delegate) {
MarkUnknownNamedArguments(objectCreateExpression.Arguments);
// Apply conversion to argument if it directly wraps the argument
// (but not when creating a delegate from a delegate, as then there would be a MGRR for .Invoke in between)
// This is necessary for lambda type inference.
var crr = rr as ConversionResolveResult;
if (crr != null && crr.Input == arguments[0]) {
ProcessConversionResult(objectCreateExpression.Arguments.Single(), crr);
// wrap the result so that the delegate creation is not handled as a reference
// to the target method - otherwise FindReferencedEntities would produce two results for
// the same delegate creation.
return WrapResult(rr);
} else {
return rr;
}
} else {
// process conversions in all other cases
ProcessInvocationResult(null, objectCreateExpression.Arguments, rr);
return rr;
}
}
void HandleObjectInitializer(ResolveResult initializedObject, ArrayInitializerExpression initializer, List<ResolveResult> initializerStatements)
{
StoreCurrentState(initializer);
resolver = resolver.PushObjectInitializer(initializedObject);
foreach (Expression element in initializer.Elements) {
ArrayInitializerExpression aie = element as ArrayInitializerExpression;
if (aie != null) {
StoreCurrentState(aie);
// constructor argument list in collection initializer
ResolveResult[] addArguments = new ResolveResult[aie.Elements.Count];
int i = 0;
foreach (var addArgument in aie.Elements) {
addArguments[i++] = Resolve(addArgument);
}
MemberLookup memberLookup = resolver.CreateMemberLookup();
var addRR = memberLookup.Lookup(initializedObject, "Add", EmptyList<IType>.Instance, true);
var mgrr = addRR as MethodGroupResolveResult;
if (mgrr != null) {
OverloadResolution or = mgrr.PerformOverloadResolution(resolver.Compilation, addArguments, null, false, false, resolver.CheckForOverflow, resolver.conversions);
var invocationRR = or.CreateResolveResult(initializedObject);
StoreResult(aie, invocationRR);
ProcessInvocationResult(null, aie.Elements, invocationRR);
initializerStatements.Add(invocationRR);
} else {
StoreResult(aie, addRR);
}
} else if (element is NamedExpression) {
HandleNamedExpression((NamedExpression)element, initializerStatements);
} else {
// unknown kind of expression
Scan(element);
}
}
resolver = resolver.PopObjectInitializer();
StoreResult(initializer, voidResult);
}
ResolveResult IAstVisitor<ResolveResult>.VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression)
{
if (resolverEnabled) {
return Resolve(parenthesizedExpression.Expression);
} else {
Scan(parenthesizedExpression.Expression);
return null;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression)
{
if (resolverEnabled) {
ResolveResult target = Resolve(pointerReferenceExpression.Target);
ResolveResult deferencedTarget = resolver.ResolveUnaryOperator(UnaryOperatorType.Dereference, target);
List<IType> typeArguments = new List<IType>();
foreach (AstType typeArgument in pointerReferenceExpression.TypeArguments) {
typeArguments.Add(ResolveType(typeArgument));
}
return resolver.ResolveMemberAccess(deferencedTarget, pointerReferenceExpression.MemberName,
typeArguments,
GetNameLookupMode(pointerReferenceExpression));
} else {
ScanChildren(pointerReferenceExpression);
return null;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitPrimitiveExpression(PrimitiveExpression primitiveExpression)
{
return resolver.ResolvePrimitive(primitiveExpression.Value);
}
ResolveResult IAstVisitor<ResolveResult>.VisitSizeOfExpression(SizeOfExpression sizeOfExpression)
{
return resolver.ResolveSizeOf(ResolveType(sizeOfExpression.Type));
}
ResolveResult IAstVisitor<ResolveResult>.VisitStackAllocExpression(StackAllocExpression stackAllocExpression)
{
ResolveAndProcessConversion(stackAllocExpression.CountExpression, resolver.Compilation.FindType(KnownTypeCode.Int32));
return new ResolveResult(new PointerType(ResolveType(stackAllocExpression.Type)));
}
ResolveResult IAstVisitor<ResolveResult>.VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression)
{
return resolver.ResolveThisReference();
}
ResolveResult IAstVisitor<ResolveResult>.VisitTypeOfExpression(TypeOfExpression typeOfExpression)
{
if (resolverEnabled) {
return resolver.ResolveTypeOf(ResolveType(typeOfExpression.Type));
} else {
Scan(typeOfExpression.Type);
return null;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression)
{
if (resolverEnabled) {
return Resolve(typeReferenceExpression.Type).ShallowClone();
} else {
Scan(typeReferenceExpression.Type);
return null;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression)
{
if (resolverEnabled) {
Expression expr = unaryOperatorExpression.Expression;
ResolveResult input = Resolve(expr);
ITypeDefinition inputTypeDef = input.Type.GetDefinition();
if (input.IsCompileTimeConstant && expr is PrimitiveExpression && inputTypeDef != null) {
// Special cases for int.MinValue and long.MinValue
if (inputTypeDef.KnownTypeCode == KnownTypeCode.UInt32 && 2147483648.Equals(input.ConstantValue)) {
return new ConstantResolveResult(resolver.Compilation.FindType(KnownTypeCode.Int32), -2147483648);
} else if (inputTypeDef.KnownTypeCode == KnownTypeCode.UInt64 && 9223372036854775808.Equals(input.ConstantValue)) {
return new ConstantResolveResult(resolver.Compilation.FindType(KnownTypeCode.Int64), -9223372036854775808);
}
}
ResolveResult rr = resolver.ResolveUnaryOperator(unaryOperatorExpression.Operator, input);
OperatorResolveResult uorr = rr as OperatorResolveResult;
if (uorr != null && uorr.Operands.Count == 1) {
ProcessConversionResult(expr, uorr.Operands[0] as ConversionResolveResult);
} else {
InvocationResolveResult irr = rr as InvocationResolveResult;
if (irr != null && irr.Arguments.Count == 1) {
ProcessConversionResult(expr, irr.Arguments[0] as ConversionResolveResult);
}
}
return rr;
} else {
ScanChildren(unaryOperatorExpression);
return null;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression)
{
ScanChildren(undocumentedExpression);
IType resultType;
switch (undocumentedExpression.UndocumentedExpressionType) {
case UndocumentedExpressionType.ArgListAccess:
case UndocumentedExpressionType.ArgList:
resultType = resolver.Compilation.FindType(typeof(RuntimeArgumentHandle));
break;
case UndocumentedExpressionType.RefValue:
var tre = undocumentedExpression.Arguments.ElementAtOrDefault(1) as TypeReferenceExpression;
if (tre != null)
resultType = ResolveType(tre.Type);
else
resultType = SpecialType.UnknownType;
break;
case UndocumentedExpressionType.RefType:
resultType = resolver.Compilation.FindType(KnownTypeCode.Type);
break;
case UndocumentedExpressionType.MakeRef:
resultType = resolver.Compilation.FindType(typeof(TypedReference));
break;
default:
throw new InvalidOperationException("Invalid value for UndocumentedExpressionType");
}
return new ResolveResult(resultType);
}
#endregion
#region Visit Identifier/MemberReference/Invocation-Expression
// IdentifierExpression, MemberReferenceExpression and InvocationExpression
// are grouped together because they have to work together for
// "7.6.4.1 Identical simple names and type names" support
List<IType> ResolveTypeArguments(IEnumerable<AstType> typeArguments)
{
List<IType> result = new List<IType>();
foreach (AstType typeArgument in typeArguments) {
result.Add(ResolveType(typeArgument));
}
return result;
}
/// <summary>
/// Gets and resolves the arguments; unpacking any NamedArgumentExpressions.
/// </summary>
/// <remarks>
/// Callers of GetArguments must also call either ProcessConversionsInInvocation or MarkUnknownNamedArguments
/// to ensure the named arguments get resolved.
/// Also, as named arguments get resolved by the parent node, the parent node must not scan
/// into the argument list without being resolved - see NeedsResolvingDueToNamedArguments().
/// </remarks>
ResolveResult[] GetArguments(IEnumerable<Expression> argumentExpressions, out string[] argumentNames)
{
argumentNames = null;
ResolveResult[] arguments = new ResolveResult[argumentExpressions.Count()];
int i = 0;
foreach (AstNode argument in argumentExpressions) {
NamedArgumentExpression nae = argument as NamedArgumentExpression;
AstNode argumentValue;
if (nae != null) {
if (argumentNames == null)
argumentNames = new string[arguments.Length];
argumentNames[i] = nae.Name;
argumentValue = nae.Expression;
} else {
argumentValue = argument;
}
arguments[i++] = Resolve(argumentValue);
}
return arguments;
}
bool NeedsResolvingDueToNamedArguments(Expression nodeWithArguments)
{
for (AstNode child = nodeWithArguments.FirstChild; child != null; child = child.NextSibling) {
if (child is NamedArgumentExpression)
return true;
}
return false;
}
static NameLookupMode GetNameLookupMode(Expression expr)
{
InvocationExpression ie = expr.Parent as InvocationExpression;
if (ie != null && ie.Target == expr)
return NameLookupMode.InvocationTarget;
else
return NameLookupMode.Expression;
}
/// <summary>
/// Gets whether 'rr' is considered a static access on the target identifier.
/// </summary>
/// <param name="rr">Resolve Result of the MemberReferenceExpression</param>
/// <param name="invocationRR">Resolve Result of the InvocationExpression</param>
bool IsStaticResult(ResolveResult rr, ResolveResult invocationRR)
{
if (rr is TypeResolveResult)
return true;
MemberResolveResult mrr = (rr is MethodGroupResolveResult ? invocationRR : rr) as MemberResolveResult;
return mrr != null && mrr.Member.IsStatic;
}
ResolveResult IAstVisitor<ResolveResult>.VisitIdentifierExpression(IdentifierExpression identifierExpression)
{
// Note: this method is not called when it occurs in a situation where an ambiguity between
// simple names and type names might occur.
if (resolverEnabled) {
var typeArguments = ResolveTypeArguments(identifierExpression.TypeArguments);
var lookupMode = GetNameLookupMode(identifierExpression);
return resolver.LookupSimpleNameOrTypeName(
identifierExpression.Identifier, typeArguments, lookupMode);
} else {
ScanChildren(identifierExpression);
return null;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression)
{
// target = Resolve(identifierExpression = memberReferenceExpression.Target)
// trr = ResolveType(identifierExpression)
// rr = Resolve(memberReferenceExpression)
IdentifierExpression identifierExpression = memberReferenceExpression.Target as IdentifierExpression;
if (identifierExpression != null && identifierExpression.TypeArguments.Count == 0) {
// Special handling for §7.6.4.1 Identicial simple names and type names
StoreCurrentState(identifierExpression);
ResolveResult target = resolver.ResolveSimpleName(identifierExpression.Identifier, EmptyList<IType>.Instance);
TypeResolveResult trr;
if (resolver.IsVariableReferenceWithSameType(target, identifierExpression.Identifier, out trr)) {
// It's ambiguous
ResolveResult rr = ResolveMemberReferenceOnGivenTarget(target, memberReferenceExpression);
ResolveResult simpleNameRR = IsStaticResult(rr, null) ? trr : target;
Log.WriteLine("Ambiguous simple name '{0}' was resolved to {1}", identifierExpression, simpleNameRR);
StoreResult(identifierExpression, simpleNameRR);
return rr;
} else {
// It's not ambiguous
Log.WriteLine("Simple name '{0}' was resolved to {1}", identifierExpression, target);
StoreResult(identifierExpression, target);
return ResolveMemberReferenceOnGivenTarget(target, memberReferenceExpression);
}
} else {
// Regular code path
if (resolverEnabled) {
ResolveResult target = Resolve(memberReferenceExpression.Target);
return ResolveMemberReferenceOnGivenTarget(target, memberReferenceExpression);
} else {
ScanChildren(memberReferenceExpression);
return null;
}
}
}
ResolveResult ResolveMemberReferenceOnGivenTarget(ResolveResult target, MemberReferenceExpression memberReferenceExpression)
{
var typeArguments = ResolveTypeArguments(memberReferenceExpression.TypeArguments);
return resolver.ResolveMemberAccess(
target, memberReferenceExpression.MemberName, typeArguments,
GetNameLookupMode(memberReferenceExpression));
}
ResolveResult IAstVisitor<ResolveResult>.VisitInvocationExpression(InvocationExpression invocationExpression)
{
// rr = Resolve(invocationExpression)
// target = Resolve(memberReferenceExpression = invocationExpression.Target)
// idRR = Resolve(identifierExpression = memberReferenceExpression.Target)
// trr = ResolveType(identifierExpression)
MemberReferenceExpression mre = invocationExpression.Target as MemberReferenceExpression;
IdentifierExpression identifierExpression = mre != null ? mre.Target as IdentifierExpression : null;
if (identifierExpression != null && identifierExpression.TypeArguments.Count == 0) {
// Special handling for §7.6.4.1 Identicial simple names and type names
StoreCurrentState(identifierExpression);
StoreCurrentState(mre);
ResolveResult idRR = resolver.ResolveSimpleName(identifierExpression.Identifier, EmptyList<IType>.Instance);
ResolveResult target = ResolveMemberReferenceOnGivenTarget(idRR, mre);
Log.WriteLine("Member reference '{0}' on potentially-ambiguous simple-name was resolved to {1}", mre, target);
StoreResult(mre, target);
TypeResolveResult trr;
if (resolver.IsVariableReferenceWithSameType(idRR, identifierExpression.Identifier, out trr)) {
// It's ambiguous
ResolveResult rr = ResolveInvocationOnGivenTarget(target, invocationExpression);
ResolveResult simpleNameRR = IsStaticResult(target, rr) ? trr : idRR;
Log.WriteLine("Ambiguous simple name '{0}' was resolved to {1}",
identifierExpression, simpleNameRR);
StoreResult(identifierExpression, simpleNameRR);
return rr;
} else {
// It's not ambiguous
Log.WriteLine("Simple name '{0}' was resolved to {1}", identifierExpression, idRR);
StoreResult(identifierExpression, idRR);
return ResolveInvocationOnGivenTarget(target, invocationExpression);
}
} else {
// Regular code path
if (resolverEnabled || NeedsResolvingDueToNamedArguments(invocationExpression)) {
ResolveResult target = Resolve(invocationExpression.Target);
return ResolveInvocationOnGivenTarget(target, invocationExpression);
} else {
ScanChildren(invocationExpression);
return null;
}
}
}
ResolveResult ResolveInvocationOnGivenTarget(ResolveResult target, InvocationExpression invocationExpression)
{
string[] argumentNames;
ResolveResult[] arguments = GetArguments(invocationExpression.Arguments, out argumentNames);
ResolveResult rr = resolver.ResolveInvocation(target, arguments, argumentNames);
ProcessInvocationResult(invocationExpression.Target, invocationExpression.Arguments, rr);
return rr;
}
#endregion
#region Lamdbas / Anonymous Functions
ResolveResult IAstVisitor<ResolveResult>.VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression)
{
return HandleExplicitlyTypedLambda(
anonymousMethodExpression.Parameters, anonymousMethodExpression.Body,
isAnonymousMethod: true,
hasParameterList: anonymousMethodExpression.HasParameterList,
isAsync: anonymousMethodExpression.IsAsync);
}
ResolveResult IAstVisitor<ResolveResult>.VisitLambdaExpression(LambdaExpression lambdaExpression)
{
bool isExplicitlyTyped = false;
bool isImplicitlyTyped = false;
foreach (var p in lambdaExpression.Parameters) {
isImplicitlyTyped |= p.Type.IsNull;
isExplicitlyTyped |= !p.Type.IsNull;
}
if (isExplicitlyTyped || !isImplicitlyTyped) {
return HandleExplicitlyTypedLambda(
lambdaExpression.Parameters, lambdaExpression.Body,
isAnonymousMethod: false, hasParameterList: true, isAsync: lambdaExpression.IsAsync);
} else {
return new ImplicitlyTypedLambda(lambdaExpression, this);
}
}
#region Explicitly typed
ExplicitlyTypedLambda HandleExplicitlyTypedLambda(
AstNodeCollection<ParameterDeclaration> parameterDeclarations,
AstNode body, bool isAnonymousMethod, bool hasParameterList, bool isAsync)
{
CSharpResolver oldResolver = resolver;
List<IParameter> parameters = (hasParameterList || parameterDeclarations.Any()) ? new List<IParameter>() : null;
//bool oldIsWithinLambdaExpression = resolver.IsWithinLambdaExpression;
resolver = resolver.WithIsWithinLambdaExpression(true);
foreach (var pd in parameterDeclarations) {
IType type = ResolveType(pd.Type);
if (pd.ParameterModifier == ParameterModifier.Ref || pd.ParameterModifier == ParameterModifier.Out)
type = new ByReferenceType(type);
IParameter p = new DefaultParameter(type, pd.Name, MakeRegion(pd),
isRef: pd.ParameterModifier == ParameterModifier.Ref,
isOut: pd.ParameterModifier == ParameterModifier.Out);
// The parameter declaration must be scanned in the current context (without the new parameter)
// in order to be consistent with the context in which we resolved pd.Type.
StoreCurrentState(pd);
StoreResult(pd, new LocalResolveResult(p));
ScanChildren(pd);
resolver = resolver.AddVariable(p);
parameters.Add(p);
}
var lambda = new ExplicitlyTypedLambda(parameters, isAnonymousMethod, isAsync, resolver, this, body);
// Don't scan the lambda body here - we'll do that later when analyzing the ExplicitlyTypedLambda.
resolver = oldResolver;
return lambda;
}
DomRegion MakeRegion(AstNode node)
{
if (unresolvedFile != null)
return new DomRegion(unresolvedFile.FileName, node.StartLocation, node.EndLocation);
else
return node.GetRegion();
}
sealed class ExplicitlyTypedLambda : LambdaBase
{
readonly IList<IParameter> parameters;
readonly bool isAnonymousMethod;
readonly bool isAsync;
CSharpResolver storedContext;
ResolveVisitor visitor;
AstNode body;
IType inferredReturnType;
IList<Expression> returnExpressions;
IList<ResolveResult> returnValues;
bool isValidAsVoidMethod;
bool isEndpointUnreachable;
// The actual return type is set when the lambda is applied by the conversion.
IType actualReturnType;
internal override bool IsUndecided {
get { return actualReturnType == null; }
}
internal override AstNode LambdaExpression {
get { return body.Parent; }
}
internal override AstNode BodyExpression {
get { return body; }
}
public override ResolveResult Body {
get {
if (body is Expression) {
Analyze();
if (returnValues.Count == 1)
return returnValues[0];
}
return visitor.voidResult;
}
}
public ExplicitlyTypedLambda(IList<IParameter> parameters, bool isAnonymousMethod, bool isAsync, CSharpResolver storedContext, ResolveVisitor visitor, AstNode body)
{
this.parameters = parameters;
this.isAnonymousMethod = isAnonymousMethod;
this.isAsync = isAsync;
this.storedContext = storedContext;
this.visitor = visitor;
this.body = body;
if (visitor.undecidedLambdas == null)
visitor.undecidedLambdas = new List<LambdaBase>();
visitor.undecidedLambdas.Add(this);
Log.WriteLine("Added undecided explicitly-typed lambda: " + this.LambdaExpression);
}
public override IList<IParameter> Parameters {
get {
return parameters ?? EmptyList<IParameter>.Instance;
}
}
bool Analyze()
{
// If it's not already analyzed
if (inferredReturnType == null) {
Log.WriteLine("Analyzing " + this.LambdaExpression + "...");
Log.Indent();
visitor.ResetContext(
storedContext,
delegate {
var oldNavigator = visitor.navigator;
visitor.navigator = new ConstantModeResolveVisitorNavigator(ResolveVisitorNavigationMode.Resolve, oldNavigator);
visitor.AnalyzeLambda(body, isAsync, out isValidAsVoidMethod, out isEndpointUnreachable, out inferredReturnType, out returnExpressions, out returnValues);
visitor.navigator = oldNavigator;
});
Log.Unindent();
Log.WriteLine("Finished analyzing " + this.LambdaExpression);
if (inferredReturnType == null)
throw new InvalidOperationException("AnalyzeLambda() didn't set inferredReturnType");
}
return true;
}
public override Conversion IsValid(IType[] parameterTypes, IType returnType, CSharpConversions conversions)
{
Log.WriteLine("Testing validity of {0} for return-type {1}...", this, returnType);
Log.Indent();
bool valid = Analyze() && IsValidLambda(isValidAsVoidMethod, isEndpointUnreachable, isAsync, returnValues, returnType, conversions);
Log.Unindent();
Log.WriteLine("{0} is {1} for return-type {2}", this, valid ? "valid" : "invalid", returnType);
return new AnonymousFunctionConversion(returnType, this, valid);
}
public override IType GetInferredReturnType(IType[] parameterTypes)
{
Analyze();
return inferredReturnType;
}
public override bool IsImplicitlyTyped {
get { return false; }
}
public override bool IsAsync {
get { return isAsync; }
}
public override bool IsAnonymousMethod {
get { return isAnonymousMethod; }
}
public override bool HasParameterList {
get { return parameters != null; }
}
public override string ToString()
{
return "[ExplicitlyTypedLambda " + this.LambdaExpression + "]";
}
public void ApplyReturnType(ResolveVisitor parentVisitor, IType returnType)
{
if (returnType == null)
throw new ArgumentNullException("returnType");
if (parentVisitor != visitor) {
// Explicitly typed lambdas do not use a nested visitor
throw new InvalidOperationException();
}
if (actualReturnType != null) {
if (actualReturnType.Equals(returnType))
return; // return type already set
throw new InvalidOperationException("inconsistent return types for explicitly-typed lambda");
}
actualReturnType = returnType;
visitor.undecidedLambdas.Remove(this);
Analyze();
Log.WriteLine("Applying return type {0} to explicitly-typed lambda {1}", returnType, this.LambdaExpression);
if (isAsync)
returnType = parentVisitor.UnpackTask(returnType);
if (returnType.Kind != TypeKind.Void) {
for (int i = 0; i < returnExpressions.Count; i++) {
visitor.ProcessConversion(returnExpressions[i], returnValues[i], returnType);
}
}
}
internal override void EnforceMerge(ResolveVisitor parentVisitor)
{
ApplyReturnType(parentVisitor, SpecialType.UnknownType);
}
}
#endregion
#region Implicitly typed
// Implicitly-typed lambdas are really complex, as the lambda depends on the target type (the delegate to which
// the lambda is converted), but figuring out the target type might involve overload resolution (for method
// calls in which the lambda is used as argument), which requires knowledge about the lamdba.
//
// The implementation in NRefactory works like this:
// 1. The lambda resolves to a ImplicitlyTypedLambda (derived from LambdaResolveResult).
// The lambda body is not resolved yet (one of the few places where ResolveVisitor
// deviates from the usual depth-first AST traversal).
// 2. The parent statement is resolved as usual. This might require analyzing the lambda in detail (for example
// as part of overload resolution). Such analysis happens using LambdaResolveResult.IsValid, where the caller
// (i.e. the overload resolution algorithm) supplies the parameter types to the lambda body. For every IsValid()
// call, a nested LambdaTypeHypothesis is constructed for analyzing the lambda using the supplied type assignment.
// Multiple IsValid() calls may use several LambdaTypeHypothesis instances, one for each set of parameter types.
// 3. When the resolver reports the conversions that occurred as part of the parent statement (as with any
// conversions), the results from the LambdaTypeHypothesis corresponding to the actually chosen
// conversion are merged into the main resolver.
// 4. LambdaResolveResult.Body is set to the main resolve result from the chosen nested resolver. I think this
// is the only place where NRefactory is mutating a ResolveResult (normally all resolve results are immutable).
// As this step is guaranteed to occur before the resolver returns the LamdbaResolveResult to user code, the
// mutation shouldn't cause any problems.
sealed class ImplicitlyTypedLambda : LambdaBase
{
readonly LambdaExpression lambda;
readonly QuerySelectClause selectClause;
readonly CSharpResolver storedContext;
readonly CSharpUnresolvedFile unresolvedFile;
readonly List<LambdaTypeHypothesis> hypotheses = new List<LambdaTypeHypothesis>();
internal IList<IParameter> parameters = new List<IParameter>();
internal LambdaTypeHypothesis winningHypothesis;
internal ResolveResult bodyResult;
internal readonly ResolveVisitor parentVisitor;
internal override bool IsUndecided {
get { return winningHypothesis == null; }
}
internal override AstNode LambdaExpression {
get {
if (selectClause != null)
return selectClause.Expression;
else
return lambda;
}
}
internal override AstNode BodyExpression {
get {
if (selectClause != null)
return selectClause.Expression;
else
return lambda.Body;
}
}
public override ResolveResult Body {
get { return bodyResult; }
}
private ImplicitlyTypedLambda(ResolveVisitor parentVisitor)
{
this.parentVisitor = parentVisitor;
this.storedContext = parentVisitor.resolver;
this.unresolvedFile = parentVisitor.unresolvedFile;
this.bodyResult = parentVisitor.voidResult;
}
public ImplicitlyTypedLambda(LambdaExpression lambda, ResolveVisitor parentVisitor)
: this(parentVisitor)
{
this.lambda = lambda;
foreach (var pd in lambda.Parameters) {
parameters.Add(new DefaultParameter(SpecialType.UnknownType, pd.Name, parentVisitor.MakeRegion(pd)));
}
RegisterUndecidedLambda();
}
public ImplicitlyTypedLambda(QuerySelectClause selectClause, IEnumerable<IParameter> parameters, ResolveVisitor parentVisitor)
: this(parentVisitor)
{
this.selectClause = selectClause;
foreach (IParameter p in parameters)
this.parameters.Add(p);
RegisterUndecidedLambda();
}
void RegisterUndecidedLambda()
{
if (parentVisitor.undecidedLambdas == null)
parentVisitor.undecidedLambdas = new List<LambdaBase>();
parentVisitor.undecidedLambdas.Add(this);
Log.WriteLine("Added undecided implicitly-typed lambda: " + this.LambdaExpression);
}
public override IList<IParameter> Parameters {
get { return parameters; }
}
public override Conversion IsValid(IType[] parameterTypes, IType returnType, CSharpConversions conversions)
{
Log.WriteLine("Testing validity of {0} for parameters ({1}) and return-type {2}...",
this, string.Join<IType>(", ", parameterTypes), returnType);
Log.Indent();
var hypothesis = GetHypothesis(parameterTypes);
Conversion c = hypothesis.IsValid(returnType, conversions);
Log.Unindent();
Log.WriteLine("{0} is {1} for return-type {2}", hypothesis, c.IsValid ? "valid" : "invalid", returnType);
return c;
}
public override IType GetInferredReturnType(IType[] parameterTypes)
{
return GetHypothesis(parameterTypes).inferredReturnType;
}
LambdaTypeHypothesis GetHypothesis(IType[] parameterTypes)
{
if (parameterTypes.Length != parameters.Count)
throw new ArgumentException("Incorrect parameter type count");
foreach (var h in hypotheses) {
bool ok = true;
for (int i = 0; i < parameterTypes.Length; i++) {
if (!parameterTypes[i].Equals(h.parameterTypes[i])) {
ok = false;
break;
}
}
if (ok)
return h;
}
ResolveVisitor visitor = new ResolveVisitor(storedContext, unresolvedFile);
var newHypothesis = new LambdaTypeHypothesis(this, parameterTypes, visitor, lambda != null ? lambda.Parameters : null);
hypotheses.Add(newHypothesis);
return newHypothesis;
}
/// <summary>
/// Get any hypothesis for this lambda.
/// This method is used as fallback if the lambda isn't merged the normal way (AnonymousFunctionConversion)
/// </summary>
internal LambdaTypeHypothesis GetAnyHypothesis()
{
if (winningHypothesis != null)
return winningHypothesis;
if (hypotheses.Count == 0) {
// make a new hypothesis with unknown parameter types
IType[] parameterTypes = new IType[parameters.Count];
for (int i = 0; i < parameterTypes.Length; i++) {
parameterTypes[i] = SpecialType.UnknownType;
}
return GetHypothesis(parameterTypes);
} else {
// We have the choice, so pick the hypothesis with the least missing parameter types
LambdaTypeHypothesis bestHypothesis = hypotheses[0];
int bestHypothesisUnknownParameters = bestHypothesis.CountUnknownParameters();
for (int i = 1; i < hypotheses.Count; i++) {
int c = hypotheses[i].CountUnknownParameters();
if (c < bestHypothesisUnknownParameters ||
(c == bestHypothesisUnknownParameters && hypotheses[i].success && !bestHypothesis.success))
{
bestHypothesis = hypotheses[i];
bestHypothesisUnknownParameters = c;
}
}
return bestHypothesis;
}
}
internal override void EnforceMerge(ResolveVisitor parentVisitor)
{
GetAnyHypothesis().MergeInto(parentVisitor, SpecialType.UnknownType);
}
public override bool IsImplicitlyTyped {
get { return true; }
}
public override bool IsAnonymousMethod {
get { return false; }
}
public override bool HasParameterList {
get { return true; }
}
public override bool IsAsync {
get { return lambda != null && lambda.IsAsync; }
}
public override string ToString()
{
return "[ImplicitlyTypedLambda " + this.LambdaExpression + "]";
}
}
/// <summary>
/// Every possible set of parameter types gets its own 'hypothetical world'.
/// It uses a nested ResolveVisitor that has its own resolve cache, so that resolve results cannot leave the hypothetical world.
///
/// Only after overload resolution is applied and the actual parameter types are known, the winning hypothesis will be merged
/// with the parent ResolveVisitor.
/// This is done when the AnonymousFunctionConversion is applied on the parent visitor.
/// </summary>
sealed class LambdaTypeHypothesis : IResolveVisitorNavigator
{
readonly ImplicitlyTypedLambda lambda;
readonly IParameter[] lambdaParameters;
internal readonly IType[] parameterTypes;
readonly ResolveVisitor visitor;
internal readonly IType inferredReturnType;
IList<Expression> returnExpressions;
IList<ResolveResult> returnValues;
bool isValidAsVoidMethod;
bool isEndpointUnreachable;
internal bool success;
public LambdaTypeHypothesis(ImplicitlyTypedLambda lambda, IType[] parameterTypes, ResolveVisitor visitor,
ICollection<ParameterDeclaration> parameterDeclarations)
{
Debug.Assert(parameterTypes.Length == lambda.Parameters.Count);
this.lambda = lambda;
this.parameterTypes = parameterTypes;
this.visitor = visitor;
visitor.SetNavigator(this);
Log.WriteLine("Analyzing " + ToString() + "...");
Log.Indent();
CSharpResolver oldResolver = visitor.resolver;
visitor.resolver = visitor.resolver.WithIsWithinLambdaExpression(true);
lambdaParameters = new IParameter[parameterTypes.Length];
if (parameterDeclarations != null) {
int i = 0;
foreach (var pd in parameterDeclarations) {
lambdaParameters[i] = new DefaultParameter(parameterTypes[i], pd.Name, visitor.MakeRegion(pd));
visitor.resolver = visitor.resolver.AddVariable(lambdaParameters[i]);
i++;
visitor.Scan(pd);
}
} else {
for (int i = 0; i < parameterTypes.Length; i++) {
var p = lambda.Parameters[i];
lambdaParameters[i] = new DefaultParameter(parameterTypes[i], p.Name, p.Region);
visitor.resolver = visitor.resolver.AddVariable(lambdaParameters[i]);
}
}
success = true;
visitor.AnalyzeLambda(lambda.BodyExpression, lambda.IsAsync, out isValidAsVoidMethod, out isEndpointUnreachable, out inferredReturnType, out returnExpressions, out returnValues);
visitor.resolver = oldResolver;
Log.Unindent();
Log.WriteLine("Finished analyzing " + ToString());
}
ResolveVisitorNavigationMode IResolveVisitorNavigator.Scan(AstNode node)
{
return ResolveVisitorNavigationMode.Resolve;
}
void IResolveVisitorNavigator.Resolved(AstNode node, ResolveResult result)
{
if (result.IsError)
success = false;
}
void IResolveVisitorNavigator.ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType)
{
success &= conversion.IsValid;
}
internal int CountUnknownParameters()
{
int c = 0;
foreach (IType t in parameterTypes) {
if (t.Kind == TypeKind.Unknown)
c++;
}
return c;
}
public Conversion IsValid(IType returnType, CSharpConversions conversions)
{
bool valid = success && IsValidLambda(isValidAsVoidMethod, isEndpointUnreachable, lambda.IsAsync, returnValues, returnType, conversions);
return new AnonymousFunctionConversion(returnType, this, valid);
}
public void MergeInto(ResolveVisitor parentVisitor, IType returnType)
{
if (returnType == null)
throw new ArgumentNullException("returnType");
if (parentVisitor != lambda.parentVisitor)
throw new InvalidOperationException("parent visitor mismatch");
if (lambda.winningHypothesis == this)
return;
else if (lambda.winningHypothesis != null)
throw new InvalidOperationException("Trying to merge conflicting hypotheses");
lambda.winningHypothesis = this;
lambda.parameters = lambdaParameters; // replace untyped parameters with typed parameters
if (lambda.BodyExpression is Expression && returnValues.Count == 1) {
lambda.bodyResult = returnValues[0];
}
Log.WriteLine("Applying return type {0} to implicitly-typed lambda {1}", returnType, lambda.LambdaExpression);
if (lambda.IsAsync)
returnType = parentVisitor.UnpackTask(returnType);
if (returnType.Kind != TypeKind.Void) {
for (int i = 0; i < returnExpressions.Count; i++) {
visitor.ProcessConversion(returnExpressions[i], returnValues[i], returnType);
}
}
visitor.MergeUndecidedLambdas();
Log.WriteLine("Merging " + ToString());
foreach (var pair in visitor.resolverBeforeDict) {
Debug.Assert(!parentVisitor.resolverBeforeDict.ContainsKey(pair.Key));
parentVisitor.resolverBeforeDict[pair.Key] = pair.Value;
}
foreach (var pair in visitor.resolverAfterDict) {
Debug.Assert(!parentVisitor.resolverAfterDict.ContainsKey(pair.Key));
parentVisitor.resolverAfterDict[pair.Key] = pair.Value;
}
foreach (var pair in visitor.resolveResultCache) {
parentVisitor.StoreResult(pair.Key, pair.Value);
}
parentVisitor.ImportConversions(visitor);
parentVisitor.undecidedLambdas.Remove(lambda);
}
public override string ToString()
{
StringBuilder b = new StringBuilder();
b.Append("[LambdaTypeHypothesis (");
for (int i = 0; i < parameterTypes.Length; i++) {
if (i > 0) b.Append(", ");
b.Append(parameterTypes[i]);
b.Append(' ');
b.Append(lambda.Parameters[i].Name);
}
b.Append(") => ");
b.Append(lambda.BodyExpression.ToString());
b.Append(']');
return b.ToString();
}
}
#endregion
#region MergeUndecidedLambdas
abstract class LambdaBase : LambdaResolveResult
{
internal abstract bool IsUndecided { get; }
internal abstract AstNode LambdaExpression { get; }
internal abstract AstNode BodyExpression { get; }
internal abstract void EnforceMerge(ResolveVisitor parentVisitor);
public override ResolveResult ShallowClone()
{
if (IsUndecided)
throw new NotSupportedException();
return base.ShallowClone();
}
}
void MergeUndecidedLambdas()
{
if (undecidedLambdas == null || undecidedLambdas.Count == 0)
return;
Log.WriteLine("MergeUndecidedLambdas()...");
Log.Indent();
while (undecidedLambdas.Count > 0) {
LambdaBase lambda = undecidedLambdas[0];
ResolveParentForConversion(lambda.LambdaExpression);
if (lambda.IsUndecided) {
// Lambda wasn't merged by resolving its parent -> enforce merging
Log.WriteLine("Lambda wasn't merged by conversion - enforce merging");
lambda.EnforceMerge(this);
}
}
Log.Unindent();
Log.WriteLine("MergeUndecidedLambdas() finished.");
}
void ResolveParentForConversion(AstNode expression)
{
AstNode parent = expression.Parent;
// Continue going upwards until we find a node that can be resolved and provides
// an expected type.
while (ParenthesizedExpression.ActsAsParenthesizedExpression(parent) || CSharpAstResolver.IsUnresolvableNode(parent)) {
parent = parent.Parent;
}
CSharpResolver storedResolver;
if (parent != null && resolverBeforeDict.TryGetValue(parent, out storedResolver)) {
Log.WriteLine("Trying to resolve '" + parent + "' in order to find the conversion applied to '" + expression + "'...");
Log.Indent();
ResetContext(storedResolver, delegate { Resolve(parent); });
Log.Unindent();
} else {
Log.WriteLine("Could not find a suitable parent for '" + expression + "'");
}
}
#endregion
#region AnalyzeLambda
IType GetTaskType(IType resultType)
{
if (resultType.Kind == TypeKind.Unknown)
return SpecialType.UnknownType;
if (resultType.Kind == TypeKind.Void)
return resolver.Compilation.FindType(KnownTypeCode.Task);
ITypeDefinition def = resolver.Compilation.FindType(KnownTypeCode.TaskOfT).GetDefinition();
if (def != null)
return new ParameterizedType(def, new[] { resultType });
else
return SpecialType.UnknownType;
}
void AnalyzeLambda(AstNode body, bool isAsync, out bool isValidAsVoidMethod, out bool isEndpointUnreachable, out IType inferredReturnType, out IList<Expression> returnExpressions, out IList<ResolveResult> returnValues)
{
isEndpointUnreachable = false;
Expression expr = body as Expression;
if (expr != null) {
isValidAsVoidMethod = ExpressionPermittedAsStatement(expr);
returnExpressions = new [] { expr };
returnValues = new[] { Resolve(expr) };
inferredReturnType = returnValues[0].Type;
} else {
Scan(body);
AnalyzeLambdaVisitor alv = new AnalyzeLambdaVisitor();
body.AcceptVisitor(alv);
isValidAsVoidMethod = (alv.ReturnExpressions.Count == 0);
if (alv.HasVoidReturnStatements) {
returnExpressions = EmptyList<Expression>.Instance;
returnValues = EmptyList<ResolveResult>.Instance;
inferredReturnType = resolver.Compilation.FindType(KnownTypeCode.Void);
} else {
returnExpressions = alv.ReturnExpressions;
returnValues = new ResolveResult[returnExpressions.Count];
for (int i = 0; i < returnValues.Count; i++) {
returnValues[i] = resolveResultCache[returnExpressions[i]];
}
TypeInference ti = new TypeInference(resolver.Compilation, resolver.conversions);
bool tiSuccess;
inferredReturnType = ti.GetBestCommonType(returnValues, out tiSuccess);
// Failure to infer a return type does not make the lambda invalid,
// so we can ignore the 'tiSuccess' value
if (isValidAsVoidMethod && returnExpressions.Count == 0 && body is Statement) {
var reachabilityAnalysis = ReachabilityAnalysis.Create(
(Statement)body, (node, _) => resolveResultCache[node],
resolver.CurrentTypeResolveContext, cancellationToken);
isEndpointUnreachable = !reachabilityAnalysis.IsEndpointReachable((Statement)body);
}
}
}
if (isAsync)
inferredReturnType = GetTaskType(inferredReturnType);
Log.WriteLine("Lambda return type was inferred to: " + inferredReturnType);
}
static bool ExpressionPermittedAsStatement(Expression expr)
{
UnaryOperatorExpression uoe = expr as UnaryOperatorExpression;
if (uoe != null) {
switch (uoe.Operator) {
case UnaryOperatorType.Increment:
case UnaryOperatorType.Decrement:
case UnaryOperatorType.PostIncrement:
case UnaryOperatorType.PostDecrement:
case UnaryOperatorType.Await:
return true;
default:
return false;
}
}
return expr is InvocationExpression
|| expr is ObjectCreateExpression
|| expr is AssignmentExpression;
}
static bool IsValidLambda(bool isValidAsVoidMethod, bool isEndpointUnreachable, bool isAsync, IList<ResolveResult> returnValues, IType returnType, CSharpConversions conversions)
{
if (returnType.Kind == TypeKind.Void) {
// Lambdas that are valid statement lambdas or expression lambdas with a statement-expression
// can be converted to delegates with void return type.
// This holds for both async and regular lambdas.
return isValidAsVoidMethod;
} else if (isAsync && IsTask(returnType) && returnType.TypeParameterCount == 0) {
// Additionally, async lambdas with the above property can be converted to non-generic Task.
return isValidAsVoidMethod;
} else {
if (returnValues.Count == 0)
return isEndpointUnreachable;
if (isAsync) {
// async lambdas must return Task<T>
if (!(IsTask(returnType) && returnType.TypeParameterCount == 1))
return false;
// unpack Task<T> for testing the implicit conversions
returnType = ((ParameterizedType)returnType).GetTypeArgument(0);
}
foreach (ResolveResult returnRR in returnValues) {
if (!conversions.ImplicitConversion(returnRR, returnType).IsValid)
return false;
}
return true;
}
}
/// <summary>
/// Gets the T in Task<T>.
/// Returns void for non-generic Task.
/// </summary>
IType UnpackTask(IType type)
{
if (!IsTask(type))
return type;
if (type.TypeParameterCount == 0)
return resolver.Compilation.FindType(KnownTypeCode.Void);
else
return ((ParameterizedType)type).GetTypeArgument(0);
}
/// <summary>
/// Gets whether the specified type is Task or Task<T>.
/// </summary>
static bool IsTask(IType type)
{
ITypeDefinition def = type.GetDefinition();
if (def != null) {
if (def.KnownTypeCode == KnownTypeCode.Task)
return true;
if (def.KnownTypeCode == KnownTypeCode.TaskOfT)
return type is ParameterizedType;
}
return false;
}
sealed class AnalyzeLambdaVisitor : DepthFirstAstVisitor
{
public bool HasVoidReturnStatements;
public List<Expression> ReturnExpressions = new List<Expression>();
public override void VisitReturnStatement(ReturnStatement returnStatement)
{
Expression expr = returnStatement.Expression;
if (expr.IsNull) {
HasVoidReturnStatements = true;
} else {
ReturnExpressions.Add(expr);
}
}
public override void VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression)
{
// don't go into nested lambdas
}
public override void VisitLambdaExpression(LambdaExpression lambdaExpression)
{
// don't go into nested lambdas
}
}
#endregion
#endregion
#region ForEach Statement
ResolveResult IAstVisitor<ResolveResult>.VisitForeachStatement(ForeachStatement foreachStatement)
{
var compilation = resolver.Compilation;
ResolveResult expression = Resolve(foreachStatement.InExpression);
bool isImplicitlyTypedVariable = IsVar(foreachStatement.VariableType);
var memberLookup = resolver.CreateMemberLookup();
IType collectionType, enumeratorType, elementType;
ResolveResult getEnumeratorInvocation;
ResolveResult currentRR = null;
// C# 4.0 spec: §8.8.4 The foreach statement
if (expression.Type.Kind == TypeKind.Array || expression.Type.Kind == TypeKind.Dynamic) {
collectionType = compilation.FindType(KnownTypeCode.IEnumerable);
enumeratorType = compilation.FindType(KnownTypeCode.IEnumerator);
if (expression.Type.Kind == TypeKind.Array) {
elementType = ((ArrayType)expression.Type).ElementType;
} else {
elementType = isImplicitlyTypedVariable ? SpecialType.Dynamic : compilation.FindType(KnownTypeCode.Object);
}
getEnumeratorInvocation = resolver.ResolveCast(collectionType, expression);
getEnumeratorInvocation = resolver.ResolveMemberAccess(getEnumeratorInvocation, "GetEnumerator", EmptyList<IType>.Instance, NameLookupMode.InvocationTarget);
getEnumeratorInvocation = resolver.ResolveInvocation(getEnumeratorInvocation, new ResolveResult[0]);
} else {
var getEnumeratorMethodGroup = memberLookup.Lookup(expression, "GetEnumerator", EmptyList<IType>.Instance, true) as MethodGroupResolveResult;
if (getEnumeratorMethodGroup != null) {
var or = getEnumeratorMethodGroup.PerformOverloadResolution(compilation, new ResolveResult[0]);
if (or.FoundApplicableCandidate && !or.IsAmbiguous && !or.BestCandidate.IsStatic && or.BestCandidate.IsPublic) {
collectionType = expression.Type;
getEnumeratorInvocation = or.CreateResolveResult(expression);
enumeratorType = getEnumeratorInvocation.Type;
currentRR = memberLookup.Lookup(new ResolveResult(enumeratorType), "Current", EmptyList<IType>.Instance, false);
elementType = currentRR.Type;
} else {
CheckForEnumerableInterface(expression, out collectionType, out enumeratorType, out elementType, out getEnumeratorInvocation);
}
} else {
CheckForEnumerableInterface(expression, out collectionType, out enumeratorType, out elementType, out getEnumeratorInvocation);
}
}
IMethod moveNextMethod = null;
var moveNextMethodGroup = memberLookup.Lookup(new ResolveResult(enumeratorType), "MoveNext", EmptyList<IType>.Instance, false) as MethodGroupResolveResult;
if (moveNextMethodGroup != null) {
var or = moveNextMethodGroup.PerformOverloadResolution(compilation, new ResolveResult[0]);
moveNextMethod = or.GetBestCandidateWithSubstitutedTypeArguments() as IMethod;
}
if (currentRR == null)
currentRR = memberLookup.Lookup(new ResolveResult(enumeratorType), "Current", EmptyList<IType>.Instance, false);
IProperty currentProperty = null;
if (currentRR is MemberResolveResult)
currentProperty = ((MemberResolveResult)currentRR).Member as IProperty;
// end of foreach resolve logic
// back to resolve visitor:
resolver = resolver.PushBlock();
IVariable v;
if (isImplicitlyTypedVariable) {
StoreCurrentState(foreachStatement.VariableType);
StoreResult(foreachStatement.VariableType, new TypeResolveResult(elementType));
v = MakeVariable(elementType, foreachStatement.VariableNameToken);
} else {
IType variableType = ResolveType(foreachStatement.VariableType);
v = MakeVariable(variableType, foreachStatement.VariableNameToken);
}
StoreCurrentState(foreachStatement.VariableNameToken);
resolver = resolver.AddVariable(v);
StoreResult(foreachStatement.VariableNameToken, new LocalResolveResult(v));
Scan(foreachStatement.EmbeddedStatement);
resolver = resolver.PopBlock();
return new ForEachResolveResult(getEnumeratorInvocation, collectionType, enumeratorType, elementType,
v, currentProperty, moveNextMethod, voidResult.Type);
}
void CheckForEnumerableInterface(ResolveResult expression, out IType collectionType, out IType enumeratorType, out IType elementType, out ResolveResult getEnumeratorInvocation)
{
var compilation = resolver.Compilation;
bool? isGeneric;
elementType = GetElementTypeFromIEnumerable(expression.Type, compilation, false, out isGeneric);
if (isGeneric == true) {
ITypeDefinition enumerableOfT = compilation.FindType(KnownTypeCode.IEnumerableOfT).GetDefinition();
if (enumerableOfT != null)
collectionType = new ParameterizedType(enumerableOfT, new [] { elementType });
else
collectionType = SpecialType.UnknownType;
ITypeDefinition enumeratorOfT = compilation.FindType(KnownTypeCode.IEnumeratorOfT).GetDefinition();
if (enumeratorOfT != null)
enumeratorType = new ParameterizedType(enumeratorOfT, new [] { elementType });
else
enumeratorType = SpecialType.UnknownType;
} else if (isGeneric == false) {
collectionType = compilation.FindType(KnownTypeCode.IEnumerable);
enumeratorType = compilation.FindType(KnownTypeCode.IEnumerator);
} else {
collectionType = SpecialType.UnknownType;
enumeratorType = SpecialType.UnknownType;
}
getEnumeratorInvocation = resolver.ResolveCast(collectionType, expression);
getEnumeratorInvocation = resolver.ResolveMemberAccess(getEnumeratorInvocation, "GetEnumerator", EmptyList<IType>.Instance, NameLookupMode.InvocationTarget);
getEnumeratorInvocation = resolver.ResolveInvocation(getEnumeratorInvocation, new ResolveResult[0]);
}
#endregion
#region Local Variable Scopes (Block Statements)
ResolveResult IAstVisitor<ResolveResult>.VisitBlockStatement(BlockStatement blockStatement)
{
resolver = resolver.PushBlock();
ScanChildren(blockStatement);
resolver = resolver.PopBlock();
return voidResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitUsingStatement(UsingStatement usingStatement)
{
resolver = resolver.PushBlock();
if (resolverEnabled) {
for (AstNode child = usingStatement.FirstChild; child != null; child = child.NextSibling) {
if (child.Role == UsingStatement.ResourceAcquisitionRole && child is Expression) {
ResolveAndProcessConversion((Expression)child, resolver.Compilation.FindType(KnownTypeCode.IDisposable));
} else {
Scan(child);
}
}
} else {
ScanChildren(usingStatement);
}
resolver = resolver.PopBlock();
return resolverEnabled ? voidResult : null;
}
ResolveResult IAstVisitor<ResolveResult>.VisitFixedStatement(FixedStatement fixedStatement)
{
resolver = resolver.PushBlock();
IType type = ResolveType(fixedStatement.Type);
foreach (VariableInitializer vi in fixedStatement.Variables) {
resolver = resolver.AddVariable(MakeVariable(type, vi.NameToken));
Scan(vi);
}
Scan(fixedStatement.EmbeddedStatement);
resolver = resolver.PopBlock();
return voidResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitSwitchStatement(SwitchStatement switchStatement)
{
resolver = resolver.PushBlock();
ScanChildren(switchStatement);
resolver = resolver.PopBlock();
return voidResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitCatchClause(CatchClause catchClause)
{
resolver = resolver.PushBlock();
if (string.IsNullOrEmpty(catchClause.VariableName)) {
Scan(catchClause.Type);
} else {
//DomRegion region = MakeRegion(catchClause.VariableNameToken);
StoreCurrentState(catchClause.VariableNameToken);
IVariable v = MakeVariable(ResolveType(catchClause.Type), catchClause.VariableNameToken);
resolver = resolver.AddVariable(v);
StoreResult(catchClause.VariableNameToken, new LocalResolveResult(v));
}
Scan(catchClause.Body);
resolver = resolver.PopBlock();
return voidResult;
}
#endregion
#region VariableDeclarationStatement
ResolveResult IAstVisitor<ResolveResult>.VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
{
bool isConst = (variableDeclarationStatement.Modifiers & Modifiers.Const) != 0;
if (!isConst && IsVar(variableDeclarationStatement.Type) && variableDeclarationStatement.Variables.Count == 1) {
VariableInitializer vi = variableDeclarationStatement.Variables.Single();
StoreCurrentState(variableDeclarationStatement.Type);
IType type = Resolve(vi.Initializer).Type;
StoreResult(variableDeclarationStatement.Type, new TypeResolveResult(type));
IVariable v = MakeVariable(type, vi.NameToken);
resolver = resolver.AddVariable(v);
Scan(vi);
} else {
IType type = ResolveType(variableDeclarationStatement.Type);
foreach (VariableInitializer vi in variableDeclarationStatement.Variables) {
IVariable v;
if (isConst) {
v = MakeConstant(type, vi.NameToken, Resolve(vi.Initializer).ConstantValue);
} else {
v = MakeVariable(type, vi.NameToken);
}
resolver = resolver.AddVariable(v);
Scan(vi);
}
}
return voidResult;
}
#endregion
#region Condition Statements
ResolveResult IAstVisitor<ResolveResult>.VisitForStatement(ForStatement forStatement)
{
resolver = resolver.PushBlock();
var result = HandleConditionStatement(forStatement);
resolver = resolver.PopBlock();
return result;
}
ResolveResult IAstVisitor<ResolveResult>.VisitIfElseStatement(IfElseStatement ifElseStatement)
{
return HandleConditionStatement(ifElseStatement);
}
ResolveResult IAstVisitor<ResolveResult>.VisitWhileStatement(WhileStatement whileStatement)
{
return HandleConditionStatement(whileStatement);
}
ResolveResult IAstVisitor<ResolveResult>.VisitDoWhileStatement(DoWhileStatement doWhileStatement)
{
return HandleConditionStatement(doWhileStatement);
}
ResolveResult HandleConditionStatement(Statement conditionStatement)
{
if (resolverEnabled) {
for (AstNode child = conditionStatement.FirstChild; child != null; child = child.NextSibling) {
if (child.Role == Roles.Condition) {
Expression condition = (Expression)child;
ResolveResult conditionRR = Resolve(condition);
ResolveResult convertedRR = resolver.ResolveCondition(conditionRR);
if (convertedRR != conditionRR)
ProcessConversionResult(condition, convertedRR as ConversionResolveResult);
} else {
Scan(child);
}
}
return voidResult;
} else {
ScanChildren(conditionStatement);
return null;
}
}
#endregion
#region Return Statements
ResolveResult IAstVisitor<ResolveResult>.VisitReturnStatement(ReturnStatement returnStatement)
{
if (resolverEnabled && !resolver.IsWithinLambdaExpression && resolver.CurrentMember != null) {
IType type = resolver.CurrentMember.ReturnType;
if (IsTask(type)) {
var methodDecl = returnStatement.Ancestors.OfType<EntityDeclaration>().FirstOrDefault();
if (methodDecl != null && (methodDecl.Modifiers & Modifiers.Async) == Modifiers.Async)
type = UnpackTask(type);
}
ResolveAndProcessConversion(returnStatement.Expression, type);
} else {
Scan(returnStatement.Expression);
}
return resolverEnabled ? voidResult : null;
}
ResolveResult IAstVisitor<ResolveResult>.VisitYieldReturnStatement(YieldReturnStatement yieldStatement)
{
if (resolverEnabled && resolver.CurrentMember != null) {
IType returnType = resolver.CurrentMember.ReturnType;
bool? isGeneric;
IType elementType = GetElementTypeFromIEnumerable(returnType, resolver.Compilation, true, out isGeneric);
ResolveAndProcessConversion(yieldStatement.Expression, elementType);
} else {
Scan(yieldStatement.Expression);
}
return resolverEnabled ? voidResult : null;
}
ResolveResult IAstVisitor<ResolveResult>.VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement)
{
return voidResult;
}
#endregion
#region Other statements
ResolveResult IAstVisitor<ResolveResult>.VisitExpressionStatement(ExpressionStatement expressionStatement)
{
ScanChildren(expressionStatement);
return voidResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitLockStatement(LockStatement lockStatement)
{
ScanChildren(lockStatement);
return voidResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitEmptyStatement(EmptyStatement emptyStatement)
{
return voidResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitBreakStatement(BreakStatement breakStatement)
{
return voidResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitContinueStatement(ContinueStatement continueStatement)
{
return voidResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitThrowStatement(ThrowStatement throwStatement)
{
if (resolverEnabled) {
ResolveAndProcessConversion(throwStatement.Expression, resolver.Compilation.FindType(KnownTypeCode.Exception));
return voidResult;
} else {
Scan(throwStatement.Expression);
return null;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitTryCatchStatement(TryCatchStatement tryCatchStatement)
{
ScanChildren(tryCatchStatement);
return voidResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement)
{
ScanChildren(gotoCaseStatement);
return voidResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement)
{
return voidResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitGotoStatement(GotoStatement gotoStatement)
{
return voidResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitLabelStatement(LabelStatement labelStatement)
{
return voidResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitUnsafeStatement(UnsafeStatement unsafeStatement)
{
resolver = resolver.PushBlock();
ScanChildren(unsafeStatement);
resolver = resolver.PopBlock();
return voidResult;
}
#endregion
#region Local Variable Type Inference
static bool IsVar(AstNode returnType)
{
SimpleType st = returnType as SimpleType;
return st != null && st.Identifier == "var" && st.TypeArguments.Count == 0;
}
IVariable MakeVariable(IType type, Identifier variableName)
{
return new SimpleVariable(MakeRegion(variableName), type, variableName.Name);
}
IVariable MakeConstant(IType type, Identifier variableName, object constantValue)
{
return new SimpleConstant(MakeRegion(variableName), type, variableName.Name, constantValue);
}
class SimpleVariable : IVariable
{
readonly DomRegion region;
readonly IType type;
readonly string name;
public SimpleVariable(DomRegion region, IType type, string name)
{
Debug.Assert(type != null);
Debug.Assert(name != null);
this.region = region;
this.type = type;
this.name = name;
}
public string Name {
get { return name; }
}
public DomRegion Region {
get { return region; }
}
public IType Type {
get { return type; }
}
public virtual bool IsConst {
get { return false; }
}
public virtual object ConstantValue {
get { return null; }
}
public override string ToString()
{
return type.ToString() + " " + name + ";";
}
}
sealed class SimpleConstant : SimpleVariable
{
readonly object constantValue;
public SimpleConstant(DomRegion region, IType type, string name, object constantValue)
: base(region, type, name)
{
this.constantValue = constantValue;
}
public override bool IsConst {
get { return true; }
}
public override object ConstantValue {
get { return constantValue; }
}
public override string ToString()
{
return Type.ToString() + " " + Name + " = " + new PrimitiveExpression(constantValue).ToString() + ";";
}
}
static IType GetElementTypeFromIEnumerable(IType collectionType, ICompilation compilation, bool allowIEnumerator, out bool? isGeneric)
{
bool foundNonGenericIEnumerable = false;
foreach (IType baseType in collectionType.GetAllBaseTypes()) {
ITypeDefinition baseTypeDef = baseType.GetDefinition();
if (baseTypeDef != null) {
KnownTypeCode typeCode = baseTypeDef.KnownTypeCode;
if (typeCode == KnownTypeCode.IEnumerableOfT || (allowIEnumerator && typeCode == KnownTypeCode.IEnumeratorOfT)) {
ParameterizedType pt = baseType as ParameterizedType;
if (pt != null) {
isGeneric = true;
return pt.GetTypeArgument(0);
}
}
if (typeCode == KnownTypeCode.IEnumerable || (allowIEnumerator && typeCode == KnownTypeCode.IEnumerator))
foundNonGenericIEnumerable = true;
}
}
// System.Collections.IEnumerable found in type hierarchy -> Object is element type.
if (foundNonGenericIEnumerable) {
isGeneric = false;
return compilation.FindType(KnownTypeCode.Object);
}
isGeneric = null;
return SpecialType.UnknownType;
}
#endregion
#region Attributes
ResolveResult IAstVisitor<ResolveResult>.VisitAttribute(Attribute attribute)
{
var type = ResolveType(attribute.Type);
// Separate arguments into ctor arguments and non-ctor arguments:
var constructorArguments = attribute.Arguments.Where(a => !(a is NamedExpression));
var nonConstructorArguments = attribute.Arguments.OfType<NamedExpression>();
// Scan the non-constructor arguments
resolver = resolver.PushObjectInitializer(new InitializedObjectResolveResult(type));
List<ResolveResult> initializerStatements = new List<ResolveResult>();
foreach (var arg in nonConstructorArguments)
HandleNamedExpression(arg, initializerStatements);
resolver = resolver.PopObjectInitializer();
// Resolve the ctor arguments and find the matching ctor overload
string[] argumentNames;
ResolveResult[] arguments = GetArguments(constructorArguments, out argumentNames);
ResolveResult rr = resolver.ResolveObjectCreation(type, arguments, argumentNames, false, initializerStatements);
ProcessInvocationResult(null, constructorArguments, rr);
return rr;
}
ResolveResult IAstVisitor<ResolveResult>.VisitAttributeSection(AttributeSection attributeSection)
{
ScanChildren(attributeSection);
return voidResult;
}
#endregion
#region Using Declaration
ResolveResult IAstVisitor<ResolveResult>.VisitUsingDeclaration(UsingDeclaration usingDeclaration)
{
ScanChildren(usingDeclaration);
return voidResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitUsingAliasDeclaration(UsingAliasDeclaration usingDeclaration)
{
ScanChildren(usingDeclaration);
return voidResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration)
{
return voidResult;
}
#endregion
#region Type References
ResolveResult IAstVisitor<ResolveResult>.VisitPrimitiveType(PrimitiveType primitiveType)
{
if (!resolverEnabled)
return null;
KnownTypeCode typeCode = primitiveType.KnownTypeCode;
if (typeCode == KnownTypeCode.None && primitiveType.Parent is Constraint && primitiveType.Role == Roles.BaseType) {
switch (primitiveType.Keyword) {
case "class":
case "struct":
case "new":
return voidResult;
}
}
IType type = resolver.Compilation.FindType(typeCode);
return new TypeResolveResult(type);
}
ResolveResult IAstVisitor<ResolveResult>.VisitSimpleType(SimpleType simpleType)
{
if (!resolverEnabled) {
ScanChildren(simpleType);
return null;
}
// Figure out the correct lookup mode:
NameLookupMode lookupMode = GetNameLookupMode(simpleType);
var typeArguments = ResolveTypeArguments(simpleType.TypeArguments);
Identifier identifier = simpleType.IdentifierToken;
if (string.IsNullOrEmpty(identifier.Name))
return new TypeResolveResult(SpecialType.UnboundTypeArgument);
ResolveResult rr = resolver.LookupSimpleNameOrTypeName(identifier.Name, typeArguments, lookupMode);
if (simpleType.Parent is Attribute && !identifier.IsVerbatim) {
var withSuffix = resolver.LookupSimpleNameOrTypeName(identifier.Name + "Attribute", typeArguments, lookupMode);
if (AttributeTypeReference.PreferAttributeTypeWithSuffix(rr.Type, withSuffix.Type, resolver.Compilation))
return withSuffix;
}
return rr;
}
NameLookupMode GetNameLookupMode(AstType type)
{
AstType outermostType = type;
while (outermostType.Parent is AstType)
outermostType = (AstType)outermostType.Parent;
NameLookupMode lookupMode = NameLookupMode.Type;
if (outermostType.Parent is UsingDeclaration || outermostType.Parent is UsingAliasDeclaration) {
lookupMode = NameLookupMode.TypeInUsingDeclaration;
} else if (outermostType.Parent is TypeDeclaration && outermostType.Role == Roles.BaseType) {
lookupMode = NameLookupMode.BaseTypeReference;
}
return lookupMode;
}
ResolveResult IAstVisitor<ResolveResult>.VisitMemberType(MemberType memberType)
{
ResolveResult target;
if (memberType.IsDoubleColon && memberType.Target is SimpleType) {
SimpleType t = (SimpleType)memberType.Target;
StoreCurrentState(t);
target = resolver.ResolveAlias(t.Identifier);
StoreResult(t, target);
} else {
if (!resolverEnabled) {
ScanChildren(memberType);
return null;
}
target = Resolve(memberType.Target);
}
NameLookupMode lookupMode = GetNameLookupMode(memberType);
var typeArguments = ResolveTypeArguments(memberType.TypeArguments);
Identifier identifier = memberType.MemberNameToken;
ResolveResult rr = resolver.ResolveMemberAccess(target, identifier.Name, typeArguments, lookupMode);
if (memberType.Parent is Attribute && !identifier.IsVerbatim) {
var withSuffix = resolver.ResolveMemberAccess(target, identifier.Name + "Attribute", typeArguments, lookupMode);
if (AttributeTypeReference.PreferAttributeTypeWithSuffix(rr.Type, withSuffix.Type, resolver.Compilation))
return withSuffix;
}
return rr;
}
ResolveResult IAstVisitor<ResolveResult>.VisitComposedType(ComposedType composedType)
{
if (!resolverEnabled) {
ScanChildren(composedType);
return null;
}
IType t = ResolveType(composedType.BaseType);
if (composedType.HasNullableSpecifier) {
t = NullableType.Create(resolver.Compilation, t);
}
for (int i = 0; i < composedType.PointerRank; i++) {
t = new PointerType(t);
}
foreach (var a in composedType.ArraySpecifiers.Reverse()) {
t = new ArrayType(resolver.Compilation, t, a.Dimensions);
}
return new TypeResolveResult(t);
}
#endregion
#region Query Expressions
ResolveResult IAstVisitor<ResolveResult>.VisitQueryExpression(QueryExpression queryExpression)
{
resolver = resolver.PushBlock();
var oldQueryResult = currentQueryResult;
var oldCancellationToken = cancellationToken;
try {
// Because currentQueryResult isn't part of the stored state,
// query expressions must be resolved in a single operation.
// This means we can't allow cancellation within the query expression.
cancellationToken = CancellationToken.None;
currentQueryResult = null;
foreach (var clause in queryExpression.Clauses) {
currentQueryResult = Resolve(clause);
}
return WrapResult(currentQueryResult);
} finally {
currentQueryResult = oldQueryResult;
cancellationToken = oldCancellationToken;
resolver = resolver.PopBlock();
}
}
IType GetTypeForQueryVariable(IType type)
{
// This assumes queries are only used on IEnumerable.
// We might want to look at the signature of a LINQ method (e.g. Select) instead.
bool? isGeneric;
return GetElementTypeFromIEnumerable(type, resolver.Compilation, false, out isGeneric);
}
ResolveResult MakeTransparentIdentifierResolveResult()
{
return new ResolveResult(new AnonymousType(resolver.Compilation, EmptyList<IUnresolvedProperty>.Instance));
}
sealed class QueryExpressionLambdaConversion : Conversion
{
internal readonly IType[] ParameterTypes;
public QueryExpressionLambdaConversion(IType[] parameterTypes)
{
this.ParameterTypes = parameterTypes;
}
public override bool IsImplicit {
get { return true; }
}
public override bool IsAnonymousFunctionConversion {
get { return true; }
}
}
sealed class QueryExpressionLambda : LambdaResolveResult
{
readonly IParameter[] parameters;
readonly ResolveResult bodyExpression;
internal IType[] inferredParameterTypes;
public QueryExpressionLambda(int parameterCount, ResolveResult bodyExpression)
{
this.parameters = new IParameter[parameterCount];
for (int i = 0; i < parameterCount; i++) {
parameters[i] = new DefaultParameter(SpecialType.UnknownType, "x" + i);
}
this.bodyExpression = bodyExpression;
}
public override IList<IParameter> Parameters {
get { return parameters; }
}
public override Conversion IsValid(IType[] parameterTypes, IType returnType, CSharpConversions conversions)
{
if (parameterTypes.Length == parameters.Length) {
this.inferredParameterTypes = parameterTypes;
return new QueryExpressionLambdaConversion(parameterTypes);
} else {
return Conversion.None;
}
}
public override bool IsAsync {
get { return false; }
}
public override bool IsImplicitlyTyped {
get { return true; }
}
public override bool IsAnonymousMethod {
get { return false; }
}
public override bool HasParameterList {
get { return true; }
}
public override ResolveResult Body {
get { return bodyExpression; }
}
public override IType GetInferredReturnType(IType[] parameterTypes)
{
return bodyExpression.Type;
}
public override string ToString()
{
return string.Format("[QueryExpressionLambda ({0}) => {1}]", string.Join(",", parameters.Select(p => p.Name)), bodyExpression);
}
}
QueryClause GetPreviousQueryClause(QueryClause clause)
{
for (AstNode node = clause.PrevSibling; node != null; node = node.PrevSibling) {
if (node.Role == QueryExpression.ClauseRole)
return (QueryClause)node;
}
return null;
}
QueryClause GetNextQueryClause(QueryClause clause)
{
for (AstNode node = clause.NextSibling; node != null; node = node.NextSibling) {
if (node.Role == QueryExpression.ClauseRole)
return (QueryClause)node;
}
return null;
}
ResolveResult IAstVisitor<ResolveResult>.VisitQueryFromClause(QueryFromClause queryFromClause)
{
ResolveResult result = errorResult;
ResolveResult expr = Resolve(queryFromClause.Expression);
IVariable v;
if (queryFromClause.Type.IsNull) {
v = MakeVariable(GetTypeForQueryVariable(expr.Type), queryFromClause.IdentifierToken);
result = expr;
} else {
v = MakeVariable(ResolveType(queryFromClause.Type), queryFromClause.IdentifierToken);
// resolve the .Cast<>() call
ResolveResult methodGroup = resolver.ResolveMemberAccess(expr, "Cast", new[] { v.Type }, NameLookupMode.InvocationTarget);
result = resolver.ResolveInvocation(methodGroup, new ResolveResult[0]);
}
StoreCurrentState(queryFromClause.IdentifierToken);
resolver = resolver.AddVariable(v);
StoreResult(queryFromClause.IdentifierToken, new LocalResolveResult(v));
if (currentQueryResult != null) {
// this is a second 'from': resolve the .SelectMany() call
QuerySelectClause selectClause = GetNextQueryClause(queryFromClause) as QuerySelectClause;
ResolveResult selectResult;
if (selectClause != null) {
// from ... from ... select - the SelectMany call also performs the Select operation
selectResult = Resolve(selectClause.Expression);
} else {
// from .. from ... ... - introduce a transparent identifier
selectResult = MakeTransparentIdentifierResolveResult();
}
ResolveResult methodGroup = resolver.ResolveMemberAccess(currentQueryResult, "SelectMany", EmptyList<IType>.Instance, NameLookupMode.InvocationTarget);
ResolveResult[] arguments = {
new QueryExpressionLambda(1, result),
new QueryExpressionLambda(2, selectResult)
};
result = resolver.ResolveInvocation(methodGroup, arguments);
}
if (result == expr)
return WrapResult(result);
else
return result;
}
/// <summary>
/// Wraps the result in an identity conversion.
/// This is necessary so that '$from x in variable$ select x*2' does not resolve
/// to the LocalResolveResult for the variable, which would confuse find references.
/// </summary>
ResolveResult WrapResult(ResolveResult result)
{
return new ConversionResolveResult(result.Type, result, Conversion.IdentityConversion, resolver.CheckForOverflow);
}
ResolveResult IAstVisitor<ResolveResult>.VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause)
{
ResolveResult rr = Resolve(queryContinuationClause.PrecedingQuery);
IType variableType = GetTypeForQueryVariable(rr.Type);
StoreCurrentState(queryContinuationClause.IdentifierToken);
IVariable v = MakeVariable(variableType, queryContinuationClause.IdentifierToken);
resolver = resolver.AddVariable(v);
StoreResult(queryContinuationClause.IdentifierToken, new LocalResolveResult(v));
return WrapResult(rr);
}
ResolveResult IAstVisitor<ResolveResult>.VisitQueryLetClause(QueryLetClause queryLetClause)
{
ResolveResult expr = Resolve(queryLetClause.Expression);
StoreCurrentState(queryLetClause.IdentifierToken);
IVariable v = MakeVariable(expr.Type, queryLetClause.IdentifierToken);
resolver = resolver.AddVariable(v);
StoreResult(queryLetClause.IdentifierToken, new LocalResolveResult(v));
if (currentQueryResult != null) {
// resolve the .Select() call
ResolveResult methodGroup = resolver.ResolveMemberAccess(currentQueryResult, "Select", EmptyList<IType>.Instance, NameLookupMode.InvocationTarget);
ResolveResult[] arguments = { new QueryExpressionLambda(1, MakeTransparentIdentifierResolveResult()) };
return resolver.ResolveInvocation(methodGroup, arguments);
} else {
return errorResult;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitQueryJoinClause(QueryJoinClause queryJoinClause)
{
// join v in expr on onExpr equals equalsExpr [into g]
ResolveResult inResult = null;
ResolveResult expr = Resolve(queryJoinClause.InExpression);
IType variableType;
if (queryJoinClause.Type.IsNull) {
variableType = GetTypeForQueryVariable(expr.Type);
inResult = expr;
} else {
variableType = ResolveType(queryJoinClause.Type);
// resolve the .Cast<>() call
ResolveResult methodGroup = resolver.ResolveMemberAccess(expr, "Cast", new[] { variableType }, NameLookupMode.InvocationTarget);
inResult = resolver.ResolveInvocation(methodGroup, new ResolveResult[0]);
}
// resolve the 'On' expression in a context that contains only the previously existing range variables:
// (before adding any variable)
ResolveResult onResult = Resolve(queryJoinClause.OnExpression);
// scan the 'Equals' expression in a context that contains only the variable 'v'
CSharpResolver resolverOutsideQuery = resolver;
resolverOutsideQuery = resolverOutsideQuery.PopBlock(); // pop all variables from the current query expression
IVariable v = MakeVariable(variableType, queryJoinClause.JoinIdentifierToken);
resolverOutsideQuery = resolverOutsideQuery.AddVariable(v);
ResolveResult equalsResult = errorResult;
ResetContext(resolverOutsideQuery, delegate {
equalsResult = Resolve(queryJoinClause.EqualsExpression);
});
StoreCurrentState(queryJoinClause.JoinIdentifierToken);
StoreResult(queryJoinClause.JoinIdentifierToken, new LocalResolveResult(v));
if (queryJoinClause.IsGroupJoin) {
return ResolveGroupJoin(queryJoinClause, inResult, onResult, equalsResult);
} else {
resolver = resolver.AddVariable(v);
if (currentQueryResult != null) {
QuerySelectClause selectClause = GetNextQueryClause(queryJoinClause) as QuerySelectClause;
ResolveResult selectResult;
if (selectClause != null) {
// from ... join ... select - the Join call also performs the Select operation
selectResult = Resolve(selectClause.Expression);
} else {
// from .. join ... ... - introduce a transparent identifier
selectResult = MakeTransparentIdentifierResolveResult();
}
var methodGroup = resolver.ResolveMemberAccess(currentQueryResult, "Join", EmptyList<IType>.Instance);
ResolveResult[] arguments = {
inResult,
new QueryExpressionLambda(1, onResult),
new QueryExpressionLambda(1, equalsResult),
new QueryExpressionLambda(2, selectResult)
};
return resolver.ResolveInvocation(methodGroup, arguments);
} else {
return errorResult;
}
}
}
ResolveResult ResolveGroupJoin(QueryJoinClause queryJoinClause,
ResolveResult inResult, ResolveResult onResult, ResolveResult equalsResult)
{
Debug.Assert(queryJoinClause.IsGroupJoin);
DomRegion intoIdentifierRegion = MakeRegion(queryJoinClause.IntoIdentifierToken);
// We need to declare the group variable, but it's a bit tricky to determine its type:
// We'll have to resolve the GroupJoin invocation and take a look at the inferred types
// for the lambda given as last parameter.
var methodGroup = resolver.ResolveMemberAccess(currentQueryResult, "GroupJoin", EmptyList<IType>.Instance);
QuerySelectClause selectClause = GetNextQueryClause(queryJoinClause) as QuerySelectClause;
LambdaResolveResult groupJoinLambda;
if (selectClause != null) {
// from ... join ... into g select - the GroupJoin call also performs the Select operation
IParameter[] selectLambdaParameters = {
new DefaultParameter(SpecialType.UnknownType, "<>transparentIdentifier"),
new DefaultParameter(SpecialType.UnknownType, queryJoinClause.IntoIdentifier, region: intoIdentifierRegion)
};
groupJoinLambda = new ImplicitlyTypedLambda(selectClause, selectLambdaParameters, this);
} else {
// from .. join ... ... - introduce a transparent identifier
groupJoinLambda = new QueryExpressionLambda(2, MakeTransparentIdentifierResolveResult());
}
ResolveResult[] arguments = {
inResult,
new QueryExpressionLambda(1, onResult),
new QueryExpressionLambda(1, equalsResult),
groupJoinLambda
};
ResolveResult rr = resolver.ResolveInvocation(methodGroup, arguments);
InvocationResolveResult invocationRR = rr as InvocationResolveResult;
IVariable groupVariable;
if (groupJoinLambda is ImplicitlyTypedLambda) {
var implicitlyTypedLambda = (ImplicitlyTypedLambda)groupJoinLambda;
if (invocationRR != null && invocationRR.Arguments.Count > 0) {
ConversionResolveResult crr = invocationRR.Arguments[invocationRR.Arguments.Count - 1] as ConversionResolveResult;
if (crr != null)
ProcessConversion(null, crr.Input, crr.Conversion, crr.Type);
}
implicitlyTypedLambda.EnforceMerge(this);
if (implicitlyTypedLambda.Parameters.Count == 2) {
StoreCurrentState(queryJoinClause.IntoIdentifierToken);
groupVariable = implicitlyTypedLambda.Parameters[1];
} else {
groupVariable = null;
}
} else {
Debug.Assert(groupJoinLambda is QueryExpressionLambda);
// Add the variable if the query expression continues after the group join
// (there's no need to do this if there's only a select clause remaining, as
// we already handled that in the ImplicitlyTypedLambda).
// Get the inferred type of the group variable:
IType[] inferredParameterTypes = null;
if (invocationRR != null && invocationRR.Arguments.Count > 0) {
ConversionResolveResult crr = invocationRR.Arguments[invocationRR.Arguments.Count - 1] as ConversionResolveResult;
if (crr != null && crr.Conversion is QueryExpressionLambdaConversion) {
inferredParameterTypes = ((QueryExpressionLambdaConversion)crr.Conversion).ParameterTypes;
}
}
if (inferredParameterTypes == null)
inferredParameterTypes = ((QueryExpressionLambda)groupJoinLambda).inferredParameterTypes;
IType groupParameterType;
if (inferredParameterTypes != null && inferredParameterTypes.Length == 2)
groupParameterType = inferredParameterTypes[1];
else
groupParameterType = SpecialType.UnknownType;
StoreCurrentState(queryJoinClause.IntoIdentifierToken);
groupVariable = MakeVariable(groupParameterType, queryJoinClause.IntoIdentifierToken);
resolver = resolver.AddVariable(groupVariable);
}
if (groupVariable != null) {
StoreResult(queryJoinClause.IntoIdentifierToken, new LocalResolveResult(groupVariable));
}
return rr;
}
ResolveResult IAstVisitor<ResolveResult>.VisitQueryWhereClause(QueryWhereClause queryWhereClause)
{
ResolveResult condition = Resolve(queryWhereClause.Condition);
IType boolType = resolver.Compilation.FindType(KnownTypeCode.Boolean);
Conversion conversionToBool = resolver.conversions.ImplicitConversion(condition, boolType);
ProcessConversion(queryWhereClause.Condition, condition, conversionToBool, boolType);
if (currentQueryResult != null) {
if (conversionToBool != Conversion.IdentityConversion && conversionToBool != Conversion.None) {
condition = new ConversionResolveResult(boolType, condition, conversionToBool, resolver.CheckForOverflow);
}
var methodGroup = resolver.ResolveMemberAccess(currentQueryResult, "Where", EmptyList<IType>.Instance);
ResolveResult[] arguments = { new QueryExpressionLambda(1, condition) };
return resolver.ResolveInvocation(methodGroup, arguments);
} else {
return errorResult;
}
}
ResolveResult IAstVisitor<ResolveResult>.VisitQuerySelectClause(QuerySelectClause querySelectClause)
{
if (currentQueryResult == null) {
ScanChildren(querySelectClause);
return errorResult;
}
QueryClause previousQueryClause = GetPreviousQueryClause(querySelectClause);
// If the 'select' follows on a 'SelectMany', 'Join' or 'GroupJoin' clause, then the 'select' portion
// was already done as part of the previous clause.
if (((previousQueryClause is QueryFromClause && GetPreviousQueryClause(previousQueryClause) != null))
|| previousQueryClause is QueryJoinClause)
{
// GroupJoin already scans the following select clause in a different context,
// so we must not scan it again.
if (!(previousQueryClause is QueryJoinClause && ((QueryJoinClause)previousQueryClause).IsGroupJoin))
Scan(querySelectClause.Expression);
return WrapResult(currentQueryResult);
}
QueryExpression query = querySelectClause.Parent as QueryExpression;
string rangeVariable = GetSingleRangeVariable(query);
if (rangeVariable != null) {
IdentifierExpression ident = ParenthesizedExpression.UnpackParenthesizedExpression(querySelectClause.Expression) as IdentifierExpression;
if (ident != null && ident.Identifier == rangeVariable && !ident.TypeArguments.Any()) {
// selecting the single identifier that is the range variable
if (query.Clauses.Count > 2) {
// only if the query is not degenerate:
// the Select call will be optimized away, so directly return the previous result
Scan(querySelectClause.Expression);
return WrapResult(currentQueryResult);
}
}
}
ResolveResult expr = Resolve(querySelectClause.Expression);
var methodGroup = resolver.ResolveMemberAccess(currentQueryResult, "Select", EmptyList<IType>.Instance);
ResolveResult[] arguments = { new QueryExpressionLambda(1, expr) };
return resolver.ResolveInvocation(methodGroup, arguments);
}
/// <summary>
/// Gets the name of the range variable in the specified query.
/// If the query has multiple range variables, this method returns null.
/// </summary>
string GetSingleRangeVariable(QueryExpression query)
{
if (query == null)
return null;
foreach (QueryClause clause in query.Clauses.Skip(1)) {
if (clause is QueryFromClause || clause is QueryJoinClause || clause is QueryLetClause) {
// query has more than 1 range variable
return null;
}
}
QueryFromClause fromClause = query.Clauses.FirstOrDefault() as QueryFromClause;
if (fromClause != null)
return fromClause.Identifier;
QueryContinuationClause continuationClause = query.Clauses.FirstOrDefault() as QueryContinuationClause;
if (continuationClause != null)
return continuationClause.Identifier;
return null;
}
ResolveResult IAstVisitor<ResolveResult>.VisitQueryGroupClause(QueryGroupClause queryGroupClause)
{
if (currentQueryResult == null) {
ScanChildren(queryGroupClause);
return errorResult;
}
// ... group projection by key
ResolveResult projection = Resolve(queryGroupClause.Projection);
ResolveResult key = Resolve(queryGroupClause.Key);
var methodGroup = resolver.ResolveMemberAccess(currentQueryResult, "GroupBy", EmptyList<IType>.Instance);
ResolveResult[] arguments = {
new QueryExpressionLambda(1, key),
new QueryExpressionLambda(1, projection)
};
return resolver.ResolveInvocation(methodGroup, arguments);
}
ResolveResult IAstVisitor<ResolveResult>.VisitQueryOrderClause(QueryOrderClause queryOrderClause)
{
foreach (QueryOrdering ordering in queryOrderClause.Orderings) {
currentQueryResult = Resolve(ordering);
}
return WrapResult(currentQueryResult);
}
ResolveResult IAstVisitor<ResolveResult>.VisitQueryOrdering(QueryOrdering queryOrdering)
{
if (currentQueryResult == null) {
ScanChildren(queryOrdering);
return errorResult;
}
// ... orderby sortKey [descending]
ResolveResult sortKey = Resolve(queryOrdering.Expression);
QueryOrderClause parentClause = queryOrdering.Parent as QueryOrderClause;
bool isFirst = (parentClause == null || parentClause.Orderings.FirstOrDefault() == queryOrdering);
string methodName = isFirst ? "OrderBy" : "ThenBy";
if (queryOrdering.Direction == QueryOrderingDirection.Descending)
methodName += "Descending";
var methodGroup = resolver.ResolveMemberAccess(currentQueryResult, methodName, EmptyList<IType>.Instance);
ResolveResult[] arguments = {
new QueryExpressionLambda(1, sortKey),
};
return resolver.ResolveInvocation(methodGroup, arguments);
}
#endregion
#region Constructor Initializer
ResolveResult IAstVisitor<ResolveResult>.VisitConstructorInitializer(ConstructorInitializer constructorInitializer)
{
ResolveResult target;
if (constructorInitializer.ConstructorInitializerType == ConstructorInitializerType.Base) {
target = resolver.ResolveBaseReference();
} else {
target = resolver.ResolveThisReference();
}
string[] argumentNames;
ResolveResult[] arguments = GetArguments(constructorInitializer.Arguments, out argumentNames);
ResolveResult rr = resolver.ResolveObjectCreation(target.Type, arguments, argumentNames, allowProtectedAccess: true);
ProcessInvocationResult(null, constructorInitializer.Arguments, rr);
return rr;
}
#endregion
#region Other Nodes
// Token nodes
ResolveResult IAstVisitor<ResolveResult>.VisitIdentifier(Identifier identifier)
{
return null;
}
ResolveResult IAstVisitor<ResolveResult>.VisitComment (Comment comment)
{
return null;
}
ResolveResult IAstVisitor<ResolveResult>.VisitNewLine (NewLineNode comment)
{
return null;
}
ResolveResult IAstVisitor<ResolveResult>.VisitWhitespace(WhitespaceNode whitespaceNode)
{
return null;
}
ResolveResult IAstVisitor<ResolveResult>.VisitText(TextNode textNode)
{
return null;
}
ResolveResult IAstVisitor<ResolveResult>.VisitPreProcessorDirective (PreProcessorDirective preProcessorDirective)
{
return null;
}
ResolveResult IAstVisitor<ResolveResult>.VisitCSharpTokenNode(CSharpTokenNode cSharpTokenNode)
{
return null;
}
ResolveResult IAstVisitor<ResolveResult>.VisitArraySpecifier(ArraySpecifier arraySpecifier)
{
return null;
}
ResolveResult IAstVisitor<ResolveResult>.VisitPatternPlaceholder(AstNode placeholder, ICSharpCode.NRefactory.PatternMatching.Pattern pattern)
{
return null;
}
// Nodes where we just need to visit the children:
ResolveResult IAstVisitor<ResolveResult>.VisitAccessor(Accessor accessor)
{
ScanChildren(accessor);
return voidResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitSwitchSection(SwitchSection switchSection)
{
ScanChildren(switchSection);
return voidResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitCaseLabel(CaseLabel caseLabel)
{
ScanChildren(caseLabel);
return voidResult;
}
ResolveResult IAstVisitor<ResolveResult>.VisitConstraint(Constraint constraint)
{
ScanChildren(constraint);
return voidResult;
}
#endregion
#region Documentation Reference
ResolveResult IAstVisitor<ResolveResult>.VisitDocumentationReference(DocumentationReference documentationReference)
{
// Resolve child nodes:
ITypeDefinition declaringTypeDef;
if (documentationReference.DeclaringType.IsNull)
declaringTypeDef = resolver.CurrentTypeDefinition;
else
declaringTypeDef = ResolveType(documentationReference.DeclaringType).GetDefinition();
IType[] typeArguments = documentationReference.TypeArguments.Select(ResolveType).ToArray();
IType conversionOperatorReturnType = ResolveType(documentationReference.ConversionOperatorReturnType);
IParameter[] parameters = documentationReference.Parameters.Select(ResolveXmlDocParameter).ToArray();
if (documentationReference.EntityType == EntityType.TypeDefinition) {
if (declaringTypeDef != null)
return new TypeResolveResult(declaringTypeDef);
else
return errorResult;
}
if (documentationReference.EntityType == EntityType.None) {
// might be a type, member or ctor
string memberName = documentationReference.MemberName;
ResolveResult rr;
if (documentationReference.DeclaringType.IsNull) {
rr = resolver.LookupSimpleNameOrTypeName(memberName, typeArguments, NameLookupMode.Expression);
} else {
var target = Resolve(documentationReference.DeclaringType);
rr = resolver.ResolveMemberAccess(target, memberName, typeArguments);
}
// reduce to definition:
if (rr.IsError) {
return rr;
} else if (rr is TypeResolveResult) {
var typeDef = rr.Type.GetDefinition();
if (typeDef == null)
return errorResult;
if (documentationReference.HasParameterList) {
var ctors = typeDef.GetConstructors(options: GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions);
return FindByParameters(ctors, parameters);
} else {
return new TypeResolveResult(typeDef);
}
} else if (rr is MemberResolveResult) {
var mrr = (MemberResolveResult)rr;
return new MemberResolveResult(null, mrr.Member.MemberDefinition);
} else if (rr is MethodGroupResolveResult) {
var mgrr = (MethodGroupResolveResult)rr;
var methods = mgrr.MethodsGroupedByDeclaringType.Reverse()
.SelectMany(ml => ml.Select(m => (IParameterizedMember)m.MemberDefinition));
return FindByParameters(methods, parameters);
}
return rr;
}
// Indexer or operator
if (declaringTypeDef == null)
return errorResult;
if (documentationReference.EntityType == EntityType.Indexer) {
var indexers = declaringTypeDef.Properties.Where(p => p.IsIndexer && !p.IsExplicitInterfaceImplementation);
return FindByParameters(indexers, parameters);
} else if (documentationReference.EntityType == EntityType.Operator) {
var opType = documentationReference.OperatorType;
string memberName = OperatorDeclaration.GetName(opType);
var methods = declaringTypeDef.Methods.Where(m => m.IsOperator && m.Name == memberName);
if (opType == OperatorType.Implicit || opType == OperatorType.Explicit) {
// conversion operator
foreach (var method in methods) {
if (ParameterListComparer.Instance.Equals(method.Parameters, parameters)) {
if (method.ReturnType.Equals(conversionOperatorReturnType))
return new MemberResolveResult(null, method);
}
}
return new MemberResolveResult(null, methods.FirstOrDefault());
} else {
// not a conversion operator
return FindByParameters(methods, parameters);
}
} else {
throw new NotSupportedException(); // unknown entity type
}
}
IParameter ResolveXmlDocParameter(ParameterDeclaration p)
{
var lrr = Resolve(p) as LocalResolveResult;
if (lrr != null && lrr.IsParameter)
return (IParameter)lrr.Variable;
else
return new DefaultParameter(SpecialType.UnknownType, string.Empty);
}
ResolveResult FindByParameters(IEnumerable<IParameterizedMember> methods, IList<IParameter> parameters)
{
foreach (var method in methods) {
if (ParameterListComparer.Instance.Equals(method.Parameters, parameters))
return new MemberResolveResult(null, method);
}
return new MemberResolveResult(null, methods.FirstOrDefault());
}
#endregion
}
}
| mit |
seraum/nectarjs | tests/ES3/Conformance/15_Native_ECMA_Script_Objects/15.3_Function_Objects/15.3.5_Properties_of_Function_Instances/S15.3.5.1_A1_T2.js | 754 | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.3.5.1_A1_T2;
* @section: 15.3.5.1;
* @assertion: The value of the length property is usually an integer that indicates the 'typical' number of arguments expected by the function;
* @description: Checking length property of Function("arg1,arg2,arg3","arg4,arg5", null);
*/
f = Function("arg1,arg2,arg3","arg4,arg5", null);
//CHECK#1
if (!(f.hasOwnProperty('length'))) {
$FAIL('#1: the function has length property.');
}
//CHECK#2
if (f.length !== 5) {
$ERROR('#2: The value of the length property is usually an integer that indicates the "typical" number of arguments expected by the function');
}
| mit |
MikeLockz/exit-now-mobile | www/lib/aerisjs/examples/amd/bower_components/aerisjs/tests/spec/aeris/errors/AbstractError.js | 1250 | define(['aeris/util', 'aeris/errors/abstracterror'], function(_, AbstractError) {
describe('An Error', function() {
var MyError = function() {
AbstractError.apply(this, arguments);
};
_.inherits(
MyError,
AbstractError
);
MyError.prototype.setName = function() {
return 'MyError';
};
MyError.prototype.setMessage = function(message) {
return 'Error: ' + message;
};
it('must implement a setName method', function() {
var BadErrorClass = function() {
AbstractError.apply(this, arguments);
};
_.inherits(
BadErrorClass,
AbstractError
);
expect(function() { throw new BadErrorClass('msg'); }).toThrow();
new MyError('msg'); // shouldn't throw error
});
it('should construct with a name and message', function() {
var msg = 'something awful happened';
var myError = new MyError(msg);
expect(myError.name).toEqual('MyError');
expect(myError.message).toEqual('Error: ' + msg);
});
it('should throw a message', function() {
var msg = 'something awful happened';
expect(function() {
throw new MyError(msg);
}).toThrow('Error: ' + msg);
});
});
});
| mit |
davidalger/n98-magerun | src/N98/Util/Console/Helper/Table/Renderer/XmlRenderer.php | 942 | <?php
namespace N98\Util\Console\Helper\Table\Renderer;
use Symfony\Component\Console\Output\OutputInterface;
class XmlRenderer implements RendererInterface
{
/**
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @param array $rows
*/
public function render(OutputInterface $output, array $rows)
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
$rootXml = $dom->createElement('table');
$dom->appendChild($rootXml);
foreach ($rows as $row) {
$rowXml = $dom->createElement('row');
foreach ($row as $key => $value) {
$key = preg_replace("/[^A-Za-z0-9]/u", '_', $key);
$rowXml->appendChild($dom->createElement($key, @iconv('UTF-8', 'UTF-8//IGNORE', $value)));
}
$rootXml->appendChild($rowXml);
}
$output->writeln($dom->saveXML());
}
} | mit |
j-froehlich/magento2_wk | dev/tests/integration/testsuite/Magento/DownloadableImportExport/Model/Import/Product/Type/DownloadableTest.php | 7415 | <?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\DownloadableImportExport\Model\Import\Product\Type;
use Magento\Framework\App\Bootstrap;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\ImportExport\Model\Import;
/**
* @magentoAppArea adminhtml
*/
class DownloadableTest extends \PHPUnit_Framework_TestCase
{
/**
* Downloadable product test Name
*/
const TEST_PRODUCT_NAME = 'Downloadable 1';
/**
* Downloadable product test Type
*/
const TEST_PRODUCT_TYPE = 'downloadable';
/**
* Downloadable product Links Group Name
*/
const TEST_PRODUCT_LINKS_GROUP_NAME = 'TEST Import Links';
/**
* Downloadable product Samples Group Name
*/
const TEST_PRODUCT_SAMPLES_GROUP_NAME = 'TEST Import Samples';
/**
* @var \Magento\CatalogImportExport\Model\Import\Product
*/
protected $model;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $objectManager;
/**
* @var \Magento\Framework\EntityManager\EntityMetadata
*/
protected $productMetadata;
protected function setUp()
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->model = $this->objectManager->create(
\Magento\CatalogImportExport\Model\Import\Product::class
);
/** @var \Magento\Framework\EntityManager\MetadataPool $metadataPool */
$metadataPool = $this->objectManager->get(\Magento\Framework\EntityManager\MetadataPool::class);
$this->productMetadata = $metadataPool->getMetadata(\Magento\Catalog\Api\Data\ProductInterface::class);
}
/**
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testDownloadableImport()
{
// import data from CSV file
$pathToFile = __DIR__ . '/../../_files/import_downloadable.csv';
$filesystem = $this->objectManager->create(
\Magento\Framework\Filesystem::class
);
$directory = $filesystem->getDirectoryWrite(DirectoryList::ROOT);
$source = $this->objectManager->create(
\Magento\ImportExport\Model\Import\Source\Csv::class,
[
'file' => $pathToFile,
'directory' => $directory
]
);
$errors = $this->model->setSource(
$source
)->setParameters(
[
'behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_APPEND,
'entity' => 'catalog_product'
]
)->validateData();
$this->assertTrue($errors->getErrorsCount() == 0);
$this->model->importData();
$resource = $this->objectManager->get(\Magento\Catalog\Model\ResourceModel\Product::class);
$productId = $resource->getIdBySku(self::TEST_PRODUCT_NAME);
$this->assertTrue(is_numeric($productId));
/** @var \Magento\Catalog\Model\Product $product */
$product = $this->objectManager->create(
\Magento\Catalog\Model\Product::class
);
$product->load($productId);
$this->assertFalse($product->isObjectNew());
$this->assertEquals(self::TEST_PRODUCT_NAME, $product->getName());
$this->assertEquals(self::TEST_PRODUCT_TYPE, $product->getTypeId());
$downloadableProductLinks = $product->getExtensionAttributes()->getDownloadableProductLinks();
$downloadableLinks = $product->getDownloadableLinks();
$downloadableProductSamples = $product->getExtensionAttributes()->getDownloadableProductSamples();
$downloadableSamples = $product->getDownloadableSamples();
//TODO: Track Fields: id, link_id, link_file and sample_file)
$expectedLinks= [
'file' => [
'title' => 'TEST Import Link Title File',
'sort_order' => '78',
'sample_type' => 'file',
'price' => '123.0000',
'number_of_downloads' => '123',
'is_shareable' => '0',
'link_type' => 'file'
],
'url' => [
'title' => 'TEST Import Link Title URL',
'sort_order' => '42',
'sample_type' => 'url',
'sample_url' => 'http://www.bing.com',
'price' => '1.0000',
'number_of_downloads' => '0',
'is_shareable' => '1',
'link_type' => 'url',
'link_url' => 'http://www.google.com'
]
];
foreach ($downloadableProductLinks as $link) {
$actualLink = $link->getData();
$this->assertArrayHasKey('link_type', $actualLink);
foreach ($expectedLinks[$actualLink['link_type']] as $expectedKey => $expectedValue) {
$this->assertArrayHasKey($expectedKey, $actualLink);
$this->assertEquals($actualLink[$expectedKey], $expectedValue);
}
}
foreach ($downloadableLinks as $link) {
$actualLink = $link->getData();
$this->assertArrayHasKey('link_type', $actualLink);
$this->assertArrayHasKey('product_id', $actualLink);
$this->assertEquals($actualLink['product_id'], $product->getData($this->productMetadata->getLinkField()));
foreach ($expectedLinks[$actualLink['link_type']] as $expectedKey => $expectedValue) {
$this->assertArrayHasKey($expectedKey, $actualLink);
$this->assertEquals($actualLink[$expectedKey], $expectedValue);
}
}
//TODO: Track Fields: id, sample_id and sample_file)
$expectedSamples= [
'file' => [
'title' => 'TEST Import Sample File',
'sort_order' => '178',
'sample_type' => 'file'
],
'url' => [
'title' => 'TEST Import Sample URL',
'sort_order' => '178',
'sample_type' => 'url',
'sample_url' => 'http://www.yahoo.com'
]
];
foreach ($downloadableProductSamples as $sample) {
$actualSample = $sample->getData();
$this->assertArrayHasKey('sample_type', $actualSample);
foreach ($expectedSamples[$actualSample['sample_type']] as $expectedKey => $expectedValue) {
$this->assertArrayHasKey($expectedKey, $actualSample);
$this->assertEquals($actualSample[$expectedKey], $expectedValue);
}
}
foreach ($downloadableSamples as $sample) {
$actualSample = $sample->getData();
$this->assertArrayHasKey('sample_type', $actualSample);
$this->assertArrayHasKey('product_id', $actualSample);
$this->assertEquals($actualSample['product_id'], $product->getData($this->productMetadata->getLinkField()));
foreach ($expectedSamples[$actualSample['sample_type']] as $expectedKey => $expectedValue) {
$this->assertArrayHasKey($expectedKey, $actualSample);
$this->assertEquals($actualSample[$expectedKey], $expectedValue);
}
}
}
}
| mit |
shreyasmulay23/Git_Repo_Angular2 | node_modules/ng2-bootstrap/tabs/ng-transclude.directive.js | 1096 | import { Directive, Input, ViewContainerRef } from '@angular/core';
export var NgTranscludeDirective = (function () {
function NgTranscludeDirective(viewRef) {
this.viewRef = viewRef;
}
Object.defineProperty(NgTranscludeDirective.prototype, "ngTransclude", {
get: function () {
return this._ngTransclude;
},
set: function (templateRef) {
this._ngTransclude = templateRef;
if (templateRef) {
this.viewRef.createEmbeddedView(templateRef);
}
},
enumerable: true,
configurable: true
});
NgTranscludeDirective.decorators = [
{ type: Directive, args: [{
selector: '[ngTransclude]'
},] },
];
/** @nocollapse */
NgTranscludeDirective.ctorParameters = function () { return [
{ type: ViewContainerRef, },
]; };
NgTranscludeDirective.propDecorators = {
'ngTransclude': [{ type: Input },],
};
return NgTranscludeDirective;
}());
//# sourceMappingURL=ng-transclude.directive.js.map | mit |
FinchYang/test | AecPrivateCloud.ALL/Apps/DBWorld.ClientApps/bin/Release/CooperationCloud/Home/scripts/mf/ui.js | 12895 | /***********************************************
* M-Files UI Operation...
* like View, Menu, Dialog etc...
* export name: MF.ui
* dependency: client.js, vault.js
************************************************/
var MF = MF || {};
(function (u, undefined) {
var ui = {
///<summary>m-files ui utils</summary>
setCmdsState: function (shellFrame, location, state, cmds) {
///<param name="cmds" type="Array">命令ID的数组</param>
for (var i = 0; i < cmds.length; i++) {
shellFrame.Commands.SetCommandState(cmds[i], location, state);
}
},
setCurrentPath: function(shellFrame, relativePath) {
try {
shellFrame.CurrentPath = relativePath;
} catch (e) {
shellFrame.ShellUI.ShowMessage('路径(' + relativePath + ')没有权限或不存在!');
}
},
setCurrentView: function(shellFrame, viewId, subFolder) {
///<param name="subFolder" type="String">视图下的子文件夹名称</param>
var vault = shellFrame.ShellUI.Vault;
try {
var location = vault.ViewOperations.GetViewLocationInClient(viewId, true);
var url = u.vault.getVaultURL(vault);
var folderPath = location.substring(url.length);
if (subFolder && subFolder !== '') {
folderPath = folderPath + subFolder;
}
this.setCurrentPath(shellFrame, folderPath);
} catch(e) {
shellFrame.ShellUI.ShowMessage('视图(ID=' + viewId + ')没有权限或不存在!');
}
},
getFilePath : function(shellFrame, objVersion, fileIndex) {
///<summary>获得指定文件的全路径</summary>
///<param name="objVersion" type="ObjectVersion">M-Files对象</param>
///<param name="fileIndex" type="int">在对象文件中的编号</param>
var vault = shellFrame.ShellUI.Vault;
if (fileIndex < 0 || fileIndex > objVersion.FilesCount) {
throw new Error('文件的编号超出了文件列表的长度');
}
var file = objVersion.Files.Item(fileIndex);
return vault.ObjectFileOperations.GetPathInDefaultView(
objVersion.ObjVer.ObjID, objVersion.ObjVer.Version, file.ID, file.Version,
MFLatestSpecificBehaviorAutomatic, false);
},
createNewObjectWithWindow: function (shellFrame, objTypeID) {
var vault = shellFrame.ShellUI.Vault;
var objType = vault.ObjectTypeOperations.GetObjectType(objTypeID);
objType.ID = objTypeID;
return vault.ObjectOperations.ShowBasicNewObjectWindow(0, objType);
},
createNewObjectShowWindow: function(shellFrame, objTypeID, classID, propertyValues, templateObjVer) {
///<param name="templateObjVer" type="ObjVer">ObjVer of template object</param>
var oVault = shellFrame.ShellUI.Vault;
var pvs = u.createObject("PropertyValues");
if (classID || classID.value === 0) {
var pvClass = u.vault.createProperty(classID.type, MFDatatypeLookup, classID.value);
pvs.Add(-1, pvClass);
}
if (propertyValues && propertyValues.Count > 0) {
for (var i = 1; i <= propertyValues.Count; i++) {
pvs.Add(-1, propertyValues.Item(i));
}
}
var objCreationInfo = u.createObject("ObjectCreationInfo");
objCreationInfo.SetObjectType(objTypeID, false);
objCreationInfo.SetSingleFileDocument(true, true);
if (templateObjVer) {
objCreationInfo.SetTemplate(templateObjVer);
}
var acl = u.createObject("AccessControlList");
oVault.ObjectOperations.ShowPrefilledNewObjectWindow(0, MFObjectWindowModeInsert, objCreationInfo, pvs, acl);
},
createCustomTaskGroup: function(shellFrame, groupName, orderPriority, theme) {
///<summary>创建自定义任务栏组</summary>
if (!shellFrame.TaskPane.Available) return;
var groupId = shellFrame.TaskPane.CreateGroup(groupName, orderPriority);
theme = theme || { groupHeader_TextColor: '#5182C4', groupHeader_FontSize: '135%' };
try {
shellFrame.TaskPane.SetTheme(theme);
} catch(e) {
}
return groupId;
},
createCommandAtTaskGroup: function(shellFrame, groupId, mfCustomCmd, orderPriority) {
///<param name="mfCustomCmd" type="MfCommand"></param>
///<param name="orderPriority" type="long">Ascending ordering.
/// If the group contains built-in commands,
/// then negative values are sorted before the built-in commands and positive values after them.
/// </param>
if (!shellFrame.TaskPane.Available) return;
var cmdName = mfCustomCmd.name;
var cmdId = mfCustomCmd.command;
if (!cmdId && cmdId !== 0) {
cmdId = shellFrame.Commands.CreateCustomCommand(cmdName);
}
mfCustomCmd.command = cmdId;
var iconPath = mfCustomCmd.iconPath;
if (iconPath && iconPath !== '') {
shellFrame.Commands.SetIconFromPath(cmdId, iconPath);
}
shellFrame.TaskPane.AddCustomCommandToGroup(cmdId, groupId, orderPriority);
return cmdId;
},
getVault: function(dashboard) {
var vault;
try {
vault = dashboard.Parent.ShellUI.Vault; //shellFrame is the parent
} catch (e) {
try {
vault = dashboard.Parent.ShellFrame.ShellUI.Vault; //IShellPaneContainer is the parent
} catch (e) {
vault = dashboard.Parent.Vault; //shellUI or vaultUI is the parent
}
}
return vault;
},
getShellFrame: function(dashboard) {
var vault;
var shellFrame = null;
try {
vault = dashboard.Parent.ShellUI.Vault; //shellFrame is the parent
shellFrame = dashboard.Parent;
} catch (e) {
try {
vault = dashboard.Parent.ShellFrame.ShellUI.Vault; //IShellPaneContainer is the parent
shellFrame = dashboard.Parent.ShellFrame;
} catch (e) {
vault = dashboard.Parent.Vault; //shellUI or vaultUI is the parent
}
}
return shellFrame;
},
_iconCache: {},
getIconFromUI: function(shellFrame, valueList) {
var key = "0-" + valueList;
var path = this._iconCache[key];
// found something in the cache! return it and be done
if (path !== undefined) {
return path;
}
try {
path = shellFrame.ShellUI.GetObjectTypeIconURL(valueList);
return path;
} catch(e) {
return this.getIcon(shellFrame.ShellUI.Vault, valueList);
}
},
getIcon: function (vault, valueList, valueListItem) {
/// <signature>
/// <summary>
/// Resolves the icon for an ObjectType, saves it locally, and returns the path.
/// Assumes 'this.vault' has been set (i.e., $.mf.vault).
/// </summary>
/// <param name="vault" type="Vault"></param>
/// <param name="objectTypeID" type="Number"></param>
/// <returns type="string">Icon Path</returns>
/// </signature>
/// <signature>
/// <summary>
/// Resolves the icon for a ValueListItem, saves it locally, and returns the path.
/// Assumes 'this.vault' has been set (i.e., $.mf.vault).
/// </summary>
/// <param name="vault" type="Vault"></param>
/// <param name="valueList" type="Number"></param>
/// <param name="valueListItem" type="Number"></param>
/// <returns type="string">Icon Path</returns>
/// </signature>
var key = (valueListItem === undefined) ? "0-" + valueList : valueList + "-" + valueListItem,
path,
fs,
//icon,
//stream,
adBinaryMode = 1,
adCreateOverwriteMode = 2;
//check cache
path = this._iconCache[key];
// found something in the cache! return it and be done
if (path !== undefined) {
return path;
}
// Start up the file sytem object and build our path
fs = new ActiveXObject('Scripting.FileSystemObject');
path = fs.GetSpecialFolder(2);
// Create ui ext icon folder
path += "\\CADS_UIEXT_Icons";
if (!fs.FolderExists(path)) {
fs.CreateFolder(path);
}
// create a folder for each vault
path += "\\" + vault.getGUID();
if (!fs.FolderExists(path)) {
fs.CreateFolder(path);
}
// add file to path
path += "\\" + key + ".ico";
// if file already exists, don't load it...
if (fs.FileExists(path)) {
return path;
}
// just in case something goes wrong (like the item doesn't have an icon)
try {
var icon;
// load the image
if (valueListItem === undefined) {
// ObjectType icon
icon = vault.ObjectTypeOperations.GetObjectType(valueList).Icon;
} else {
//ValueList icon
icon = vault.ValueListItemOperations.GetValueListItemByID(valueList, valueListItem).Icon;
}
// save icon data to file
var stream = new ActiveXObject("ADODB.Stream");
stream.Type = adBinaryMode;
stream.Open();
stream.Write(icon);
stream.SaveToFile(path, adCreateOverwriteMode);
// save to cache
this._iconCache[key] = path;
// return the local path to the icon
return path;
} catch (e) {
// cache that we were unable to generate an icon
this._iconCache[key] = "";
}
},
getCurrentListing: function(shellFrame) {
var listing;
try {
listing = shellFrame.ActiveListing;
} catch (e) {
listing = shellFrame.Listing;
}
return listing;
},
selectObject: function (shellFrame, objVer, novirtial) {
var listing = this.getCurrentListing(shellFrame);
if (!novirtial) {
var objOrFileVers = MF.createObject("ObjOrFileVers");
var objOrFileVer = MF.createObject("ObjOrFileVer");
objOrFileVer.ObjVer = objVer;
objOrFileVers.Add(-1, objOrFileVer);
try {
listing.UnselectAll();
listing.SetVirtualSelection(objOrFileVers);
} catch (e) {
if (setTimeout) {
setTimeout(function () { selObj0(shellFrame, listing, objVer); }, 0);
} else {
selObj0(shellFrame, listing, objVer);
}
}
} else {
if (setTimeout) {
setTimeout(function () { selObj0(shellFrame, listing, objVer); }, 0);
} else {
selObj0(shellFrame, listing, objVer);
}
}
function selObj0(sf, li, ov) {
try {
// select the item natively in the listing so tasks and properties pane are shown
// this will succeed on top level items
li.SelectObjectVersion(ov);
if (sf.BottomPane.Visible) sf.BottomPane.ShowDefaultContent();
} catch (ee) {
// lower level items will fall back to this
// no tasks, manually load properties into property pane (double-click is broken this way ;-( )
if (sf.BottomPane.Visible) {
sf.BottomPane.ShowObjectVersionProperties(sf.ShellUI.vault.ObjectPropertyOperations.GetPropertiesWithIconClues(ov, false));
}
li.UnselectAll();
}
}
}
};
u.ui = ui;
}(MF)); | mit |
mlorbetske/cli | src/Microsoft.DotNet.ProjectJsonMigration/Microsoft.DotNet.Internal.ProjectModel/CommonCompilerOptions.cs | 7220 | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.DotNet.Internal.ProjectModel.Files;
namespace Microsoft.DotNet.Internal.ProjectModel
{
internal class CommonCompilerOptions
{
public IEnumerable<string> Defines { get; set; }
public string LanguageVersion { get; set; }
public string Platform { get; set; }
public bool? AllowUnsafe { get; set; }
public bool? WarningsAsErrors { get; set; }
public bool? Optimize { get; set; }
public string KeyFile { get; set; }
public bool? DelaySign { get; set; }
public bool? PublicSign { get; set; }
public string DebugType { get; set; }
public bool? EmitEntryPoint { get; set; }
public bool? PreserveCompilationContext { get; set; }
public bool? GenerateXmlDocumentation { get; set; }
public IEnumerable<string> SuppressWarnings { get; set; }
public IEnumerable<string> AdditionalArguments { get; set; }
public string OutputName { get; set; }
public string CompilerName { get; set; }
public IncludeContext CompileInclude { get; set; }
public IncludeContext EmbedInclude { get; set; }
public IncludeContext CopyToOutputInclude { get; set; }
public override bool Equals(object obj)
{
var other = obj as CommonCompilerOptions;
return other != null &&
LanguageVersion == other.LanguageVersion &&
Platform == other.Platform &&
AllowUnsafe == other.AllowUnsafe &&
WarningsAsErrors == other.WarningsAsErrors &&
Optimize == other.Optimize &&
KeyFile == other.KeyFile &&
DelaySign == other.DelaySign &&
PublicSign == other.PublicSign &&
DebugType == other.DebugType &&
EmitEntryPoint == other.EmitEntryPoint &&
GenerateXmlDocumentation == other.GenerateXmlDocumentation &&
PreserveCompilationContext == other.PreserveCompilationContext &&
EnumerableEquals(Defines, other.Defines) &&
EnumerableEquals(SuppressWarnings, other.SuppressWarnings) &&
EnumerableEquals(AdditionalArguments, other.AdditionalArguments) &&
OutputName == other.OutputName &&
CompilerName == other.CompilerName &&
IsEqual(CompileInclude, other.CompileInclude) &&
IsEqual(EmbedInclude, other.EmbedInclude) &&
IsEqual(CopyToOutputInclude, other.CopyToOutputInclude);
}
private static bool IsEqual(IncludeContext first, IncludeContext second)
{
if (first == null || second == null)
{
return first == second;
}
return first.Equals(second);
}
private static bool EnumerableEquals(IEnumerable<string> left, IEnumerable<string> right)
=> Enumerable.SequenceEqual(left ?? EmptyArray<string>.Value, right ?? EmptyArray<string>.Value);
public override int GetHashCode()
{
return base.GetHashCode();
}
private static IEnumerable<string> Combine(IEnumerable<string> @new, IEnumerable<string> old)
{
if (@new != null)
{
old = old ?? EmptyArray<string>.Value;
return old.Concat(@new).Distinct().ToArray();
}
return old;
}
public static CommonCompilerOptions Combine(params CommonCompilerOptions[] options)
{
var result = new CommonCompilerOptions();
foreach (var option in options)
{
// Skip null options
if (option == null)
{
continue;
}
// Defines, suppressions, and additional arguments are always combined
result.Defines = Combine(option.Defines, result.Defines);
result.SuppressWarnings = Combine(option.SuppressWarnings, result.SuppressWarnings);
result.AdditionalArguments = Combine(option.AdditionalArguments, result.AdditionalArguments);
if (option.LanguageVersion != null)
{
result.LanguageVersion = option.LanguageVersion;
}
if (option.Platform != null)
{
result.Platform = option.Platform;
}
if (option.AllowUnsafe != null)
{
result.AllowUnsafe = option.AllowUnsafe;
}
if (option.WarningsAsErrors != null)
{
result.WarningsAsErrors = option.WarningsAsErrors;
}
if (option.Optimize != null)
{
result.Optimize = option.Optimize;
}
if (option.KeyFile != null)
{
result.KeyFile = option.KeyFile;
}
if (option.DelaySign != null)
{
result.DelaySign = option.DelaySign;
}
if (option.PublicSign != null)
{
result.PublicSign = option.PublicSign;
}
if (option.DebugType != null)
{
result.DebugType = option.DebugType;
}
if (option.EmitEntryPoint != null)
{
result.EmitEntryPoint = option.EmitEntryPoint;
}
if (option.PreserveCompilationContext != null)
{
result.PreserveCompilationContext = option.PreserveCompilationContext;
}
if (option.GenerateXmlDocumentation != null)
{
result.GenerateXmlDocumentation = option.GenerateXmlDocumentation;
}
if (option.OutputName != null)
{
result.OutputName = option.OutputName;
}
if (option.CompileInclude != null)
{
result.CompileInclude = option.CompileInclude;
}
if (option.EmbedInclude != null)
{
result.EmbedInclude = option.EmbedInclude;
}
if (option.CopyToOutputInclude != null)
{
result.CopyToOutputInclude = option.CopyToOutputInclude;
}
// compilerName set in the root cannot be overriden.
if (result.CompilerName == null)
{
result.CompilerName = option.CompilerName;
}
}
return result;
}
}
}
| mit |
DDoS/SpongeAPI | src/main/java/org/spongepowered/api/block/trait/BooleanTrait.java | 1621 | /*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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.
*/
package org.spongepowered.api.block.trait;
import org.spongepowered.api.util.annotation.CatalogedBy;
/**
* Represents a type of {@link BlockTrait} that allows only {@link Boolean} of
* which two possible values may exist: <code>true</code> and <code>false</code>.
*/
@CatalogedBy(BooleanTraits.class)
public interface BooleanTrait extends BlockTrait<Boolean> {
}
| mit |
startinggravity/lean-drupal | node_modules/gulp/node_modules/gulp-util/lib/isNull.js | 58 | module.exports = function (v) {
return v === null;
};
| mit |
gn0st1k4m/phalcon-module-skeleton | public/dist/ns.js | 69 | window.ADM = (function() {
function ADM() {}
return ADM;
})();
| mit |
nivanov1984/nunit | src/NUnitFramework/framework/Internal/Results/TestCaseResult.cs | 3821 | // ***********************************************************************
// Copyright (c) 2015 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
#if PARALLEL
using System.Collections.Concurrent;
#endif
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Represents the result of running a single test case.
/// </summary>
public class TestCaseResult : TestResult
{
/// <summary>
/// Construct a TestCaseResult based on a TestMethod
/// </summary>
/// <param name="test">A TestMethod to which the result applies.</param>
public TestCaseResult(TestMethod test) : base(test) { }
#region Overrides
/// <summary>
/// Gets the number of test cases that failed
/// when running the test and all its children.
/// </summary>
public override int FailCount
{
get { return ResultState.Status == TestStatus.Failed ? 1 : 0; }
}
/// <summary>
/// Gets the number of test cases that had warnings
/// when running the test and all its children.
/// </summary>
public override int WarningCount
{
get { return ResultState.Status == TestStatus.Warning ? 1 : 0; }
}
/// <summary>
/// Gets the number of test cases that passed
/// when running the test and all its children.
/// </summary>
public override int PassCount
{
get { return ResultState.Status == TestStatus.Passed ? 1 : 0; }
}
/// <summary>
/// Gets the number of test cases that were skipped
/// when running the test and all its children.
/// </summary>
public override int SkipCount
{
get { return ResultState.Status == TestStatus.Skipped ? 1 : 0; }
}
/// <summary>
/// Gets the number of test cases that were inconclusive
/// when running the test and all its children.
/// </summary>
public override int InconclusiveCount
{
get { return ResultState.Status == TestStatus.Inconclusive ? 1 : 0; }
}
/// <summary>
/// Indicates whether this result has any child results.
/// </summary>
public override bool HasChildren
{
get { return false; }
}
/// <summary>
/// Gets the collection of child results.
/// </summary>
public override IEnumerable<ITestResult> Children
{
get { return new ITestResult[0]; }
}
#endregion
}
}
| mit |
JeffProgrammer/Torque2D-empty | engine/source/console/compiler.cc | 8820 | //-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
#include "platform/platform.h"
#include "console/console.h"
#include "debug/telnetDebugger.h"
#include "platform/event.h"
#include "console/ast.h"
#include "collection/findIterator.h"
#include "io/resource/resourceManager.h"
#include "string/findMatch.h"
#include "console/consoleInternal.h"
#include "io/fileStream.h"
#include "console/compiler.h"
#include "sim/simBase.h"
namespace Compiler
{
F64 consoleStringToNumber(const char *str, StringTableEntry file, U32 line)
{
F64 val = dAtof(str);
if(val != 0)
return val;
else if(!dStricmp(str, "true"))
return 1;
else if(!dStricmp(str, "false"))
return 0;
else if(file)
{
Con::warnf(ConsoleLogEntry::General, "%s (%d): string always evaluates to 0.", file, line);
return 0;
}
return 0;
}
//------------------------------------------------------------
CompilerStringTable *gCurrentStringTable, gGlobalStringTable, gFunctionStringTable;
CompilerFloatTable *gCurrentFloatTable, gGlobalFloatTable, gFunctionFloatTable;
DataChunker gConsoleAllocator;
CompilerIdentTable gIdentTable;
CodeBlock *gCurBreakBlock;
//------------------------------------------------------------
CodeBlock *getBreakCodeBlock() { return gCurBreakBlock; }
void setBreakCodeBlock(CodeBlock *cb) { gCurBreakBlock = cb; }
//------------------------------------------------------------
void evalSTEtoCode(StringTableEntry ste, U32 ip, U32 *codeStream)
{
#ifdef TORQUE_64
*((U64*)(codeStream+ip)) = (U64)ste;
#else
codeStream[ip] = (U32)ste;
#endif
}
void compileSTEtoCode(StringTableEntry ste, U32 ip, U32 *codeStream)
{
if(ste)
getIdentTable().add(ste, ip);
codeStream[ip] = 0;
codeStream[ip+1] = 0;
}
void (*STEtoCode)(StringTableEntry ste, U32 ip, U32 *codeStream) = evalSTEtoCode;
//------------------------------------------------------------
bool gSyntaxError = false;
//------------------------------------------------------------
CompilerStringTable *getCurrentStringTable() { return gCurrentStringTable; }
CompilerStringTable &getGlobalStringTable() { return gGlobalStringTable; }
CompilerStringTable &getFunctionStringTable() { return gFunctionStringTable; }
void setCurrentStringTable (CompilerStringTable* cst) { gCurrentStringTable = cst; }
CompilerFloatTable *getCurrentFloatTable() { return gCurrentFloatTable; }
CompilerFloatTable &getGlobalFloatTable() { return gGlobalFloatTable; }
CompilerFloatTable &getFunctionFloatTable() { return gFunctionFloatTable; }
void setCurrentFloatTable (CompilerFloatTable* cst) { gCurrentFloatTable = cst; }
CompilerIdentTable &getIdentTable() { return gIdentTable; }
void precompileIdent(StringTableEntry ident)
{
if(ident)
gGlobalStringTable.add(ident);
}
void resetTables()
{
setCurrentStringTable(&gGlobalStringTable);
setCurrentFloatTable(&gGlobalFloatTable);
getGlobalFloatTable().reset();
getGlobalStringTable().reset();
getFunctionFloatTable().reset();
getFunctionStringTable().reset();
getIdentTable().reset();
}
void *consoleAlloc(U32 size) { return gConsoleAllocator.alloc(size); }
void consoleAllocReset() { gConsoleAllocator.freeBlocks(); }
}
//-------------------------------------------------------------------------
using namespace Compiler;
//-------------------------------------------------------------------------
U32 CompilerStringTable::add(const char *str, bool caseSens, bool tag)
{
// Is it already in?
Entry **walk;
for(walk = &list; *walk; walk = &((*walk)->next))
{
if((*walk)->tag != tag)
continue;
if(caseSens)
{
if(!dStrcmp((*walk)->string, str))
return (*walk)->start;
}
else
{
if(!dStricmp((*walk)->string, str))
return (*walk)->start;
}
}
// Write it out.
Entry *newStr = (Entry *) consoleAlloc(sizeof(Entry));
*walk = newStr;
newStr->next = NULL;
newStr->start = totalLen;
U32 len = dStrlen(str) + 1;
if(tag && len < 7) // alloc space for the numeric tag 1 for tag, 5 for # and 1 for nul
len = 7;
totalLen += len;
newStr->string = (char *) consoleAlloc(len);
newStr->len = len;
newStr->tag = tag;
dStrcpy(newStr->string, str);
#ifdef EMSCRIPTEN
consoleAlloc(2);
//Con::printf("CompilerStringTable::add(%s) %s %s @ %u:%u", str, caseSens ? "CASE" : "NOCASE", tag ? "TAG" : "NOTAG", newStr->string, len);
#endif
return newStr->start;
}
U32 CompilerStringTable::addIntString(U32 value)
{
dSprintf(buf, sizeof(buf), "%d", value);
return add(buf);
}
U32 CompilerStringTable::addFloatString(F64 value)
{
dSprintf(buf, sizeof(buf), "%.9g", value);
return add(buf);
}
void CompilerStringTable::reset()
{
list = NULL;
totalLen = 0;
}
char *CompilerStringTable::build()
{
char *ret = new char[totalLen];
for(Entry *walk = list; walk; walk = walk->next)
dStrcpy(ret + walk->start, walk->string);
return ret;
}
void CompilerStringTable::write(Stream &st)
{
st.write(totalLen);
for(Entry *walk = list; walk; walk = walk->next)
st.write(walk->len, walk->string);
}
//------------------------------------------------------------
U32 CompilerFloatTable::add(F64 value)
{
Entry **walk;
U32 i = 0;
for(walk = &list; *walk; walk = &((*walk)->next), i++)
if(value == (*walk)->val)
return i;
Entry *newFloat = (Entry *) consoleAlloc(sizeof(Entry));
newFloat->val = value;
newFloat->next = NULL;
count++;
*walk = newFloat;
return count-1;
}
void CompilerFloatTable::reset()
{
list = NULL;
count = 0;
}
F64 *CompilerFloatTable::build()
{
F64 *ret = new F64[count];
U32 i = 0;
for(Entry *walk = list; walk; walk = walk->next, i++)
ret[i] = walk->val;
return ret;
}
void CompilerFloatTable::write(Stream &st)
{
st.write(count);
for(Entry *walk = list; walk; walk = walk->next)
st.write(walk->val);
}
//------------------------------------------------------------
void CompilerIdentTable::reset()
{
list = NULL;
}
void CompilerIdentTable::add(StringTableEntry ste, U32 ip)
{
U32 index = gGlobalStringTable.add(ste, false);
Entry *newEntry = (Entry *) consoleAlloc(sizeof(Entry));
newEntry->offset = index;
newEntry->ip = ip;
for(Entry *walk = list; walk; walk = walk->next)
{
if(walk->offset == index)
{
newEntry->nextIdent = walk->nextIdent;
walk->nextIdent = newEntry;
return;
}
}
newEntry->next = list;
list = newEntry;
newEntry->nextIdent = NULL;
}
void CompilerIdentTable::write(Stream &st)
{
U32 count = 0;
Entry * walk;
for(walk = list; walk; walk = walk->next)
count++;
st.write(count);
for(walk = list; walk; walk = walk->next)
{
U32 ec = 0;
Entry * el;
for(el = walk; el; el = el->nextIdent)
ec++;
st.write(walk->offset);
st.write(ec);
for(el = walk; el; el = el->nextIdent)
st.write(el->ip);
}
}
| mit |
rohitw1991/smartfrappe | frappe/public/js/frappe/views/ganttview.js | 4671 | // Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt
frappe.provide("frappe.views.calendar");
frappe.views.GanttFactory = frappe.views.Factory.extend({
make: function(route) {
var me = this;
frappe.model.with_doctype(route[1], function() {
var page = me.make_page();
$(page).on("show", function() {
me.set_filters_from_route_options();
});
var options = {
doctype: route[1],
page: page
};
$.extend(options, frappe.views.calendar[route[1]] || {});
page.ganttview = new frappe.views.Gantt(options);
});
}
});
frappe.views.Gantt = Class.extend({
init: function(opts) {
$.extend(this, opts);
frappe.require('assets/frappe/js/lib/jQuery.Gantt/css/style.css');
frappe.require('assets/frappe/js/lib/jQuery.Gantt/js/jquery.fn.gantt.js');
this.make_page();
frappe.route_options ?
this.set_filters_from_route_options() :
this.refresh();
},
make_page: function() {
var module = locals.DocType[this.doctype].module,
me = this;
this.appframe = this.page.appframe;
this.appframe.set_title(__("Gantt Chart") + " - " + __(this.doctype));
this.appframe.add_module_icon(module)
this.appframe.set_views_for(this.doctype, "gantt");
this.appframe.set_title_right("Refresh",
function() { me.refresh(); }, "icon-refresh")
this.appframe.add_field({fieldtype:"Date", label:"From",
fieldname:"start", "default": frappe.datetime.month_start(), input_css: {"z-index": 3}});
this.appframe.add_field({fieldtype:"Date", label:"To",
fieldname:"end", "default": frappe.datetime.month_end(), input_css: {"z-index": 3}});
if(this.filters) {
$.each(this.filters, function(i, df) {
me.appframe.add_field(df);
return false;
});
}
},
refresh: function() {
var parent = $(this.page)
.find(".layout-main")
.empty()
.css('min-height', '300px')
.html('<div class="alert alert-info">Loading...</div>');
var me = this;
return frappe.call({
method: this.get_events_method,
type: "GET",
args: {
doctype: this.doctype,
start: this.appframe.fields_dict.start.get_parsed_value(),
end: this.appframe.fields_dict.end.get_parsed_value(),
filters: this.get_filters()
},
callback: function(r) {
$(parent).empty();
if(!r.message || !r.message.length) {
$(parent).html('<div class="alert alert-info">' + __('Nothing to show for this selection') + '</div>');
} else {
var gantt_area = $('<div class="gantt">').appendTo(parent);
gantt_area.gantt({
source: me.get_source(r),
navigate: "scroll",
scale: "days",
minScale: "hours",
maxScale: "months",
onItemClick: function(data) {
frappe.set_route('Form', me.doctype, data.name);
},
onAddClick: function(dt, rowId) {
newdoc(me.doctype);
}
});
}
}
})
},
set_filter: function(doctype, value) {
var me = this;
if(this.filters) {
$.each(this.filters, function(i, df) {
if(df.options===value)
me.appframe.fields_dict[df.fieldname].set_input(value);
return false;
});
}
},
get_filters: function() {
var filter_vals = {},
me = this;
if(this.filters) {
$.each(this.filters, function(i, df) {
filter_vals[df.fieldname || df.label] =
me.appframe.fields_dict[df.fieldname || df.label].get_parsed_value();
});
}
return filter_vals;
},
get_source: function(r) {
var source = [],
me = this;
// projects
$.each(r.message, function(i,v) {
// standardize values
$.each(me.field_map, function(target, source) {
v[target] = v[source];
});
if(v.start && !v.end) {
v.end = new Date(v.start)
v.end.setHours(v.end.getHours() + 1);
}
if(v.start && v.end) {
source.push({
name: v.title,
desc: v.status,
values: [{
name: v.title,
desc: v.title + "<br>" + (v.status || ""),
from: '/Date('+moment(v.start).format("X")+'000)/',
to: '/Date('+moment(v.end).format("X")+'000)/',
customClass: {
'danger':'ganttRed',
'warning':'ganttOrange',
'info':'ganttBlue',
'success':'ganttGreen',
'':'ganttGray'
}[me.style_map ?
me.style_map[v.status] :
frappe.utils.guess_style(v.status, "standard")],
dataObj: v
}]
})
}
});
return source
},
set_filters_from_route_options: function() {
var me = this;
if(frappe.route_options) {
$.each(frappe.route_options, function(k, value) {
if(me.appframe.fields_dict[k]) {
me.appframe.fields_dict[k].set_input(value);
me.refresh();
return false;
};
})
frappe.route_options = null;
}
}
});
| mit |
amkimian/Rapture | Libs/RaptureCore/src/main/java/rapture/kernel/cache/StructuredRepoCache.java | 2216 | /**
* The MIT License (MIT)
*
* Copyright (c) 2011-2016 Incapture Technologies LLC
*
* 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.
*/
package rapture.kernel.cache;
import org.apache.log4j.Logger;
import rapture.common.Scheme;
import rapture.common.StructuredRepoConfig;
import rapture.common.StructuredRepoConfigStorage;
import rapture.repo.StructuredRepo;
import rapture.structured.StructuredFactory;
import rapture.structured.StructuredStore;
public class StructuredRepoCache extends AbstractRepoCache<StructuredRepoConfig, StructuredRepo> {
@SuppressWarnings("unused")
private static Logger log = Logger.getLogger(StructuredRepoCache.class);
public StructuredRepoCache() {
super(Scheme.STRUCTURED.toString());
}
@Override
public StructuredRepoConfig reloadConfig(String authority) {
return StructuredRepoConfigStorage.readByFields(authority);
}
@Override
public StructuredRepo reloadRepository(StructuredRepoConfig config, boolean autoloadIndex) {
StructuredStore store = StructuredFactory.getRepo(config.getConfig(), config.getAuthority());
return store == null ? null : new StructuredRepo(store);
}
}
| mit |
somenathghosh/Appraisal-App | node_modules/grunt-contrib-jade/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/stream-api-pipe.js | 515 | var readdirp = require('..')
, path = require('path')
, es = require('event-stream');
// print out all JavaScript files along with their size
readdirp({ root: path.join(__dirname), fileFilter: '*.js' })
.on('warn', function (err) { console.error('non-fatal error', err); })
.on('error', function (err) { console.error('fatal error', err); })
.pipe(es.mapSync(function (entry) {
return { path: entry.path, size: entry.stat.size };
}))
.pipe(es.stringify())
.pipe(process.stdout);
| mit |
SidHarder/meetings | client/jspm_packages/npm/core-js@2.1.0/library/modules/_iter-detect.js | 591 | /* */
var ITERATOR = require('./_wks')('iterator'),
SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function() {
SAFE_CLOSING = true;
};
Array.from(riter, function() {
throw 2;
});
} catch (e) {}
module.exports = function(exec, skipClosing) {
if (!skipClosing && !SAFE_CLOSING)
return false;
var safe = false;
try {
var arr = [7],
iter = arr[ITERATOR]();
iter.next = function() {
safe = true;
};
arr[ITERATOR] = function() {
return iter;
};
exec(arr);
} catch (e) {}
return safe;
};
| mit |
hatton/libpalaso | PalasoUIWindowsForms/Proxy/ProxyCredentialsRequestDialog.cs | 4228 | using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using Palaso.Network;
namespace Palaso.UI.WindowsForms.Proxy
{
public partial class ProxyCredentialsRequestDialog : Form
{
public ProxyCredentialsRequestDialog()
{
InitializeComponent();
Text = Application.ProductName + ": Proxy Credentials";
}
/// <summary>
/// Get proxy creds from a place (not settings) that all palaso apps can share
/// </summary>
/// <returns>true if some credentials were found</returns>
public static bool ReadProxyCredentials(out string user, out string password)
{
user = string.Empty;
password = string.Empty;
try
{
string path = GetPathToProxyCredentialsFile();
if (!File.Exists(path))
{
return false;
}
var lines = File.ReadAllLines(path);
if (lines.Length < 2)
return false;
var userParts = lines[0].Split(new string[] {"=="}, 2, StringSplitOptions.RemoveEmptyEntries);
if (userParts.Length != 2)
return false;
var passwordParts = lines[1].Split(new string[] {"=="}, 2, StringSplitOptions.RemoveEmptyEntries);
if (passwordParts.Length != 2)
return false;
user = userParts[1].Trim();
password = passwordParts[1].Trim();
return true;
}
catch (Exception error)
{
Debug.Fail(error.Message);// don't do anything to a non-debug user, though.
}
return false;
}
public static void SaveProxyCredentials(string user, string password)
{
try
{
string path = GetPathToProxyCredentialsFile();
File.WriteAllText(path, string.Format("user=={0}\r\npassword=={1}", user, password));
}
catch(Exception error)
{
Debug.Fail(error.Message);
}
}
private static string GetPathToProxyCredentialsFile()
{
var path = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
path = Path.Combine(path, "Palaso");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path = Path.Combine(path, "proxy.txt");
return path;
}
/// <summary>
///
/// </summary>
/// <param name="doTryStoredCredentials">Call it first with this true, but if that doesn't work, call with this
/// false so that we ask the user again</param>
/// <returns></returns>
public static ICredentials GetCredentials(bool doTryStoredCredentials)
{
ProxyCredentialSettings settings = new ProxyCredentialSettings();
using (var dlg = new ProxyCredentialsRequestDialog())
{
string userName=string.Empty;
string password=string.Empty;
try
{
string encryptedUserName;
string encryptedPassword;
ReadProxyCredentials(out encryptedUserName, out encryptedPassword);
userName = RobustNetworkOperation.GetClearText(encryptedUserName);
password = RobustNetworkOperation.GetClearText(encryptedPassword);
}
catch (Exception)
{
//swallow and just give them blanks in the dialog
}
// should we ask the user for info?
if (!doTryStoredCredentials || string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
{
dlg._userName.Text = userName;
dlg._password.Text = password;
if (DialogResult.OK != dlg.ShowDialog(null))
return null;
if (string.IsNullOrEmpty(dlg._userName.Text))
return null;
if (string.IsNullOrEmpty(dlg._password.Text))
return null;
if (dlg._remember.Checked)
{
SaveProxyCredentials(GetEncryptedText(userName), GetEncryptedText(password));
}
}
return new NetworkCredential(userName, password);
}
}
private static string GetEncryptedText(string clearText)
{
byte[] nameBytes = Encoding.Unicode.GetBytes(clearText);
byte[] encryptedNameBytes = ProtectedData.Protect(nameBytes, null, DataProtectionScope.CurrentUser);
return Convert.ToBase64String(encryptedNameBytes);
}
private void _okButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
}
private void _cancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
private void _headerLabel_Click(object sender, EventArgs e)
{
}
}
}
| mit |
one-gulp/one-gulp | node_modules/graphviz/Jakefile.js | 1205 | // This file is a node-jake file -- http://github.com/mde/node-jake
var util = require('util'),
exec = require('child_process').exec,
child;
var docTitle = 'node-graphviz'
var docFiles = 'lib/graphviz.js lib/deps/graph.js lib/deps/node.js lib/deps/edge.js'
var outputDocFile = 'documentation.json'
var docRibbon = 'http://github.com/glejeune/node-graphviz'
var docDesc = '[Node.js](http://nodejs.org) interface to the [GraphViz](http://graphviz.org) graphing tool'
desc('Generate node-graphviz documentation.');
task('doc', [], function () {
child = exec('dox -r ' + docRibbon + ' -d "' + docDesc + '" -t "' + docTitle + '" < ' + docFiles + ' > ' + outputDocFile,
function (error, stdout, stderr) {
if (error !== null) {
console.log('exec error: ' + error);
}
});
});
desc('Install');
task('install', [], function() {
child = exec('npm install .',
function(error, stdout, stderr) {
if (error !== null) {
console.log('exec error: ' + error);
}
}
);
});
desc('Publish');
task('publish', [], function() {
child = exec('npm publish .',
function(error, stdout, stderr) {
if (error !== null) {
console.log('exec error: ' + error);
}
}
);
});
| mit |
triggertoo/whatsup | src/vendor/zend/demos/Zend/Wildfire/application/controllers/ErrorController.php | 1539 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Wildfire
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* A sample error controller.
*
* @category Zend
* @package Zend_Wildfire
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class ErrorController extends Zend_Controller_Action
{
public function errorAction()
{
/*
* Make sure we don't log exceptions thrown during the exception logging.
* If we do we will create an infinite loop!
*/
try {
Zend_Registry::get('logger')->err($this->_getParam('error_handler')->exception);
} catch(Exception $e) {
/* TODO: You can log this exception somewhere or display it during development.
* DO NOT USE THE logger here as it will create an infinite loop!
*/
}
}
}
| mit |
insiders/KunstmaanBundlesCMS | src/Kunstmaan/PagePartBundle/Form/TextPagePartAdminType.php | 908 | <?php
namespace Kunstmaan\PagePartBundle\Form;
use Kunstmaan\AdminBundle\Form\WysiwygType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* TextPagePartAdminType
*/
class TextPagePartAdminType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('content', WysiwygType::class, [
'label' => 'pagepart.text.content',
'required' => false,
]);
}
/**
* @return string
*/
public function getBlockPrefix()
{
return 'kunstmaan_pagepartbundle_textpageparttype';
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'Kunstmaan\PagePartBundle\Entity\TextPagePart',
]);
}
}
| mit |
vgupta6/Project-2 | controllers/member.py | 6787 | # -*- coding: utf-8 -*-
"""
Membership Management
"""
module = request.controller
resourcename = request.function
if not settings.has_module(module):
raise HTTP(404, body="Module disabled: %s" % module)
# =============================================================================
def index():
""" Dashboard """
module_name = settings.modules[module].name_nice
response.title = module_name
item = None
if settings.has_module("cms"):
table = s3db.cms_post
_item = db(table.module == module).select(table.id,
table.body,
limitby=(0, 1)).first()
if _item:
if s3_has_role(ADMIN):
item = DIV(XML(_item.body),
BR(),
A(T("Edit"),
_href=URL(c="cms", f="post",
args=[_item.id, "update"],
vars={"module":module}),
_class="action-btn"))
else:
item = XML(_item.body)
elif s3_has_role(ADMIN):
item = DIV(H2(module_name),
A(T("Edit"),
_href=URL(c="cms", f="post", args="create",
vars={"module":module}),
_class="action-btn"))
if not item:
#item = H2(module_name)
# Just redirect to the list of Members
redirect(URL(f="membership"))
# tbc
report = ""
response.view = "index.html"
return dict(item=item, report=report)
# =============================================================================
def membership_type():
"""
REST Controller
"""
output = s3_rest_controller()
return output
# =============================================================================
def membership():
"""
REST Controller
"""
tablename = "member_membership"
table = s3db[tablename]
def prep(r):
if r.interactive:
if r.id and r.component is None and r.method != "delete":
# Redirect to person controller
vars = {"membership.id": r.id}
redirect(URL(f="person", vars=vars))
else:
# Assume members under 120
s3db.pr_person.date_of_birth.widget = S3DateWidget(past=1440)
return True
s3.prep = prep
def postp(r, output):
if r.interactive and r.component is None:
# Set the minimum end_date to the same as the start_date
s3.jquery_ready.append(
'''S3.start_end_date('member_membership_start_date','member_membership_end_date')''')
return output
s3.postp = postp
output = s3_rest_controller(rheader=s3db.member_rheader)
return output
# =============================================================================
def person():
"""
Person Controller
- used for Personal Profile & Imports
- includes components relevant to Membership
"""
tablename = "pr_person"
table = s3db.pr_person
s3.crud_strings[tablename].update(
title_upload = T("Import Members"))
# Custom Method for Contacts
s3db.set_method("pr", resourcename,
method="contacts",
action=s3db.pr_contacts)
# Upload for configuration (add replace option)
s3.importerPrep = lambda: \
dict(ReplaceOption=T("Remove existing data before import"))
# Import pre-process
def import_prep(data):
"""
Deletes all Member records of the organisation
before processing a new data import, used for the import_prep
hook in s3mgr
"""
resource, tree = data
xml = current.xml
tag = xml.TAG
att = xml.ATTRIBUTE
if s3.import_replace:
if tree is not None:
root = tree.getroot()
expr = "/%s/%s[@%s='org_organisation']/%s[@%s='name']" % \
(tag.root, tag.resource, att.name, tag.data, att.field)
orgs = root.xpath(expr)
for org in orgs:
org_name = org.get("value", None) or org.text
if org_name:
try:
org_name = json.loads(xml.xml_decode(org_name))
except:
pass
if org_name:
mtable = s3db.member_membership
otable = s3db.org_organisation
query = (otable.name == org_name) & \
(mtable.organisation_id == otable.id)
resource = s3db.resource("member_membership", filter=query)
ondelete = s3db.get_config("member_membership", "ondelete")
resource.delete(ondelete=ondelete, format="xml", cascade=True)
s3mgr.import_prep = import_prep
# CRUD pre-process
def prep(r):
if r.interactive and r.method != "import":
if not r.component:
# Assume members under 120
s3db.pr_person.date_of_birth.widget = S3DateWidget(past=1440)
resource = r.resource
if resource.count() == 1:
resource.load()
r.record = resource.records().first()
if r.record:
r.id = r.record.id
if not r.record:
session.error = T("Record not found")
redirect(URL(f="membership",
#args=["search"]
))
member_id = request.get_vars.get("membership.id", None)
if member_id and r.component_name == "membership":
r.component_id = member_id
s3db.configure("member_membership",
insertable = False)
return True
s3.prep = prep
def postp(r, output):
if r.interactive and r.component and r.component_name == "membership":
# Set the minimum end_date to the same as the start_date
s3.jquery_ready.append(
'''S3.start_end_date('member_membership_start_date','member_membership_end_date')''')
return output
s3.postp = postp
output = s3_rest_controller("pr", resourcename,
native=False,
rheader=s3db.member_rheader,
replace_option=T("Remove existing data before import"))
return output
# END =========================================================================
| mit |
fxcosta/DesignPatternsPHP | Creational/AbstractFactory/Html/Text.php | 430 | <?php
namespace DesignPatterns\Creational\AbstractFactory\Html;
use DesignPatterns\Creational\AbstractFactory\Text as BaseText;
/**
* Class Text.
*
* Text is a concrete text for HTML rendering
*/
class Text extends BaseText
{
/**
* some crude rendering from HTML output.
*
* @return string
*/
public function render()
{
return '<div>'.htmlspecialchars($this->text).'</div>';
}
}
| mit |
ryantheleach/SpongeCommon | src/main/java/org/spongepowered/common/mixin/core/world/gen/populators/MixinWorldGenIcePath.java | 5386 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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.
*/
package org.spongepowered.common.mixin.core.world.gen.populators;
import com.google.common.base.Objects;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.gen.feature.WorldGenIcePath;
import org.spongepowered.api.util.weighted.VariableAmount;
import org.spongepowered.api.world.Chunk;
import org.spongepowered.api.world.gen.PopulatorType;
import org.spongepowered.api.world.gen.PopulatorTypes;
import org.spongepowered.api.world.gen.populator.IcePath;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.Random;
@Mixin(WorldGenIcePath.class)
public abstract class MixinWorldGenIcePath implements IcePath {
private VariableAmount radius;
private VariableAmount sections;
@Shadow private Block block;
@Inject(method = "<init>(I)V", at = @At("RETURN") )
public void onConstructed(int radius, CallbackInfo ci) {
this.radius = VariableAmount.baseWithRandomAddition(2, radius > 2 ? radius - 2 : 1);
this.sections = VariableAmount.fixed(2);
}
@Override
public PopulatorType getType() {
return PopulatorTypes.ICE_PATH;
}
@Override
public void populate(Chunk chunk, Random random) {
World world = (World) chunk.getWorld();
int x;
int z;
BlockPos chunkPos = new BlockPos(chunk.getBlockMin().getX(), chunk.getBlockMin().getY(), chunk.getBlockMin().getZ());
int n = this.sections.getFlooredAmount(random);
for (int i = 0; i < n; ++i) {
x = random.nextInt(16) + 8;
z = random.nextInt(16) + 8;
generate(world, random, world.getHeight(chunkPos.add(x, 0, z)));
}
}
/**
* @author Deamon - December 12th, 2015
*
* @reason Overwritten to replace the path radius with one dependent on
* our variable amount.
*/
@Overwrite
public boolean generate(World worldIn, Random rand, BlockPos position) {
while (worldIn.isAirBlock(position) && position.getY() > 2) {
position = position.down();
}
if (worldIn.getBlockState(position).getBlock() != Blocks.snow) {
return false;
}
// Sponge start
int i = this.radius.getFlooredAmount(rand);
// Sponge end
byte b0 = 1;
for (int j = position.getX() - i; j <= position.getX() + i; ++j) {
for (int k = position.getZ() - i; k <= position.getZ() + i; ++k) {
int l = j - position.getX();
int i1 = k - position.getZ();
if (l * l + i1 * i1 <= i * i) {
for (int j1 = position.getY() - b0; j1 <= position.getY() + b0; ++j1) {
BlockPos blockpos1 = new BlockPos(j, j1, k);
Block block = worldIn.getBlockState(blockpos1).getBlock();
if (block == Blocks.dirt || block == Blocks.snow || block == Blocks.ice) {
worldIn.setBlockState(blockpos1, this.block.getDefaultState(), 2);
}
}
}
}
}
return true;
}
@Override
public VariableAmount getRadius() {
return this.radius;
}
@Override
public void setRadius(VariableAmount radius) {
this.radius = radius;
}
@Override
public VariableAmount getSectionsPerChunk() {
return this.sections;
}
@Override
public void setSectionsPerChunk(VariableAmount sections) {
this.sections = sections;
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("Type", "IcePath")
.add("PerChunk", this.sections)
.add("Radius", this.radius)
.toString();
}
}
| mit |
martindale/scallion | opentk/Source/OpenTK/Input/Key.cs | 11754 | #region License
//
// The Open Toolkit Library License
//
// Copyright (c) 2006 - 2009 the Open Toolkit library.
//
// 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.
//
#endregion
namespace OpenTK.Input
{
/// <summary>
/// The available keyboard keys.
/// </summary>
public enum Key : int
{
/// <summary>A key outside the known keys.</summary>
Unknown = 0,
// Modifiers
/// <summary>The left shift key.</summary>
ShiftLeft,
/// <summary>The left shift key (equivalent to ShiftLeft).</summary>
LShift = ShiftLeft,
/// <summary>The right shift key.</summary>
ShiftRight,
/// <summary>The right shift key (equivalent to ShiftRight).</summary>
RShift = ShiftRight,
/// <summary>The left control key.</summary>
ControlLeft,
/// <summary>The left control key (equivalent to ControlLeft).</summary>
LControl = ControlLeft,
/// <summary>The right control key.</summary>
ControlRight,
/// <summary>The right control key (equivalent to ControlRight).</summary>
RControl = ControlRight,
/// <summary>The left alt key.</summary>
AltLeft,
/// <summary>The left alt key (equivalent to AltLeft.</summary>
LAlt = AltLeft,
/// <summary>The right alt key.</summary>
AltRight,
/// <summary>The right alt key (equivalent to AltRight).</summary>
RAlt = AltRight,
/// <summary>The left win key.</summary>
WinLeft,
/// <summary>The left win key (equivalent to WinLeft).</summary>
LWin = WinLeft,
/// <summary>The right win key.</summary>
WinRight,
/// <summary>The right win key (equivalent to WinRight).</summary>
RWin = WinRight,
/// <summary>The menu key.</summary>
Menu,
// Function keys (hopefully enough for most keyboards - mine has 26)
// <keysymdef.h> on X11 reports up to 35 function keys.
/// <summary>The F1 key.</summary>
F1,
/// <summary>The F2 key.</summary>
F2,
/// <summary>The F3 key.</summary>
F3,
/// <summary>The F4 key.</summary>
F4,
/// <summary>The F5 key.</summary>
F5,
/// <summary>The F6 key.</summary>
F6,
/// <summary>The F7 key.</summary>
F7,
/// <summary>The F8 key.</summary>
F8,
/// <summary>The F9 key.</summary>
F9,
/// <summary>The F10 key.</summary>
F10,
/// <summary>The F11 key.</summary>
F11,
/// <summary>The F12 key.</summary>
F12,
/// <summary>The F13 key.</summary>
F13,
/// <summary>The F14 key.</summary>
F14,
/// <summary>The F15 key.</summary>
F15,
/// <summary>The F16 key.</summary>
F16,
/// <summary>The F17 key.</summary>
F17,
/// <summary>The F18 key.</summary>
F18,
/// <summary>The F19 key.</summary>
F19,
/// <summary>The F20 key.</summary>
F20,
/// <summary>The F21 key.</summary>
F21,
/// <summary>The F22 key.</summary>
F22,
/// <summary>The F23 key.</summary>
F23,
/// <summary>The F24 key.</summary>
F24,
/// <summary>The F25 key.</summary>
F25,
/// <summary>The F26 key.</summary>
F26,
/// <summary>The F27 key.</summary>
F27,
/// <summary>The F28 key.</summary>
F28,
/// <summary>The F29 key.</summary>
F29,
/// <summary>The F30 key.</summary>
F30,
/// <summary>The F31 key.</summary>
F31,
/// <summary>The F32 key.</summary>
F32,
/// <summary>The F33 key.</summary>
F33,
/// <summary>The F34 key.</summary>
F34,
/// <summary>The F35 key.</summary>
F35,
// Direction arrows
/// <summary>The up arrow key.</summary>
Up,
/// <summary>The down arrow key.</summary>
Down,
/// <summary>The left arrow key.</summary>
Left,
/// <summary>The right arrow key.</summary>
Right,
/// <summary>The enter key.</summary>
Enter,
/// <summary>The escape key.</summary>
Escape,
/// <summary>The space key.</summary>
Space,
/// <summary>The tab key.</summary>
Tab,
/// <summary>The backspace key.</summary>
BackSpace,
/// <summary>The backspace key (equivalent to BackSpace).</summary>
Back = BackSpace,
/// <summary>The insert key.</summary>
Insert,
/// <summary>The delete key.</summary>
Delete,
/// <summary>The page up key.</summary>
PageUp,
/// <summary>The page down key.</summary>
PageDown,
/// <summary>The home key.</summary>
Home,
/// <summary>The end key.</summary>
End,
/// <summary>The caps lock key.</summary>
CapsLock,
/// <summary>The scroll lock key.</summary>
ScrollLock,
/// <summary>The print screen key.</summary>
PrintScreen,
/// <summary>The pause key.</summary>
Pause,
/// <summary>The num lock key.</summary>
NumLock,
// Special keys
/// <summary>The clear key (Keypad5 with NumLock disabled, on typical keyboards).</summary>
Clear,
/// <summary>The sleep key.</summary>
Sleep,
/*LogOff,
Help,
Undo,
Redo,
New,
Open,
Close,
Reply,
Forward,
Send,
Spell,
Save,
Calculator,
// Folders and applications
Documents,
Pictures,
Music,
MediaPlayer,
Mail,
Browser,
Messenger,
// Multimedia keys
Mute,
PlayPause,
Stop,
VolumeUp,
VolumeDown,
TrackPrevious,
TrackNext,*/
// Keypad keys
/// <summary>The keypad 0 key.</summary>
Keypad0,
/// <summary>The keypad 1 key.</summary>
Keypad1,
/// <summary>The keypad 2 key.</summary>
Keypad2,
/// <summary>The keypad 3 key.</summary>
Keypad3,
/// <summary>The keypad 4 key.</summary>
Keypad4,
/// <summary>The keypad 5 key.</summary>
Keypad5,
/// <summary>The keypad 6 key.</summary>
Keypad6,
/// <summary>The keypad 7 key.</summary>
Keypad7,
/// <summary>The keypad 8 key.</summary>
Keypad8,
/// <summary>The keypad 9 key.</summary>
Keypad9,
/// <summary>The keypad divide key.</summary>
KeypadDivide,
/// <summary>The keypad multiply key.</summary>
KeypadMultiply,
/// <summary>The keypad subtract key.</summary>
KeypadSubtract,
/// <summary>The keypad minus key (equivalent to KeypadSubtract).</summary>
KeypadMinus = KeypadSubtract,
/// <summary>The keypad add key.</summary>
KeypadAdd,
/// <summary>The keypad plus key (equivalent to KeypadAdd).</summary>
KeypadPlus = KeypadAdd,
/// <summary>The keypad decimal key.</summary>
KeypadDecimal,
/// <summary>The keypad enter key.</summary>
KeypadEnter,
// Letters
/// <summary>The A key.</summary>
A,
/// <summary>The B key.</summary>
B,
/// <summary>The C key.</summary>
C,
/// <summary>The D key.</summary>
D,
/// <summary>The E key.</summary>
E,
/// <summary>The F key.</summary>
F,
/// <summary>The G key.</summary>
G,
/// <summary>The H key.</summary>
H,
/// <summary>The I key.</summary>
I,
/// <summary>The J key.</summary>
J,
/// <summary>The K key.</summary>
K,
/// <summary>The L key.</summary>
L,
/// <summary>The M key.</summary>
M,
/// <summary>The N key.</summary>
N,
/// <summary>The O key.</summary>
O,
/// <summary>The P key.</summary>
P,
/// <summary>The Q key.</summary>
Q,
/// <summary>The R key.</summary>
R,
/// <summary>The S key.</summary>
S,
/// <summary>The T key.</summary>
T,
/// <summary>The U key.</summary>
U,
/// <summary>The V key.</summary>
V,
/// <summary>The W key.</summary>
W,
/// <summary>The X key.</summary>
X,
/// <summary>The Y key.</summary>
Y,
/// <summary>The Z key.</summary>
Z,
// Numbers
/// <summary>The number 0 key.</summary>
Number0,
/// <summary>The number 1 key.</summary>
Number1,
/// <summary>The number 2 key.</summary>
Number2,
/// <summary>The number 3 key.</summary>
Number3,
/// <summary>The number 4 key.</summary>
Number4,
/// <summary>The number 5 key.</summary>
Number5,
/// <summary>The number 6 key.</summary>
Number6,
/// <summary>The number 7 key.</summary>
Number7,
/// <summary>The number 8 key.</summary>
Number8,
/// <summary>The number 9 key.</summary>
Number9,
// Symbols
/// <summary>The tilde key.</summary>
Tilde,
/// <summary>The minus key.</summary>
Minus,
//Equal,
/// <summary>The plus key.</summary>
Plus,
/// <summary>The left bracket key.</summary>
BracketLeft,
/// <summary>The left bracket key (equivalent to BracketLeft).</summary>
LBracket = BracketLeft,
/// <summary>The right bracket key.</summary>
BracketRight,
/// <summary>The right bracket key (equivalent to BracketRight).</summary>
RBracket = BracketRight,
/// <summary>The semicolon key.</summary>
Semicolon,
/// <summary>The quote key.</summary>
Quote,
/// <summary>The comma key.</summary>
Comma,
/// <summary>The period key.</summary>
Period,
/// <summary>The slash key.</summary>
Slash,
/// <summary>The backslash key.</summary>
BackSlash,
/// <summary>Indicates the last available keyboard key.</summary>
LastKey
}
} | mit |
sho-h/ruby_env | ruby-2.3.3-x64-mingw32/lib/ruby/gems/2.3.0/gems/bundler-1.13.7/lib/bundler/plugin/api/source.rb | 11000 | # frozen_string_literal: true
require "uri"
require "digest/sha1"
module Bundler
module Plugin
class API
# This class provides the base to build source plugins
# All the method here are require to build a source plugin (except
# `uri_hash`, `gem_install_dir`; they are helpers).
#
# Defaults for methods, where ever possible are provided which is
# expected to work. But, all source plugins have to override
# `fetch_gemspec_files` and `install`. Defaults are also not provided for
# `remote!`, `cache!` and `unlock!`.
#
# The defaults shall work for most situations but nevertheless they can
# be (preferably should be) overridden as per the plugins' needs safely
# (as long as they behave as expected).
# On overriding `initialize` you should call super first.
#
# If required plugin should override `hash`, `==` and `eql?` methods to be
# able to match objects representing same sources, but may be created in
# different situation (like form gemfile and lockfile). The default ones
# checks only for class and uri, but elaborate source plugins may need
# more comparisons (e.g. git checking on branch or tag).
#
# @!attribute [r] uri
# @return [String] the remote specified with `source` block in Gemfile
#
# @!attribute [r] options
# @return [String] options passed during initialization (either from
# lockfile or Gemfile)
#
# @!attribute [r] name
# @return [String] name that can be used to uniquely identify a source
#
# @!attribute [rw] dependency_names
# @return [Array<String>] Names of dependencies that the source should
# try to resolve. It is not necessary to use this list intenally. This
# is present to be compatible with `Definition` and is used by
# rubygems source.
module Source
attr_reader :uri, :options, :name
attr_accessor :dependency_names
def initialize(opts)
@options = opts
@dependency_names = []
@uri = opts["uri"]
@type = opts["type"]
@name = opts["name"] || "#{@type} at #{@uri}"
end
# This is used by the default `spec` method to constructs the
# Specification objects for the gems and versions that can be installed
# by this source plugin.
#
# Note: If the spec method is overridden, this function is not necessary
#
# @return [Array<String>] paths of the gemspec files for gems that can
# be installed
def fetch_gemspec_files
[]
end
# Options to be saved in the lockfile so that the source plugin is able
# to check out same version of gem later.
#
# There options are passed when the source plugin is created from the
# lock file.
#
# @return [Hash]
def options_to_lock
{}
end
# Install the gem specified by the spec at appropriate path.
# `install_path` provides a sufficient default, if the source can only
# satisfy one gem, but is not binding.
#
# @return [String] post installation message (if any)
def install(spec, opts)
raise MalformattedPlugin, "Source plugins need to override the install method."
end
# It builds extensions, generates bins and installs them for the spec
# provided.
#
# It depends on `spec.loaded_from` to get full_gem_path. The source
# plugins should set that.
#
# It should be called in `install` after the plugin is done placing the
# gem at correct install location.
#
# It also runs Gem hooks `post_install`, `post_build` and `post_install`
#
# Note: Do not override if you don't know what you are doing.
def post_install(spec, disable_exts = false)
opts = { :env_shebang => false, :disable_extensions => disable_exts }
installer = Bundler::Source::Path::Installer.new(spec, opts)
installer.post_install
end
# A default installation path to install a single gem. If the source
# servers multiple gems, it's not of much use and the source should one
# of its own.
def install_path
@install_path ||=
begin
base_name = File.basename(URI.parse(uri).normalize.path)
gem_install_dir.join("#{base_name}-#{uri_hash[0..11]}")
end
end
# Parses the gemspec files to find the specs for the gems that can be
# satisfied by the source.
#
# Few important points to keep in mind:
# - If the gems are not installed then it shall return specs for all
# the gems it can satisfy
# - If gem is installed (that is to be detected by the plugin itself)
# then it shall return at least the specs that are installed.
# - The `loaded_from` for each of the specs shall be correct (it is
# used to find the load path)
#
# @return [Bundler::Index] index containing the specs
def specs
files = fetch_gemspec_files
Bundler::Index.build do |index|
files.each do |file|
next unless spec = Bundler.load_gemspec(file)
Bundler.rubygems.set_installed_by_version(spec)
spec.source = self
Bundler.rubygems.validate(spec)
index << spec
end
end
end
# Set internal representation to fetch the gems/specs from remote.
#
# When this is called, the source should try to fetch the specs and
# install from remote path.
def remote!
end
# Set internal representation to fetch the gems/specs from app cache.
#
# When this is called, the source should try to fetch the specs and
# install from the path provided by `app_cache_path`.
def cached!
end
# This is called to update the spec and installation.
#
# If the source plugin is loaded from lockfile or otherwise, it shall
# refresh the cache/specs (e.g. git sources can make a fresh clone).
def unlock!
end
# Name of directory where plugin the is expected to cache the gems when
# #cache is called.
#
# Also this name is matched against the directories in cache for pruning
#
# This is used by `app_cache_path`
def app_cache_dirname
base_name = File.basename(URI.parse(uri).normalize.path)
"#{base_name}-#{uri_hash}"
end
# This method is called while caching to save copy of the gems that the
# source can resolve to path provided by `app_cache_app`so that they can
# be reinstalled from the cache without querying the remote (i.e. an
# alternative to remote)
#
# This is stored with the app and source plugins should try to provide
# specs and install only from this cache when `cached!` is called.
#
# This cache is different from the internal caching that can be done
# at sub paths of `cache_path` (from API). This can be though as caching
# by bundler.
def cache(spec, custom_path = nil)
new_cache_path = app_cache_path(custom_path)
FileUtils.rm_rf(new_cache_path)
FileUtils.cp_r(install_path, new_cache_path)
FileUtils.touch(app_cache_path.join(".bundlecache"))
end
# This shall check if two source object represent the same source.
#
# The comparison shall take place only on the attribute that can be
# inferred from the options passed from Gemfile and not on attibutes
# that are used to pin down the gem to specific version (e.g. Git
# sources should compare on branch and tag but not on commit hash)
#
# The sources objects are constructed from Gemfile as well as from
# lockfile. To converge the sources, it is necessary that they match.
#
# The same applies for `eql?` and `hash`
def ==(other)
other.is_a?(self.class) && uri == other.uri
end
# When overriding `eql?` please preserve the behaviour as mentioned in
# docstring for `==` method.
alias_method :eql?, :==
# When overriding `hash` please preserve the behaviour as mentioned in
# docstring for `==` method, i.e. two methods equal by above comparison
# should have same hash.
def hash
[self.class, uri].hash
end
# A helper method, not necessary if not used internally.
def installed?
File.directory?(install_path)
end
# The full path where the plugin should cache the gem so that it can be
# installed latter.
#
# Note: Do not override if you don't know what you are doing.
def app_cache_path(custom_path = nil)
@app_cache_path ||= Bundler.app_cache(custom_path).join(app_cache_dirname)
end
# Used by definition.
#
# Note: Do not override if you don't know what you are doing.
def unmet_deps
specs.unmet_dependency_names
end
# Note: Do not override if you don't know what you are doing.
def can_lock?(spec)
spec.source == self
end
# Generates the content to be entered into the lockfile.
# Saves type and remote and also calls to `options_to_lock`.
#
# Plugin should use `options_to_lock` to save information in lockfile
# and not override this.
#
# Note: Do not override if you don't know what you are doing.
def to_lock
out = String.new("#{LockfileParser::PLUGIN}\n")
out << " remote: #{@uri}\n"
out << " type: #{@type}\n"
options_to_lock.each do |opt, value|
out << " #{opt}: #{value}\n"
end
out << " specs:\n"
end
def to_s
"plugin source for #{options[:type]} with uri #{uri}"
end
# Note: Do not override if you don't know what you are doing.
def include?(other)
other == self
end
def uri_hash
Digest::SHA1.hexdigest(uri)
end
# Note: Do not override if you don't know what you are doing.
def gem_install_dir
Bundler.install_path
end
# It is used to obtain the full_gem_path.
#
# spec's loaded_from path is expanded against this to get full_gem_path
#
# Note: Do not override if you don't know what you are doing.
def root
Bundler.root
end
end
end
end
end
| mit |
frisbeesport/frisbeesport.nl | vendor/bolt/bolt/src/Storage/Repository.php | 15299 | <?php
namespace Bolt\Storage;
use ArrayObject;
use Bolt\Events\HydrationEvent;
use Bolt\Events\StorageEvent;
use Bolt\Events\StorageEvents;
use Bolt\Storage\Entity\Builder;
use Bolt\Storage\Entity\Entity;
use Bolt\Storage\Field\Type\FieldTypeInterface;
use Bolt\Storage\Mapping\ClassMetadata;
use Bolt\Storage\Query\QueryInterface;
use Doctrine\Common\Persistence\ObjectRepository;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Query\QueryBuilder;
/**
* A default repository class that other repositories can inherit to provide more specific features.
*/
class Repository implements ObjectRepository
{
/** @var EntityManager */
public $em;
/** @var ClassMetadata */
public $_class;
/** @var string */
public $entityName;
/** @var Builder */
public $builder;
/**
* Initializes a new Repository.
*
* @param EntityManager $em the EntityManager to use
* @param ClassMetadata $classMetadata the class descriptor
*/
public function __construct($em, ClassMetadata $classMetadata)
{
$this->em = $em;
$this->_class = $classMetadata;
$this->entityName = $classMetadata->getName();
}
/**
* Creates a new empty entity and passes the supplied data to the constructor.
*
* @param array $params
* @param ClassMetadata $metadata
*
* @return Entity
*/
public function create($params = [], ClassMetadata $metadata = null)
{
$params = new ArrayObject($params);
$builder = $this->getEntityBuilder();
/** @var Entity $entity */
$entity = $builder->getEntity();
$preEventArgs = new HydrationEvent($params, ['entity' => $entity, 'repository' => $this]);
$this->event()->dispatch(StorageEvents::PRE_HYDRATE, $preEventArgs);
$builder->create($params, $entity);
$postEventArgs = new HydrationEvent($params, ['entity' => $entity, 'repository' => $this]);
$this->event()->dispatch(StorageEvents::POST_HYDRATE, $postEventArgs);
return $entity;
}
/**
* Creates a new QueryBuilder instance that is prepopulated for this entity name.
*
* @param string $alias
*
* @return QueryBuilder
*/
public function createQueryBuilder($alias = null)
{
if ($alias === null) {
$alias = $this->getAlias();
}
if (empty($alias)) {
$select = '*';
} else {
$select = $alias . '.*';
}
return $this->em->createQueryBuilder()
->select($select)
->from($this->getTableName(), $alias);
}
/**
* Return the number of rows used in this repository table.
*
* @return int
*/
public function count()
{
$qb = $this->getLoadQuery()
->select('COUNT(' . $this->getAlias() . '.id) as count')
->resetQueryParts(['groupBy', 'join'])
;
$result = $qb->execute()->fetchColumn(0);
return (int) $result;
}
/**
* {@inheritdoc}
*/
public function find($id)
{
$qb = $this->getLoadQuery();
$result = $qb->where($this->getAlias() . '.id = :id')
->setParameter('id', $id)
->execute()
->fetch();
if ($result) {
return $this->hydrate($result, $qb);
}
return false;
}
/**
* {@inheritdoc}
*/
public function findAll()
{
return $this->findBy([]);
}
/**
* {@inheritdoc}
*/
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
{
$qb = $this->findWithCriteria($criteria, $orderBy, $limit, $offset);
$result = $qb->execute()->fetchAll();
if ($result) {
return $this->hydrateAll($result, $qb);
}
return false;
}
/**
* Finds a single object by a set of criteria.
*
* @param array $criteria the criteria
* @param array $orderBy
*
* @return object|false the object
*/
public function findOneBy(array $criteria, array $orderBy = null)
{
$qb = $this->findWithCriteria($criteria, $orderBy);
$result = $qb->execute()->fetch();
if ($result) {
return $this->hydrate($result, $qb);
}
return false;
}
/**
* Internal method to build a basic select, returns QB object.
*
* @param array $criteria
* @param array $orderBy
* @param int $limit
* @param int $offset
*
* @return QueryBuilder
*/
protected function findWithCriteria(array $criteria, array $orderBy = null, $limit = null, $offset = null)
{
$qb = $this->getLoadQuery();
foreach ($criteria as $col => $val) {
if (is_array($val)) {
$qb->andWhere($this->getAlias() . ".$col IN(:$col)");
$qb->setParameter(":$col", $val, Connection::PARAM_INT_ARRAY);
} else {
$qb->andWhere($this->getAlias() . ".$col = :$col");
$qb->setParameter(":$col", $val);
}
}
if ($orderBy) {
$qb->orderBy($orderBy[0], $orderBy[1]);
}
if ($limit) {
$qb->setMaxResults($limit);
}
if ($offset) {
$qb->setFirstResult($offset);
}
return $qb;
}
/**
* Method to hydrate and return a QueryBuilder query.
*
* @param QueryBuilder $query
*
* @return array Entity
*/
public function findWith(QueryBuilder $query)
{
$this->load($query);
$result = $query->execute()->fetchAll();
if ($result) {
return $this->hydrateAll($result, $query);
}
return [];
}
/**
* Method to hydrate and return a single QueryBuilder result.
*
* @param QueryBuilder $query
*
* @return Entity|false
*/
public function findOneWith(QueryBuilder $query)
{
$this->load($query);
$result = $query->execute()->fetch();
if ($result) {
return $this->hydrate($result, $query);
}
return false;
}
/**
* Method to execute query from a Bolt QueryInterface object
* The query is passed to the pre-load handlers then built into a
* QueryBuilder instance that can be executed.
*
* @param QueryInterface $query [description]
*
* @return array Entity | false
*/
public function queryWith(QueryInterface $query)
{
$this->query($query);
$queryBuilder = $query->build();
return $this->findWith($queryBuilder);
}
/**
* Internal method to initialise and return a QueryBuilder instance.
* Note that the metadata fields will be passed the instance to modify where appropriate.
*
* @return QueryBuilder
*/
protected function getLoadQuery()
{
$qb = $this->createQueryBuilder();
$this->load($qb);
return $qb;
}
/**
* Internal method to run load method on each field for the managed entity.
*
* Takes a QueryBuilder instance as input
*
* @param QueryBuilder $query
*/
protected function load(QueryBuilder $query)
{
$metadata = $this->getClassMetadata();
foreach ($metadata->getFieldMappings() as $field) {
$fieldtype = $this->getFieldManager()->get($field['fieldtype'], $field);
if ($fieldtype instanceof FieldTypeInterface) {
$fieldtype->load($query, $metadata);
}
}
}
/**
* Internal method to run query method on each field for the managed entity.
*
* Takes a QueryInterface instance as input
*
* @param QueryInterface $query
*/
protected function query(QueryInterface $query)
{
$metadata = $this->getClassMetadata();
foreach ($metadata->getFieldMappings() as $field) {
$fieldtype = $this->getFieldManager()->get($field['fieldtype'], $field);
if ($fieldtype instanceof FieldTypeInterface) {
$fieldtype->query($query, $metadata);
}
}
}
/**
* Internal method to run persist method on each field for the managed entity.
*
* Takes a QuerySet instance as input
*
* @param QuerySet $queries
* @param Entity $entity
* @param array $exclusions
*/
protected function persist(QuerySet $queries, $entity, $exclusions = [])
{
$metadata = $this->getClassMetadata();
foreach ($metadata->getFieldMappings() as $field) {
$fieldName = $field['fieldname'];
if (in_array($fieldName, $exclusions)) {
continue;
}
// Don't add field to the persistence query if it is not an entity
// property, and on UPDATE only
if (!isset($entity->$fieldName) && $entity->getId() !== null) {
continue;
}
$field = $this->getFieldManager()->get($field['fieldtype'], $field);
if ($field instanceof FieldTypeInterface) {
$field->persist($queries, $entity);
}
}
}
/**
* Deletes a single object.
*
* @param object $entity the entity to delete
*
* @return bool
*/
public function delete($entity)
{
$event = new StorageEvent($entity);
$this->event()->dispatch(StorageEvents::PRE_DELETE, $event);
$qb = $this->em->createQueryBuilder()
->delete($this->getTableName())
->where('id = :id')
->setParameter('id', $entity->getId());
$response = $qb->execute();
$event = new StorageEvent($entity);
$this->event()->dispatch(StorageEvents::POST_DELETE, $event);
return $response;
}
/**
* Saves a single object.
*
* @param object $entity the entity to save
* @param bool $silent Suppress events
*
* @return bool
*/
public function save($entity, $silent = null)
{
try {
if ($existing = $entity->getId()) {
$creating = false;
} else {
$creating = true;
}
} catch (\Exception $e) {
$creating = $existing = false;
}
if ($silent === null) {
$event = new StorageEvent($entity, ['create' => $creating]);
$this->event()->dispatch(StorageEvents::PRE_SAVE, $event);
}
if ($existing) {
$response = $this->update($entity);
} else {
$response = $this->insert($entity);
}
if ($silent === null) {
$this->event()->dispatch(StorageEvents::POST_SAVE, $event);
}
return $response;
}
/**
* Saves a new object into the database.
*
* @param object $entity the entity to insert
*
* @return bool
*/
public function insert($entity)
{
$querySet = new QuerySet();
$qb = $this->em->createQueryBuilder();
$qb->insert($this->getTableName());
$querySet->append($qb);
$this->persist($querySet, $entity, ['id']);
$result = $querySet->execute();
// Try and set the entity id using the response from the insert
try {
$entity->setId($querySet->getInsertId());
} catch (\Exception $e) {
}
return $result;
}
/**
* Updates an object into the database.
*
* @param object $entity the entity to update
* @param string[] $exclusions Ignore updates to these fields
*
* @return bool
*/
public function update($entity, $exclusions = [])
{
$querySet = new QuerySet();
$querySet->setParentId($entity->getId());
$qb = $this->em->createQueryBuilder();
$qb->update($this->getTableName())
->where('id = :id')
->setParameter('id', $entity->getId());
$querySet->append($qb);
$this->persist($querySet, $entity, $exclusions);
return $querySet->execute();
}
/**
* Internal method to hydrate an Entity Object from fetched data.
*
* @param array $data
* @param QueryBuilder $qb
*
* @return mixed
*/
protected function hydrate(array $data, QueryBuilder $qb)
{
$entity = $this->getEntityBuilder()->getEntity();
$data = new ArrayObject($data);
$preEventArgs = new HydrationEvent($data, ['entity' => $entity, 'repository' => $this]);
$this->event()->dispatch(StorageEvents::PRE_HYDRATE, $preEventArgs);
$this->getEntityBuilder()->createFromDatabaseValues($data, $entity);
$postEventArgs = new HydrationEvent($entity, ['entity' => $entity, 'data' => $data, 'repository' => $this]);
$this->event()->dispatch(StorageEvents::POST_HYDRATE, $postEventArgs);
return $entity;
}
/**
* Internal method to hydrate an array of Entity Objects from fetched data.
*
* @param array $data
* @param QueryBuilder $qb
*
* @return mixed
*/
protected function hydrateAll(array $data, QueryBuilder $qb)
{
$rows = [];
foreach ($data as $row) {
$rows[] = $this->hydrate($row, $qb);
}
return $rows;
}
/**
* Internal method to refresh (re-hydrate an entity) using
* the field setters.
*
* @param $entity
*/
protected function refresh($entity)
{
$this->getEntityBuilder()->refresh($entity);
}
/**
* Fetches FieldManager instance from the EntityManager.
*
* @return FieldManager
*/
public function getFieldManager()
{
return $this->em->getFieldManager();
}
/**
* @return Builder $builder
*/
public function getEntityBuilder()
{
$builder = $this->em->getEntityBuilder();
$builder->setClass($this->getEntityName());
$builder->setClassMetadata($this->getClassMetadata());
return $builder;
}
/**
* @return string
*/
public function getEntityName()
{
return $this->entityName;
}
/**
* @return string
*/
public function getClassName()
{
return $this->getEntityName();
}
/**
* @return string
*/
public function getTableName()
{
return $this->getClassMetadata()->getTableName();
}
/**
* @return string
*/
public function getAlias()
{
return $this->getClassMetadata()->getAliasName();
}
/**
* @return EntityManager
*/
public function getEntityManager()
{
return $this->em;
}
/**
* Getter for class metadata.
*
* @return ClassMetadata
*/
public function getClassMetadata()
{
return $this->_class;
}
/**
* Shortcut method to fetch the Event Dispatcher.
*
* @return \Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
public function event()
{
return $this->getEntityManager()->getEventManager();
}
}
| mit |
skycolor/study | frontWeb/three/official/examples/js/shaders/VerticalTiltShiftShader.js | 1637 | /**
* @author alteredq / http://alteredqualia.com/
*
* Simple fake tilt-shift effect, modulating two pass Gaussian blur (see above) by vertical position
*
* - 9 samples per pass
* - standard deviation 2.7
* - "h" and "v" parameters should be set to "1 / width" and "1 / height"
* - "r" parameter control where "focused" horizontal line lies
*/
THREE.VerticalTiltShiftShader = {
uniforms: {
"tDiffuse": { value: null },
"v": { value: 1.0 / 512.0 },
"r": { value: 0.35 }
},
vertexShader: [
"varying vec2 vUv;",
"void main() {",
"vUv = uv;",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}"
].join( "\n" ),
fragmentShader: [
"uniform sampler2D tDiffuse;",
"uniform float v;",
"uniform float r;",
"varying vec2 vUv;",
"void main() {",
"vec4 sum = vec4( 0.0 );",
"float vv = v * abs( r - vUv.y );",
"sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * vv ) ) * 0.051;",
"sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * vv ) ) * 0.0918;",
"sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * vv ) ) * 0.12245;",
"sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * vv ) ) * 0.1531;",
"sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;",
"sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * vv ) ) * 0.1531;",
"sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * vv ) ) * 0.12245;",
"sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * vv ) ) * 0.0918;",
"sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * vv ) ) * 0.051;",
"gl_FragColor = sum;",
"}"
].join( "\n" )
};
| mit |
davehorton/drachtio-server | deps/boost_1_77_0/libs/regex/src/posix_api.cpp | 7339 | /*
*
* Copyright (c) 1998-2002
* John Maddock
*
* 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)
*
*/
/*
* LOCATION: see http://www.boost.org for most recent version.
* FILE: posix_api.cpp
* VERSION: see <boost/version.hpp>
* DESCRIPTION: Implements the Posix API wrappers.
*/
#define BOOST_REGEX_SOURCE
#include <boost/config.hpp>
#include <boost/regex.hpp>
#include <boost/cregex.hpp>
#include <cstdio>
#if defined(BOOST_NO_STDC_NAMESPACE)
namespace std{
using ::sprintf;
using ::strcpy;
using ::strcmp;
}
#endif
namespace boost{
namespace{
unsigned int magic_value = 25631;
const char* names[] = {
"REG_NOERROR",
"REG_NOMATCH",
"REG_BADPAT",
"REG_ECOLLATE",
"REG_ECTYPE",
"REG_EESCAPE",
"REG_ESUBREG",
"REG_EBRACK",
"REG_EPAREN",
"REG_EBRACE",
"REG_BADBR",
"REG_ERANGE",
"REG_ESPACE",
"REG_BADRPT",
"REG_EEND",
"REG_ESIZE",
"REG_ERPAREN",
"REG_EMPTY",
"REG_ECOMPLEXITY",
"REG_ESTACK",
"REG_E_PERL",
"REG_E_UNKNOWN",
};
} // namespace
typedef boost::basic_regex<char, c_regex_traits<char> > c_regex_type;
#ifdef BOOST_MSVC
# pragma warning(push)
#pragma warning(disable:26812)
#endif
BOOST_REGEX_DECL int BOOST_REGEX_CCALL regcompA(regex_tA* expression, const char* ptr, int f)
{
#ifndef BOOST_NO_EXCEPTIONS
try{
#endif
expression->guts = new c_regex_type();
#ifndef BOOST_NO_EXCEPTIONS
} catch(...)
{
expression->guts = 0;
return REG_ESPACE;
}
#else
if(0 == expression->guts)
return REG_E_MEMORY;
#endif
// set default flags:
boost::uint_fast32_t flags = (f & REG_PERLEX) ? 0 : ((f & REG_EXTENDED) ? regex::extended : regex::basic);
expression->eflags = (f & REG_NEWLINE) ? match_not_dot_newline : match_default;
// and translate those that are actually set:
if(f & REG_NOCOLLATE)
{
flags |= regex::nocollate;
#ifndef BOOST_REGEX_V3
flags &= ~regex::collate;
#endif
}
if(f & REG_NOSUB)
{
//expression->eflags |= match_any;
flags |= regex::nosubs;
}
if(f & REG_NOSPEC)
flags |= regex::literal;
if(f & REG_ICASE)
flags |= regex::icase;
if(f & REG_ESCAPE_IN_LISTS)
flags &= ~regex::no_escape_in_lists;
if(f & REG_NEWLINE_ALT)
flags |= regex::newline_alt;
const char* p2;
if(f & REG_PEND)
p2 = expression->re_endp;
else p2 = ptr + std::strlen(ptr);
int result;
#ifndef BOOST_NO_EXCEPTIONS
try{
#endif
expression->re_magic = magic_value;
static_cast<c_regex_type*>(expression->guts)->set_expression(ptr, p2, flags);
expression->re_nsub = static_cast<c_regex_type*>(expression->guts)->mark_count();
result = static_cast<c_regex_type*>(expression->guts)->error_code();
#ifndef BOOST_NO_EXCEPTIONS
}
catch(const boost::regex_error& be)
{
result = be.code();
}
catch(...)
{
result = REG_E_UNKNOWN;
}
#endif
if(result)
regfreeA(expression);
return result;
}
#ifdef BOOST_MSVC
# pragma warning(pop)
#endif
BOOST_REGEX_DECL regsize_t BOOST_REGEX_CCALL regerrorA(int code, const regex_tA* e, char* buf, regsize_t buf_size)
{
std::size_t result = 0;
if(code & REG_ITOA)
{
code &= ~REG_ITOA;
if(code <= (int)REG_E_UNKNOWN)
{
result = std::strlen(names[code]) + 1;
if(buf_size >= result)
BOOST_REGEX_DETAIL_NS::strcpy_s(buf, buf_size, names[code]);
return result;
}
return result;
}
if(code == REG_ATOI)
{
char localbuf[5];
if(e == 0)
return 0;
for(int i = 0; i <= (int)REG_E_UNKNOWN; ++i)
{
if(std::strcmp(e->re_endp, names[i]) == 0)
{
//
// We're converting an integer i to a string, and since i <= REG_E_UNKNOWN
// a five character string is *always* large enough:
//
#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400) && !defined(_WIN32_WCE) && !defined(UNDER_CE)
int r = (::sprintf_s)(localbuf, 5, "%d", i);
#else
int r = (std::sprintf)(localbuf, "%d", i);
#endif
if(r < 0)
return 0; // sprintf failed
if(std::strlen(localbuf) < buf_size)
BOOST_REGEX_DETAIL_NS::strcpy_s(buf, buf_size, localbuf);
return std::strlen(localbuf) + 1;
}
}
#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400) && !defined(_WIN32_WCE) && !defined(UNDER_CE)
int r = (::sprintf_s)(localbuf, 5, "%d", 0);
#else
int r = (std::sprintf)(localbuf, "%d", 0);
#endif
if(r < 0)
return 0; // sprintf failed
if(std::strlen(localbuf) < buf_size)
BOOST_REGEX_DETAIL_NS::strcpy_s(buf, buf_size, localbuf);
return std::strlen(localbuf) + 1;
}
if(code <= (int)REG_E_UNKNOWN)
{
std::string p;
if((e) && (e->re_magic == magic_value))
p = static_cast<c_regex_type*>(e->guts)->get_traits().error_string(static_cast< ::boost::regex_constants::error_type>(code));
else
{
p = BOOST_REGEX_DETAIL_NS::get_default_error_string(static_cast< ::boost::regex_constants::error_type>(code));
}
std::size_t len = p.size();
if(len < buf_size)
{
BOOST_REGEX_DETAIL_NS::strcpy_s(buf, buf_size, p.c_str());
}
return len + 1;
}
if(buf_size)
*buf = 0;
return 0;
}
BOOST_REGEX_DECL int BOOST_REGEX_CCALL regexecA(const regex_tA* expression, const char* buf, regsize_t n, regmatch_t* array, int eflags)
{
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable:4267)
#endif
bool result = false;
match_flag_type flags = match_default | expression->eflags;
const char* end;
const char* start;
cmatch m;
if(eflags & REG_NOTBOL)
flags |= match_not_bol;
if(eflags & REG_NOTEOL)
flags |= match_not_eol;
if(eflags & REG_STARTEND)
{
start = buf + array[0].rm_so;
end = buf + array[0].rm_eo;
}
else
{
start = buf;
end = buf + std::strlen(buf);
}
#ifndef BOOST_NO_EXCEPTIONS
try{
#endif
if(expression->re_magic == magic_value)
{
result = regex_search(start, end, m, *static_cast<c_regex_type*>(expression->guts), flags);
}
else
return result;
#ifndef BOOST_NO_EXCEPTIONS
} catch(...)
{
return REG_E_UNKNOWN;
}
#endif
if(result)
{
// extract what matched:
std::size_t i;
for(i = 0; (i < n) && (i < expression->re_nsub + 1); ++i)
{
array[i].rm_so = m[i].matched ? (m[i].first - buf) : -1;
array[i].rm_eo = m[i].matched ? (m[i].second - buf) : -1;
}
// and set anything else to -1:
for(i = expression->re_nsub + 1; i < n; ++i)
{
array[i].rm_so = -1;
array[i].rm_eo = -1;
}
return 0;
}
return REG_NOMATCH;
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
}
BOOST_REGEX_DECL void BOOST_REGEX_CCALL regfreeA(regex_tA* expression)
{
if(expression->re_magic == magic_value)
{
delete static_cast<c_regex_type*>(expression->guts);
}
expression->re_magic = 0;
}
} // namespace boost
| mit |
GMarsden-EDR/Jumph | src/Jumph/Bundle/ClientBundle/EventListener/ClientMenuListener.php | 792 | <?php
/**
* This file is part of the Jumph package.
*
* (c) Peter Nijssen
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Jumph\Bundle\ClientBundle\EventListener;
use Jumph\Bundle\AppBundle\Event\BuildMenuEvent;
class ClientMenuListener
{
/**
* @param BuildMenuEvent $event
*/
public function onMenuClient(BuildMenuEvent $event)
{
$menu = $event->getMenu();
$menu->addChild(
'Clients',
array(
'route' => 'jumph_client_company_overview',
'extras' => array(
'icon' => 'fa-building fa-fw',
'weight' => 100
)
)
);
}
}
| mit |
macressler/haml | lib/haml/helpers.rb | 22945 | module Haml
# This module contains various helpful methods to make it easier to do various tasks.
# {Haml::Helpers} is automatically included in the context
# that a Haml template is parsed in, so all these methods are at your
# disposal from within the template.
module Helpers
# An object that raises an error when \{#to\_s} is called.
# It's used to raise an error when the return value of a helper is used
# when it shouldn't be.
class ErrorReturn
def initialize(method)
@message = <<MESSAGE
#{method} outputs directly to the Haml template.
Disregard its return value and use the - operator,
or use capture_haml to get the value as a String.
MESSAGE
end
# Raises an error.
#
# @raise [Haml::Error] The error
def to_s
raise Haml::Error.new(@message)
rescue Haml::Error => e
e.backtrace.shift
# If the ErrorReturn is used directly in the template,
# we don't want Haml's stuff to get into the backtrace,
# so we get rid of the format_script line.
#
# We also have to subtract one from the Haml line number
# since the value is passed to format_script the line after
# it's actually used.
if e.backtrace.first =~ /^\(eval\):\d+:in `format_script/
e.backtrace.shift
e.backtrace.first.gsub!(/^\(haml\):(\d+)/) {|s| "(haml):#{$1.to_i - 1}"}
end
raise e
end
# @return [String] A human-readable string representation
def inspect
"Haml::Helpers::ErrorReturn(#{@message.inspect})"
end
end
self.extend self
@@action_view_defined = false
# @return [Boolean] Whether or not ActionView is loaded
def self.action_view?
@@action_view_defined
end
# Note: this does **not** need to be called when using Haml helpers
# normally in Rails.
#
# Initializes the current object as though it were in the same context
# as a normal ActionView instance using Haml.
# This is useful if you want to use the helpers in a context
# other than the normal setup with ActionView.
# For example:
#
# context = Object.new
# class << context
# include Haml::Helpers
# end
# context.init_haml_helpers
# context.haml_tag :p, "Stuff"
#
def init_haml_helpers
@haml_buffer = Haml::Buffer.new(haml_buffer, Options.new.for_buffer)
nil
end
# Runs a block of code in a non-Haml context
# (i.e. \{#is\_haml?} will return false).
#
# This is mainly useful for rendering sub-templates such as partials in a non-Haml language,
# particularly where helpers may behave differently when run from Haml.
#
# Note that this is automatically applied to Rails partials.
#
# @yield A block which won't register as Haml
def non_haml
was_active = @haml_buffer.active?
@haml_buffer.active = false
yield
ensure
@haml_buffer.active = was_active
end
# Uses \{#preserve} to convert any newlines inside whitespace-sensitive tags
# into the HTML entities for endlines.
#
# @param tags [Array<String>] Tags that should have newlines escaped
#
# @overload find_and_preserve(input, tags = haml_buffer.options[:preserve])
# Escapes newlines within a string.
#
# @param input [String] The string within which to escape newlines
# @overload find_and_preserve(tags = haml_buffer.options[:preserve])
# Escapes newlines within a block of Haml code.
#
# @yield The block within which to escape newlines
def find_and_preserve(input = nil, tags = haml_buffer.options[:preserve], &block)
return find_and_preserve(capture_haml(&block), input || tags) if block
tags = tags.each_with_object('') do |t, s|
s << '|' unless s.empty?
s << Regexp.escape(t)
end
re = /<(#{tags})([^>]*)>(.*?)(<\/\1>)/im
input.to_s.gsub(re) do |s|
s =~ re # Can't rely on $1, etc. existing since Rails' SafeBuffer#gsub is incompatible
"<#{$1}#{$2}>#{preserve($3)}</#{$1}>"
end
end
# Takes any string, finds all the newlines, and converts them to
# HTML entities so they'll render correctly in
# whitespace-sensitive tags without screwing up the indentation.
#
# @overload preserve(input)
# Escapes newlines within a string.
#
# @param input [String] The string within which to escape all newlines
# @overload preserve
# Escapes newlines within a block of Haml code.
#
# @yield The block within which to escape newlines
def preserve(input = nil, &block)
return preserve(capture_haml(&block)) if block
s = input.to_s.chomp("\n")
s.gsub!(/\n/, '
')
s.delete!("\r")
s
end
alias_method :flatten, :preserve
# Takes an `Enumerable` object and a block
# and iterates over the enum,
# yielding each element to a Haml block
# and putting the result into `<li>` elements.
# This creates a list of the results of the block.
# For example:
#
# = list_of([['hello'], ['yall']]) do |i|
# = i[0]
#
# Produces:
#
# <li>hello</li>
# <li>yall</li>
#
# And:
#
# = list_of({:title => 'All the stuff', :description => 'A book about all the stuff.'}) do |key, val|
# %h3= key.humanize
# %p= val
#
# Produces:
#
# <li>
# <h3>Title</h3>
# <p>All the stuff</p>
# </li>
# <li>
# <h3>Description</h3>
# <p>A book about all the stuff.</p>
# </li>
#
# While:
#
# = list_of(["Home", "About", "Contact", "FAQ"], {class: "nav", role: "nav"}) do |item|
# %a{ href="#" }= item
#
# Produces:
#
# <li class='nav' role='nav'>
# <a href='#'>Home</a>
# </li>
# <li class='nav' role='nav'>
# <a href='#'>About</a>
# </li>
# <li class='nav' role='nav'>
# <a href='#'>Contact</a>
# </li>
# <li class='nav' role='nav'>
# <a href='#'>FAQ</a>
# </li>
#
# `[[class", "nav"], [role", "nav"]]` could have been used instead of `{class: "nav", role: "nav"}` (or any enumerable collection where each pair of items responds to #to_s)
#
# @param enum [Enumerable] The list of objects to iterate over
# @param [Enumerable<#to_s,#to_s>] opts Each key/value pair will become an attribute pair for each list item element.
# @yield [item] A block which contains Haml code that goes within list items
# @yieldparam item An element of `enum`
def list_of(enum, opts={}, &block)
opts_attributes = opts.each_with_object('') {|(k, v), s| s << " #{k}='#{v}'"}
enum.each_with_object('') do |i, ret|
result = capture_haml(i, &block)
if result.count("\n") > 1
result.gsub!("\n", "\n ")
result = "\n #{result.strip!}\n"
else
result.strip!
end
ret << "\n" unless ret.empty?
ret << %Q!<li#{opts_attributes}>#{result}</li>!
end
end
# Returns a hash containing default assignments for the `xmlns`, `lang`, and `xml:lang`
# attributes of the `html` HTML element.
# For example,
#
# %html{html_attrs}
#
# becomes
#
# <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en-US' lang='en-US'>
#
# @param lang [String] The value of `xml:lang` and `lang`
# @return [{#to_s => String}] The attribute hash
def html_attrs(lang = 'en-US')
if haml_buffer.options[:format] == :xhtml
{:xmlns => "http://www.w3.org/1999/xhtml", 'xml:lang' => lang, :lang => lang}
else
{:lang => lang}
end
end
# Increments the number of tabs the buffer automatically adds
# to the lines of the template.
# For example:
#
# %h1 foo
# - tab_up
# %p bar
# - tab_down
# %strong baz
#
# Produces:
#
# <h1>foo</h1>
# <p>bar</p>
# <strong>baz</strong>
#
# @param i [Fixnum] The number of tabs by which to increase the indentation
# @see #tab_down
def tab_up(i = 1)
haml_buffer.tabulation += i
end
# Decrements the number of tabs the buffer automatically adds
# to the lines of the template.
#
# @param i [Fixnum] The number of tabs by which to decrease the indentation
# @see #tab_up
def tab_down(i = 1)
haml_buffer.tabulation -= i
end
# Sets the number of tabs the buffer automatically adds
# to the lines of the template,
# but only for the duration of the block.
# For example:
#
# %h1 foo
# - with_tabs(2) do
# %p bar
# %strong baz
#
# Produces:
#
# <h1>foo</h1>
# <p>bar</p>
# <strong>baz</strong>
#
#
# @param i [Fixnum] The number of tabs to use
# @yield A block in which the indentation will be `i` spaces
def with_tabs(i)
old_tabs = haml_buffer.tabulation
haml_buffer.tabulation = i
yield
ensure
haml_buffer.tabulation = old_tabs
end
# Surrounds a block of Haml code with strings,
# with no whitespace in between.
# For example:
#
# = surround '(', ')' do
# %a{:href => "food"} chicken
#
# Produces:
#
# (<a href='food'>chicken</a>)
#
# and
#
# = surround '*' do
# %strong angry
#
# Produces:
#
# *<strong>angry</strong>*
#
# @param front [String] The string to add before the Haml
# @param back [String] The string to add after the Haml
# @yield A block of Haml to surround
def surround(front, back = front, &block)
output = capture_haml(&block)
"#{front}#{output.chomp}#{back}\n"
end
# Prepends a string to the beginning of a Haml block,
# with no whitespace between.
# For example:
#
# = precede '*' do
# %span.small Not really
#
# Produces:
#
# *<span class='small'>Not really</span>
#
# @param str [String] The string to add before the Haml
# @yield A block of Haml to prepend to
def precede(str, &block)
"#{str}#{capture_haml(&block).chomp}\n"
end
# Appends a string to the end of a Haml block,
# with no whitespace between.
# For example:
#
# click
# = succeed '.' do
# %a{:href=>"thing"} here
#
# Produces:
#
# click
# <a href='thing'>here</a>.
#
# @param str [String] The string to add after the Haml
# @yield A block of Haml to append to
def succeed(str, &block)
"#{capture_haml(&block).chomp}#{str}\n"
end
# Captures the result of a block of Haml code,
# gets rid of the excess indentation,
# and returns it as a string.
# For example, after the following,
#
# .foo
# - foo = capture_haml(13) do |a|
# %p= a
#
# the local variable `foo` would be assigned to `"<p>13</p>\n"`.
#
# @param args [Array] Arguments to pass into the block
# @yield [args] A block of Haml code that will be converted to a string
# @yieldparam args [Array] `args`
def capture_haml(*args, &block)
buffer = eval('if defined? _hamlout then _hamlout else nil end', block.binding) || haml_buffer
with_haml_buffer(buffer) do
position = haml_buffer.buffer.length
haml_buffer.capture_position = position
value = block.call(*args)
captured = haml_buffer.buffer.slice!(position..-1)
if captured == '' and value != haml_buffer.buffer
captured = (value.is_a?(String) ? value : nil)
end
return nil if captured.nil?
return (haml_buffer.options[:ugly] ? captured : prettify(captured))
end
ensure
haml_buffer.capture_position = nil
end
# Outputs text directly to the Haml buffer, with the proper indentation.
#
# @param text [#to_s] The text to output
def haml_concat(text = "")
haml_internal_concat text
ErrorReturn.new("haml_concat")
end
# Internal method to write directly to the buffer with control of
# whether the first line should be indented, and if there should be a
# final newline.
#
# Lines added will have the proper indentation. This can be controlled
# for the first line.
#
# Used by #haml_concat and #haml_tag.
#
# @param text [#to_s] The text to output
# @param newline [Boolean] Whether to add a newline after the text
# @param indent [Boolean] Whether to add indentation to the first line
def haml_internal_concat(text = "", newline = true, indent = true)
if haml_buffer.options[:ugly] || haml_buffer.tabulation == 0
haml_buffer.buffer << "#{text}#{"\n" if newline}"
else
haml_buffer.buffer << %[#{haml_indent if indent}#{text.to_s.gsub("\n", "\n#{haml_indent}")}#{"\n" if newline}]
end
end
private :haml_internal_concat
# Allows writing raw content. `haml_internal_concat_raw` isn't
# effected by XSS mods. Used by #haml_tag to write the actual tags.
alias :haml_internal_concat_raw :haml_internal_concat
# @return [String] The indentation string for the current line
def haml_indent
' ' * haml_buffer.tabulation
end
# Creates an HTML tag with the given name and optionally text and attributes.
# Can take a block that will run between the opening and closing tags.
# If the block is a Haml block or outputs text using \{#haml\_concat},
# the text will be properly indented.
#
# `name` can be a string using the standard Haml class/id shorthand
# (e.g. "span#foo.bar", "#foo").
# Just like standard Haml tags, these class and id values
# will be merged with manually-specified attributes.
#
# `flags` is a list of symbol flags
# like those that can be put at the end of a Haml tag
# (`:/`, `:<`, and `:>`).
# Currently, only `:/` and `:<` are supported.
#
# `haml_tag` outputs directly to the buffer;
# its return value should not be used.
# If you need to get the results as a string,
# use \{#capture\_haml\}.
#
# For example,
#
# haml_tag :table do
# haml_tag :tr do
# haml_tag 'td.cell' do
# haml_tag :strong, "strong!"
# haml_concat "data"
# end
# haml_tag :td do
# haml_concat "more_data"
# end
# end
# end
#
# outputs
#
# <table>
# <tr>
# <td class='cell'>
# <strong>
# strong!
# </strong>
# data
# </td>
# <td>
# more_data
# </td>
# </tr>
# </table>
#
# @param name [#to_s] The name of the tag
#
# @overload haml_tag(name, *rest, attributes = {})
# @yield The block of Haml code within the tag
# @overload haml_tag(name, text, *flags, attributes = {})
# @param text [#to_s] The text within the tag
# @param flags [Array<Symbol>] Haml end-of-tag flags
def haml_tag(name, *rest, &block)
ret = ErrorReturn.new("haml_tag")
text = rest.shift.to_s unless [Symbol, Hash, NilClass].any? {|t| rest.first.is_a? t}
flags = []
flags << rest.shift while rest.first.is_a? Symbol
attrs = (rest.shift || {})
attrs.keys.each {|key| attrs[key.to_s] = attrs.delete(key)} unless attrs.empty?
name, attrs = merge_name_and_attributes(name.to_s, attrs)
attributes = Haml::Compiler.build_attributes(haml_buffer.html?,
haml_buffer.options[:attr_wrapper],
haml_buffer.options[:escape_attrs],
haml_buffer.options[:hyphenate_data_attrs],
attrs)
if text.nil? && block.nil? && (haml_buffer.options[:autoclose].include?(name) || flags.include?(:/))
haml_internal_concat_raw "<#{name}#{attributes}#{' /' if haml_buffer.options[:format] == :xhtml}>"
return ret
end
if flags.include?(:/)
raise Error.new(Error.message(:self_closing_content)) if text
raise Error.new(Error.message(:illegal_nesting_self_closing)) if block
end
tag = "<#{name}#{attributes}>"
end_tag = "</#{name}>"
if block.nil?
text = text.to_s
if text.include?("\n")
haml_internal_concat_raw tag
tab_up
haml_internal_concat text
tab_down
haml_internal_concat_raw end_tag
else
haml_internal_concat_raw tag, false
haml_internal_concat text, false, false
haml_internal_concat_raw end_tag, true, false
end
return ret
end
if text
raise Error.new(Error.message(:illegal_nesting_line, name))
end
if flags.include?(:<)
haml_internal_concat_raw tag, false
haml_internal_concat "#{capture_haml(&block).strip}", false, false
haml_internal_concat_raw end_tag, true, false
return ret
end
haml_internal_concat_raw tag
tab_up
block.call
tab_down
haml_internal_concat_raw end_tag
ret
end
# Conditionally wrap a block in an element. If `condition` is `true` then
# this method renders the tag described by the arguments in `tag` (using
# \{#haml_tag}) with the given block inside, otherwise it just renders the block.
#
# For example,
#
# - haml_tag_if important, '.important' do
# %p
# A (possibly) important paragraph.
#
# will produce
#
# <div class='important'>
# <p>
# A (possibly) important paragraph.
# </p>
# </div>
#
# if `important` is truthy, and just
#
# <p>
# A (possibly) important paragraph.
# </p>
#
# otherwise.
#
# Like \{#haml_tag}, `haml_tag_if` outputs directly to the buffer and its
# return value should not be used. Use \{#capture_haml} if you need to use
# its results as a string.
#
# @param condition The condition to test to determine whether to render
# the enclosing tag
# @param tag Definition of the enclosing tag. See \{#haml_tag} for details
# (specifically the form that takes a block)
def haml_tag_if(condition, *tag)
if condition
haml_tag(*tag){ yield }
else
yield
end
ErrorReturn.new("haml_tag_if")
end
# Characters that need to be escaped to HTML entities from user input
HTML_ESCAPE = { '&' => '&', '<' => '<', '>' => '>', '"' => '"', "'" => ''' }
HTML_ESCAPE_REGEX = /[\"><&]/
# Returns a copy of `text` with ampersands, angle brackets and quotes
# escaped into HTML entities.
#
# Note that if ActionView is loaded and XSS protection is enabled
# (as is the default for Rails 3.0+, and optional for version 2.3.5+),
# this won't escape text declared as "safe".
#
# @param text [String] The string to sanitize
# @return [String] The sanitized string
def html_escape(text)
text = text.to_s
text.gsub(HTML_ESCAPE_REGEX, HTML_ESCAPE)
end
HTML_ESCAPE_ONCE_REGEX = /[\"><]|&(?!(?:[a-zA-Z]+|#(?:\d+|[xX][0-9a-fA-F]+));)/
# Escapes HTML entities in `text`, but without escaping an ampersand
# that is already part of an escaped entity.
#
# @param text [String] The string to sanitize
# @return [String] The sanitized string
def escape_once(text)
text = text.to_s
text.gsub(HTML_ESCAPE_ONCE_REGEX, HTML_ESCAPE)
end
# Returns whether or not the current template is a Haml template.
#
# This function, unlike other {Haml::Helpers} functions,
# also works in other `ActionView` templates,
# where it will always return false.
#
# @return [Boolean] Whether or not the current template is a Haml template
def is_haml?
!@haml_buffer.nil? && @haml_buffer.active?
end
# Returns whether or not `block` is defined directly in a Haml template.
#
# @param block [Proc] A Ruby block
# @return [Boolean] Whether or not `block` is defined directly in a Haml template
def block_is_haml?(block)
eval('!!defined?(_hamlout)', block.binding)
end
private
# Parses the tag name used for \{#haml\_tag}
# and merges it with the Ruby attributes hash.
def merge_name_and_attributes(name, attributes_hash = {})
# skip merging if no ids or classes found in name
return name, attributes_hash unless name =~ /^(.+?)?([\.#].*)$/
return $1 || "div", Buffer.merge_attrs(
Haml::Parser.parse_class_and_id($2), attributes_hash)
end
# Runs a block of code with the given buffer as the currently active buffer.
#
# @param buffer [Haml::Buffer] The Haml buffer to use temporarily
# @yield A block in which the given buffer should be used
def with_haml_buffer(buffer)
@haml_buffer, old_buffer = buffer, @haml_buffer
old_buffer.active, old_was_active = false, old_buffer.active? if old_buffer
@haml_buffer.active, was_active = true, @haml_buffer.active?
yield
ensure
@haml_buffer.active = was_active
old_buffer.active = old_was_active if old_buffer
@haml_buffer = old_buffer
end
# The current {Haml::Buffer} object.
#
# @return [Haml::Buffer]
def haml_buffer
@haml_buffer if defined? @haml_buffer
end
# Gives a proc the same local `_hamlout` and `_erbout` variables
# that the current template has.
#
# @param proc [#call] The proc to bind
# @return [Proc] A new proc with the new variables bound
def haml_bind_proc(&proc)
_hamlout = haml_buffer
#double assignment is to avoid warnings
_erbout = _erbout = _hamlout.buffer
proc { |*args| proc.call(*args) }
end
def prettify(text)
text = text.split(/^/)
text.delete('')
min_tabs = nil
text.each do |line|
tabs = line.index(/[^ ]/) || line.length
min_tabs ||= tabs
min_tabs = min_tabs > tabs ? tabs : min_tabs
end
text.each_with_object('') do |line, str|
str << line.slice(min_tabs, line.length)
end
end
end
end
# @private
class Object
# Haml overrides various `ActionView` helpers,
# which call an \{#is\_haml?} method
# to determine whether or not the current context object
# is a proper Haml context.
# Because `ActionView` helpers may be included in non-`ActionView::Base` classes,
# it's a good idea to define \{#is\_haml?} for all objects.
def is_haml?
false
end
end
| mit |
NikRimington/Umbraco-CMS | src/Umbraco.Core/Services/IRedirectUrlService.cs | 3605 | using System;
using System.Collections.Generic;
using Umbraco.Core.Models;
namespace Umbraco.Core.Services
{
/// <summary>
///
/// </summary>
public interface IRedirectUrlService : IService
{
/// <summary>
/// Registers a redirect url.
/// </summary>
/// <param name="url">The Umbraco url route.</param>
/// <param name="contentKey">The content unique key.</param>
/// <param name="culture">The culture.</param>
/// <remarks>Is a proper Umbraco route eg /path/to/foo or 123/path/tofoo.</remarks>
void Register(string url, Guid contentKey, string culture = null);
/// <summary>
/// Deletes all redirect urls for a given content.
/// </summary>
/// <param name="contentKey">The content unique key.</param>
void DeleteContentRedirectUrls(Guid contentKey);
/// <summary>
/// Deletes a redirect url.
/// </summary>
/// <param name="redirectUrl">The redirect url to delete.</param>
void Delete(IRedirectUrl redirectUrl);
/// <summary>
/// Deletes a redirect url.
/// </summary>
/// <param name="id">The redirect url identifier.</param>
void Delete(Guid id);
/// <summary>
/// Deletes all redirect urls.
/// </summary>
void DeleteAll();
/// <summary>
/// Gets the most recent redirect urls corresponding to an Umbraco redirect url route.
/// </summary>
/// <param name="url">The Umbraco redirect url route.</param>
/// <returns>The most recent redirect urls corresponding to the route.</returns>
IRedirectUrl GetMostRecentRedirectUrl(string url);
/// <summary>
/// Gets all redirect urls for a content item.
/// </summary>
/// <param name="contentKey">The content unique key.</param>
/// <returns>All redirect urls for the content item.</returns>
IEnumerable<IRedirectUrl> GetContentRedirectUrls(Guid contentKey);
/// <summary>
/// Gets all redirect urls.
/// </summary>
/// <param name="pageIndex">The page index.</param>
/// <param name="pageSize">The page size.</param>
/// <param name="total">The total count of redirect urls.</param>
/// <returns>The redirect urls.</returns>
IEnumerable<IRedirectUrl> GetAllRedirectUrls(long pageIndex, int pageSize, out long total);
/// <summary>
/// Gets all redirect urls below a given content item.
/// </summary>
/// <param name="rootContentId">The content unique identifier.</param>
/// <param name="pageIndex">The page index.</param>
/// <param name="pageSize">The page size.</param>
/// <param name="total">The total count of redirect urls.</param>
/// <returns>The redirect urls.</returns>
IEnumerable<IRedirectUrl> GetAllRedirectUrls(int rootContentId, long pageIndex, int pageSize, out long total);
/// <summary>
/// Searches for all redirect urls that contain a given search term in their URL property.
/// </summary>
/// <param name="searchTerm">The term to search for.</param>
/// <param name="pageIndex">The page index.</param>
/// <param name="pageSize">The page size.</param>
/// <param name="total">The total count of redirect urls.</param>
/// <returns>The redirect urls.</returns>
IEnumerable<IRedirectUrl> SearchRedirectUrls(string searchTerm, long pageIndex, int pageSize, out long total);
}
}
| mit |