code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.debugger.engine.evaluation.expression; import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.engine.evaluation.EvaluateException; import com.intellij.debugger.engine.evaluation.EvaluateExceptionUtil; import com.intellij.debugger.engine.evaluation.EvaluateRuntimeException; import com.intellij.debugger.jdi.VirtualMachineProxyImpl; import com.intellij.openapi.diagnostic.Logger; import java.util.HashMap; import com.sun.jdi.Value; import java.util.Map; /** * @author lex */ public class CodeFragmentEvaluator extends BlockStatementEvaluator{ private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.engine.evaluation.expression.CodeFragmentEvaluator"); private final CodeFragmentEvaluator myParentFragmentEvaluator; private final Map<String, Object> mySyntheticLocals = new HashMap<>(); public CodeFragmentEvaluator(CodeFragmentEvaluator parentFragmentEvaluator) { super(null); myParentFragmentEvaluator = parentFragmentEvaluator; } public void setStatements(Evaluator[] evaluators) { myStatements = evaluators; } public Value getValue(String localName, VirtualMachineProxyImpl vm) throws EvaluateException { if(!mySyntheticLocals.containsKey(localName)) { if(myParentFragmentEvaluator != null){ return myParentFragmentEvaluator.getValue(localName, vm); } else { throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.variable.not.declared", localName)); } } Object value = mySyntheticLocals.get(localName); if(value instanceof Value) { return (Value)value; } else if(value == null) { return null; } else if(value instanceof Boolean) { return vm.mirrorOf(((Boolean)value).booleanValue()); } else if(value instanceof Byte) { return vm.mirrorOf(((Byte)value).byteValue()); } else if(value instanceof Character) { return vm.mirrorOf(((Character)value).charValue()); } else if(value instanceof Short) { return vm.mirrorOf(((Short)value).shortValue()); } else if(value instanceof Integer) { return vm.mirrorOf(((Integer)value).intValue()); } else if(value instanceof Long) { return vm.mirrorOf(((Long)value).longValue()); } else if(value instanceof Float) { return vm.mirrorOf(((Float)value).floatValue()); } else if(value instanceof Double) { return vm.mirrorOf(((Double)value).doubleValue()); } else if(value instanceof String) { return vm.mirrorOf((String)value); } else { LOG.error("unknown default initializer type " + value.getClass().getName()); return null; } } private boolean hasValue(String localName) { if(!mySyntheticLocals.containsKey(localName)) { if(myParentFragmentEvaluator != null){ return myParentFragmentEvaluator.hasValue(localName); } else { return false; } } else { return true; } } public void setInitialValue(String localName, Object value) { LOG.assertTrue(!(value instanceof Value), "use setValue for jdi values"); if(hasValue(localName)) { throw new EvaluateRuntimeException( EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.variable.already.declared", localName))); } mySyntheticLocals.put(localName, value); } public void setValue(String localName, Value value) throws EvaluateException { if(!mySyntheticLocals.containsKey(localName)) { if(myParentFragmentEvaluator != null){ myParentFragmentEvaluator.setValue(localName, value); } else { throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.variable.not.declared", localName)); } } else { mySyntheticLocals.put(localName, value); } } }
mglukhikh/intellij-community
java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/CodeFragmentEvaluator.java
Java
apache-2.0
4,502
/*Stats*/ .bar-chart-grids { margin:150px auto; max-width:640px;} .fabo-chart { border-right: 1px; margin: 2em 0 0 0; } .fabo-chart::after { content: " "; display: table; clear: both; } .fabo-chart .fabo-point { height: 400px; display: inline-block; float: left; box-sizing: border-box; padding-left: 0px; ovefabolow: hidden; } .fabo-chart .fabo-point .fabo-point-inner { height: 100%; position: relative; ovefabolow: hidden; background: #f4f6f7; } .fabo-chart .fabo-point .fabo-value-text { width: 100%; text-align: center; z-index: 100; color: #ffffff; font-size: 18px; font-weight: 600; position: absolute; left: 0; right: 0; bottom: 18px; } .fabo-chart .fabo-point .fabo-value-label { width: 100%; text-align: center; z-index: 100; color: #95a5b3; font-size: 12px; font-weight: 700; position: absolute; left: 0; right: 0; top: 18px; } .fabo-chart .fabo-point .fabo-value { box-sizing: content-box; width: 0; height: 100px; border-top: 0 solid transparent; border-right: 0 solid #7b82ff; border-bottom: 0 solid transparent; border-left: 0px solid #7b82ff; transition: height 200ms; position: absolute; bottom: 0; -webkit-animation: chart-height 200ms; animation: chart-height 200ms; } .fabo-chart .fabo-point .fabo-value.hide { display: none; height: 0 !important; } .fabo-chart .fabo-point .fabo-value.hide-border { border-top-width: 0 !important; } @-webkit-keyframes chart-height { 0% { height: 0; } } @keyframes chart-height { 0% { height: 0; } } /*# sourceMappingURL=chart.css.map */
ArmstrongYang/hiShare
dashboard/css/fabochart.css
CSS
apache-2.0
1,719
#include "extensions/common/tap/tap_config_base.h" #include "envoy/config/tap/v3/common.pb.h" #include "envoy/data/tap/v3/common.pb.h" #include "envoy/data/tap/v3/wrapper.pb.h" #include "common/common/assert.h" #include "common/common/fmt.h" #include "common/config/version_converter.h" #include "common/protobuf/utility.h" #include "extensions/common/matcher/matcher.h" #include "absl/container/fixed_array.h" namespace Envoy { namespace Extensions { namespace Common { namespace Tap { using namespace Matcher; bool Utility::addBufferToProtoBytes(envoy::data::tap::v3::Body& output_body, uint32_t max_buffered_bytes, const Buffer::Instance& data, uint32_t buffer_start_offset, uint32_t buffer_length_to_copy) { // TODO(mattklein123): Figure out if we can use the buffer API here directly in some way. This is // is not trivial if we want to avoid extra copies since we end up appending to the existing // protobuf string. // Note that max_buffered_bytes is assumed to include any data already contained in output_bytes. // This is to account for callers that may be tracking this over multiple body objects. ASSERT(buffer_start_offset + buffer_length_to_copy <= data.length()); const uint32_t final_bytes_to_copy = std::min(max_buffered_bytes, buffer_length_to_copy); Buffer::RawSliceVector slices = data.getRawSlices(); trimSlices(slices, buffer_start_offset, final_bytes_to_copy); for (const Buffer::RawSlice& slice : slices) { output_body.mutable_as_bytes()->append(static_cast<const char*>(slice.mem_), slice.len_); } if (final_bytes_to_copy < buffer_length_to_copy) { output_body.set_truncated(true); return true; } else { return false; } } TapConfigBaseImpl::TapConfigBaseImpl(envoy::config::tap::v3::TapConfig&& proto_config, Common::Tap::Sink* admin_streamer) : max_buffered_rx_bytes_(PROTOBUF_GET_WRAPPED_OR_DEFAULT( proto_config.output_config(), max_buffered_rx_bytes, DefaultMaxBufferedBytes)), max_buffered_tx_bytes_(PROTOBUF_GET_WRAPPED_OR_DEFAULT( proto_config.output_config(), max_buffered_tx_bytes, DefaultMaxBufferedBytes)), streaming_(proto_config.output_config().streaming()) { ASSERT(proto_config.output_config().sinks().size() == 1); // TODO(mattklein123): Add per-sink checks to make sure format makes sense. I.e., when using // streaming, we should require the length delimited version of binary proto, etc. sink_format_ = proto_config.output_config().sinks()[0].format(); switch (proto_config.output_config().sinks()[0].output_sink_type_case()) { case envoy::config::tap::v3::OutputSink::OutputSinkTypeCase::kStreamingAdmin: ASSERT(admin_streamer != nullptr, "admin output must be configured via admin"); // TODO(mattklein123): Graceful failure, error message, and test if someone specifies an // admin stream output with the wrong format. RELEASE_ASSERT(sink_format_ == envoy::config::tap::v3::OutputSink::JSON_BODY_AS_BYTES || sink_format_ == envoy::config::tap::v3::OutputSink::JSON_BODY_AS_STRING, "admin output only supports JSON formats"); sink_to_use_ = admin_streamer; break; case envoy::config::tap::v3::OutputSink::OutputSinkTypeCase::kFilePerTap: sink_ = std::make_unique<FilePerTapSink>(proto_config.output_config().sinks()[0].file_per_tap()); sink_to_use_ = sink_.get(); break; default: NOT_REACHED_GCOVR_EXCL_LINE; } envoy::config::common::matcher::v3::MatchPredicate match; if (proto_config.has_match()) { // Use the match field whenever it is set. match = proto_config.match(); } else if (proto_config.has_match_config()) { // Fallback to use the deprecated match_config field and upgrade (wire cast) it to the new // MatchPredicate which is backward compatible with the old MatchPredicate originally // introduced in the Tap filter. Config::VersionConverter::upgrade(proto_config.match_config(), match); } else { throw EnvoyException(fmt::format("Neither match nor match_config is set in TapConfig: {}", proto_config.DebugString())); } buildMatcher(match, matchers_); } const Matcher& TapConfigBaseImpl::rootMatcher() const { ASSERT(!matchers_.empty()); return *matchers_[0]; } namespace { void swapBytesToString(envoy::data::tap::v3::Body& body) { body.set_allocated_as_string(body.release_as_bytes()); } } // namespace void Utility::bodyBytesToString(envoy::data::tap::v3::TraceWrapper& trace, envoy::config::tap::v3::OutputSink::Format sink_format) { // Swap the "bytes" string into the "string" string. This is done purely so that JSON // serialization will serialize as a string vs. doing base64 encoding. if (sink_format != envoy::config::tap::v3::OutputSink::JSON_BODY_AS_STRING) { return; } switch (trace.trace_case()) { case envoy::data::tap::v3::TraceWrapper::TraceCase::kHttpBufferedTrace: { auto* http_trace = trace.mutable_http_buffered_trace(); if (http_trace->has_request() && http_trace->request().has_body()) { swapBytesToString(*http_trace->mutable_request()->mutable_body()); } if (http_trace->has_response() && http_trace->response().has_body()) { swapBytesToString(*http_trace->mutable_response()->mutable_body()); } break; } case envoy::data::tap::v3::TraceWrapper::TraceCase::kHttpStreamedTraceSegment: { auto* http_trace = trace.mutable_http_streamed_trace_segment(); if (http_trace->has_request_body_chunk()) { swapBytesToString(*http_trace->mutable_request_body_chunk()); } if (http_trace->has_response_body_chunk()) { swapBytesToString(*http_trace->mutable_response_body_chunk()); } break; } case envoy::data::tap::v3::TraceWrapper::TraceCase::kSocketBufferedTrace: { auto* socket_trace = trace.mutable_socket_buffered_trace(); for (auto& event : *socket_trace->mutable_events()) { if (event.has_read()) { swapBytesToString(*event.mutable_read()->mutable_data()); } else { ASSERT(event.has_write()); swapBytesToString(*event.mutable_write()->mutable_data()); } } break; } case envoy::data::tap::v3::TraceWrapper::TraceCase::kSocketStreamedTraceSegment: { auto& event = *trace.mutable_socket_streamed_trace_segment()->mutable_event(); if (event.has_read()) { swapBytesToString(*event.mutable_read()->mutable_data()); } else if (event.has_write()) { swapBytesToString(*event.mutable_write()->mutable_data()); } break; } case envoy::data::tap::v3::TraceWrapper::TraceCase::TRACE_NOT_SET: NOT_REACHED_GCOVR_EXCL_LINE; } } void TapConfigBaseImpl::PerTapSinkHandleManagerImpl::submitTrace(TraceWrapperPtr&& trace) { Utility::bodyBytesToString(*trace, parent_.sink_format_); handle_->submitTrace(std::move(trace), parent_.sink_format_); } void FilePerTapSink::FilePerTapSinkHandle::submitTrace( TraceWrapperPtr&& trace, envoy::config::tap::v3::OutputSink::Format format) { if (!output_file_.is_open()) { std::string path = fmt::format("{}_{}", parent_.config_.path_prefix(), trace_id_); switch (format) { case envoy::config::tap::v3::OutputSink::PROTO_BINARY: path += MessageUtil::FileExtensions::get().ProtoBinary; break; case envoy::config::tap::v3::OutputSink::PROTO_BINARY_LENGTH_DELIMITED: path += MessageUtil::FileExtensions::get().ProtoBinaryLengthDelimited; break; case envoy::config::tap::v3::OutputSink::PROTO_TEXT: path += MessageUtil::FileExtensions::get().ProtoText; break; case envoy::config::tap::v3::OutputSink::JSON_BODY_AS_BYTES: case envoy::config::tap::v3::OutputSink::JSON_BODY_AS_STRING: path += MessageUtil::FileExtensions::get().Json; break; default: NOT_REACHED_GCOVR_EXCL_LINE; } ENVOY_LOG_MISC(debug, "Opening tap file for [id={}] to {}", trace_id_, path); // When reading and writing binary files, we need to be sure std::ios_base::binary // is set, otherwise we will not get the expected results on Windows output_file_.open(path, std::ios_base::binary); } ENVOY_LOG_MISC(trace, "Tap for [id={}]: {}", trace_id_, trace->DebugString()); switch (format) { case envoy::config::tap::v3::OutputSink::PROTO_BINARY: trace->SerializeToOstream(&output_file_); break; case envoy::config::tap::v3::OutputSink::PROTO_BINARY_LENGTH_DELIMITED: { Protobuf::io::OstreamOutputStream stream(&output_file_); Protobuf::io::CodedOutputStream coded_stream(&stream); coded_stream.WriteVarint32(trace->ByteSize()); trace->SerializeWithCachedSizes(&coded_stream); break; } case envoy::config::tap::v3::OutputSink::PROTO_TEXT: output_file_ << trace->DebugString(); break; case envoy::config::tap::v3::OutputSink::JSON_BODY_AS_BYTES: case envoy::config::tap::v3::OutputSink::JSON_BODY_AS_STRING: output_file_ << MessageUtil::getJsonStringFromMessage(*trace, true, true); break; default: NOT_REACHED_GCOVR_EXCL_LINE; } } } // namespace Tap } // namespace Common } // namespace Extensions } // namespace Envoy
lizan/envoy
source/extensions/common/tap/tap_config_base.cc
C++
apache-2.0
9,292
#pragma once #include <string> #include "envoy/server/filter_config.h" #include "common/protobuf/protobuf.h" namespace Envoy { namespace Extensions { namespace HttpFilters { namespace Common { /** * Config registration for http filters that have empty configuration blocks. * The boiler plate instantiation functions (createFilterFactory, createFilterFactoryFromProto, * and createEmptyConfigProto) are implemented here. Users of this class have to implement * the createFilter function that instantiates the actual filter. */ class EmptyHttpFilterConfig : public Server::Configuration::NamedHttpFilterConfigFactory { public: virtual Http::FilterFactoryCb createFilter(const std::string& stat_prefix, Server::Configuration::FactoryContext& context) PURE; Http::FilterFactoryCb createFilterFactoryFromProto(const Protobuf::Message&, const std::string& stat_prefix, Server::Configuration::FactoryContext& context) override { return createFilter(stat_prefix, context); } ProtobufTypes::MessagePtr createEmptyConfigProto() override { // Using Struct instead of a custom filter config proto. This is only allowed in tests. return ProtobufTypes::MessagePtr{new Envoy::ProtobufWkt::Struct()}; } std::string configType() override { // Prevent registration of filters by type. This is only allowed in tests. return ""; } std::string name() const override { return name_; } protected: EmptyHttpFilterConfig(const std::string& name) : name_(name) {} private: const std::string name_; }; } // namespace Common } // namespace HttpFilters } // namespace Extensions } // namespace Envoy
lizan/envoy
test/extensions/filters/http/common/empty_http_filter_config.h
C
apache-2.0
1,707
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_09) on Wed Aug 01 14:02:17 EEST 2007 --> <TITLE> datechooser.beans.editor.border.types (DateChooser javadoc) </TITLE> <META NAME="keywords" CONTENT="datechooser.beans.editor.border.types package"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../../../datechooser/beans/editor/border/types/package-summary.html" target="classFrame">datechooser.beans.editor.border.types</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="AbstractBevelBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">AbstractBevelBorderEditor</A> <BR> <A HREF="AbstractBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">AbstractBorderEditor</A> <BR> <A HREF="BevelBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">BevelBorderEditor</A> <BR> <A HREF="CompoundBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">CompoundBorderEditor</A> <BR> <A HREF="DefaultBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">DefaultBorderEditor</A> <BR> <A HREF="EmptyBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">EmptyBorderEditor</A> <BR> <A HREF="EtchedBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">EtchedBorderEditor</A> <BR> <A HREF="LineBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">LineBorderEditor</A> <BR> <A HREF="MatteBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">MatteBorderEditor</A> <BR> <A HREF="NoBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">NoBorderEditor</A> <BR> <A HREF="SoftBevelBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">SoftBevelBorderEditor</A> <BR> <A HREF="TitledBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">TitledBorderEditor</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
AndresJMM/Proyecto
Proyecto/librerias/jdatechooser_bin_doc_1_1_1/javadoc/datechooser/beans/editor/border/types/package-frame.html
HTML
apache-2.0
2,595
package com.kit.imagelib.imagelooker; public interface OnPageSelectedListener { public void onPageSelected(); }
BigAppOS/BigApp_Discuz_Android
libs/ImageLib/src/com/kit/imagelib/imagelooker/OnPageSelectedListener.java
Java
apache-2.0
126
package matchers import ( "fmt" "github.com/onsi/gomega/format" "math" ) type BeNumericallyMatcher struct { Comparator string CompareTo []interface{} } func (matcher *BeNumericallyMatcher) Match(actual interface{}) (success bool, message string, err error) { if len(matcher.CompareTo) == 0 || len(matcher.CompareTo) > 2 { return false, "", fmt.Errorf("BeNumerically requires 1 or 2 CompareTo arguments. Got:\n%s", format.Object(matcher.CompareTo, 1)) } if !isNumber(actual) { return false, "", fmt.Errorf("Expected a number. Got:\n%s", format.Object(actual, 1)) } if !isNumber(matcher.CompareTo[0]) { return false, "", fmt.Errorf("Expected a number. Got:\n%s", format.Object(matcher.CompareTo[0], 1)) } if len(matcher.CompareTo) == 2 && !isNumber(matcher.CompareTo[1]) { return false, "", fmt.Errorf("Expected a number. Got:\n%s", format.Object(matcher.CompareTo[0], 1)) } switch matcher.Comparator { case "==", "~", ">", ">=", "<", "<=": default: return false, "", fmt.Errorf("Unknown comparator: %s", matcher.Comparator) } if isFloat(actual) || isFloat(matcher.CompareTo[0]) { var secondOperand float64 = 1e-8 if len(matcher.CompareTo) == 2 { secondOperand = toFloat(matcher.CompareTo[1]) } success = matcher.matchFloats(toFloat(actual), toFloat(matcher.CompareTo[0]), secondOperand) } else if isInteger(actual) { var secondOperand int64 = 0 if len(matcher.CompareTo) == 2 { secondOperand = toInteger(matcher.CompareTo[1]) } success = matcher.matchIntegers(toInteger(actual), toInteger(matcher.CompareTo[0]), secondOperand) } else if isUnsignedInteger(actual) { var secondOperand uint64 = 0 if len(matcher.CompareTo) == 2 { secondOperand = toUnsignedInteger(matcher.CompareTo[1]) } success = matcher.matchUnsignedIntegers(toUnsignedInteger(actual), toUnsignedInteger(matcher.CompareTo[0]), secondOperand) } else { return false, "", fmt.Errorf("Failed to compare:\n%s\n%s:\n%s", format.Object(actual, 1), matcher.Comparator, format.Object(matcher.CompareTo[0], 1)) } if success { return true, format.Message(actual, fmt.Sprintf("not to be %s", matcher.Comparator), matcher.CompareTo[0]), nil } else { return false, format.Message(actual, fmt.Sprintf("to be %s", matcher.Comparator), matcher.CompareTo[0]), nil } } func (matcher *BeNumericallyMatcher) matchIntegers(actual, compareTo, threshold int64) (success bool) { switch matcher.Comparator { case "==", "~": diff := actual - compareTo return -threshold <= diff && diff <= threshold case ">": return (actual > compareTo) case ">=": return (actual >= compareTo) case "<": return (actual < compareTo) case "<=": return (actual <= compareTo) } return false } func (matcher *BeNumericallyMatcher) matchUnsignedIntegers(actual, compareTo, threshold uint64) (success bool) { switch matcher.Comparator { case "==", "~": if actual < compareTo { actual, compareTo = compareTo, actual } return actual-compareTo <= threshold case ">": return (actual > compareTo) case ">=": return (actual >= compareTo) case "<": return (actual < compareTo) case "<=": return (actual <= compareTo) } return false } func (matcher *BeNumericallyMatcher) matchFloats(actual, compareTo, threshold float64) (success bool) { switch matcher.Comparator { case "~": return math.Abs(actual-compareTo) <= threshold case "==": return (actual == compareTo) case ">": return (actual > compareTo) case ">=": return (actual >= compareTo) case "<": return (actual < compareTo) case "<=": return (actual <= compareTo) } return false }
aminjam/onememberoauth2
Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_numerically_matcher.go
GO
apache-2.0
3,596
/******************************************************************************* * Copyright 2015 Unicon (R) Licensed under the * Educational Community 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.osedu.org/licenses/ECL-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.apereo.lai; import java.io.Serializable; /** * @author ggilbert * */ public interface Institution extends Serializable { String getName(); String getKey(); String getSecret(); }
ccooper1/OpenDash
src/main/java/org/apereo/lai/Institution.java
Java
apache-2.0
967
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/include/plat/subroutine_executor.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file subroutine_executor.H /// /// @brief Defines the PLAT Subroutine Executor Macro. /// /// The PLAT Subroutine Executor macro is called by /// FAPI_CALL_SUBROUTINE when a hardware procedure when /// a subroutine is needed, typicaly a chipop function. /// /// Example implementation of plat code #ifndef SUBROUTINEEXECUTOR_H_ #define SUBROUTINEEXECUTOR_H_ #include <fapi2_subroutine_executor.H> #include <plat_trace.H> /** * @brief Subroutine Executor macro example code - Platforms will need to * implement as needed for their enviroment. * * This macro calls a PLAT macro which will do any platform specific work to * execute the Subroutine (e.g. dlopening a shared library) */ #define FAPI_PLAT_CALL_SUBROUTINE(RC, FUNC, _args...) \ { \ FAPI_DBG("executing FAPI_PLAT_CALL_SUBROUTINE macro"); \ RC = FUNC(_args); \ } #endif
Over-enthusiastic/hostboot
src/import/hwpf/fapi2/include/plat/subroutine_executor.H
C++
apache-2.0
2,727
/* * Copyright (c) 2017 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #define DT_DRV_COMPAT plantower_pms7003 /* sensor pms7003.c - Driver for plantower PMS7003 sensor * PMS7003 product: http://www.plantower.com/en/content/?110.html * PMS7003 spec: http://aqicn.org/air/view/sensor/spec/pms7003.pdf */ #include <errno.h> #include <arch/cpu.h> #include <init.h> #include <kernel.h> #include <drivers/sensor.h> #include <stdlib.h> #include <string.h> #include <drivers/uart.h> #include <logging/log.h> LOG_MODULE_REGISTER(PMS7003, CONFIG_SENSOR_LOG_LEVEL); /* wait serial output with 1000ms timeout */ #define CFG_PMS7003_SERIAL_TIMEOUT 1000 struct pms7003_data { const struct device *uart_dev; uint16_t pm_1_0; uint16_t pm_2_5; uint16_t pm_10; }; /** * @brief wait for an array data from uart device with a timeout * * @param dev the uart device * @param data the data array to be matched * @param len the data array len * @param timeout the timeout in milliseconds * @return 0 if success; -ETIME if timeout */ static int uart_wait_for(const struct device *dev, uint8_t *data, int len, int timeout) { int matched_size = 0; int64_t timeout_time = k_uptime_get() + K_MSEC(timeout); while (1) { uint8_t c; if (k_uptime_get() > timeout_time) { return -ETIME; } if (uart_poll_in(dev, &c) == 0) { if (c == data[matched_size]) { matched_size++; if (matched_size == len) { break; } } else if (c == data[0]) { matched_size = 1; } else { matched_size = 0; } } } return 0; } /** * @brief read bytes from uart * * @param data the data buffer * @param len the data len * @param timeout the timeout in milliseconds * @return 0 if success; -ETIME if timeout */ static int uart_read_bytes(const struct device *dev, uint8_t *data, int len, int timeout) { int read_size = 0; int64_t timeout_time = k_uptime_get() + K_MSEC(timeout); while (1) { uint8_t c; if (k_uptime_get() > timeout_time) { return -ETIME; } if (uart_poll_in(dev, &c) == 0) { data[read_size++] = c; if (read_size == len) { break; } } } return 0; } static int pms7003_sample_fetch(const struct device *dev, enum sensor_channel chan) { struct pms7003_data *drv_data = dev->data; /* sample output */ /* 42 4D 00 1C 00 01 00 01 00 01 00 01 00 01 00 01 01 92 * 00 4E 00 03 00 00 00 00 00 00 71 00 02 06 */ uint8_t pms7003_start_bytes[] = {0x42, 0x4d}; uint8_t pms7003_receive_buffer[30]; if (uart_wait_for(drv_data->uart_dev, pms7003_start_bytes, sizeof(pms7003_start_bytes), CFG_PMS7003_SERIAL_TIMEOUT) < 0) { LOG_WRN("waiting for start bytes is timeout"); return -ETIME; } if (uart_read_bytes(drv_data->uart_dev, pms7003_receive_buffer, 30, CFG_PMS7003_SERIAL_TIMEOUT) < 0) { return -ETIME; } drv_data->pm_1_0 = (pms7003_receive_buffer[8] << 8) + pms7003_receive_buffer[9]; drv_data->pm_2_5 = (pms7003_receive_buffer[10] << 8) + pms7003_receive_buffer[11]; drv_data->pm_10 = (pms7003_receive_buffer[12] << 8) + pms7003_receive_buffer[13]; LOG_DBG("pm1.0 = %d", drv_data->pm_1_0); LOG_DBG("pm2.5 = %d", drv_data->pm_2_5); LOG_DBG("pm10 = %d", drv_data->pm_10); return 0; } static int pms7003_channel_get(const struct device *dev, enum sensor_channel chan, struct sensor_value *val) { struct pms7003_data *drv_data = dev->data; if (chan == SENSOR_CHAN_PM_1_0) { val->val1 = drv_data->pm_1_0; val->val2 = 0; } else if (chan == SENSOR_CHAN_PM_2_5) { val->val1 = drv_data->pm_2_5; val->val2 = 0; } else if (chan == SENSOR_CHAN_PM_10) { val->val1 = drv_data->pm_10; val->val2 = 0; } else { return -EINVAL; } return 0; } static const struct sensor_driver_api pms7003_api = { .sample_fetch = &pms7003_sample_fetch, .channel_get = &pms7003_channel_get, }; static int pms7003_init(const struct device *dev) { struct pms7003_data *drv_data = dev->data; drv_data->uart_dev = device_get_binding(DT_INST_BUS_LABEL(0)); if (!drv_data->uart_dev) { LOG_DBG("uart device is not found: %s", DT_INST_BUS_LABEL(0)); return -EINVAL; } return 0; } static struct pms7003_data pms7003_data; DEVICE_DT_INST_DEFINE(0, &pms7003_init, device_pm_control_nop, &pms7003_data, NULL, POST_KERNEL, CONFIG_SENSOR_INIT_PRIORITY, &pms7003_api);
Vudentz/zephyr
drivers/sensor/pms7003/pms7003.c
C
apache-2.0
4,354
var spawn = require('child_process').spawn var port = exports.port = 1337 exports.registry = "http://localhost:" + port exports.run = run function run (cmd, t, opts, cb) { if (!opts) opts = {} if (!Array.isArray(cmd)) throw new Error("cmd must be an Array") if (!t || !t.end) throw new Error("node-tap instance is missing") var stdout = "" , stderr = "" , node = process.execPath , child = spawn(node, cmd, opts) child.stderr.on("data", function (chunk) { stderr += chunk }) child.stdout.on("data", function (chunk) { stdout += chunk }) child.on("close", function (code) { if (cb) cb(t, stdout, stderr, code, { cmd: cmd, opts: opts }) else t.end() }) }
jplusui/xfly
xfly/node/node_modules/npm/test/common-tap.js
JavaScript
apache-2.0
731
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/securityhub/model/AwsS3BucketLoggingConfiguration.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace SecurityHub { namespace Model { AwsS3BucketLoggingConfiguration::AwsS3BucketLoggingConfiguration() : m_destinationBucketNameHasBeenSet(false), m_logFilePrefixHasBeenSet(false) { } AwsS3BucketLoggingConfiguration::AwsS3BucketLoggingConfiguration(JsonView jsonValue) : m_destinationBucketNameHasBeenSet(false), m_logFilePrefixHasBeenSet(false) { *this = jsonValue; } AwsS3BucketLoggingConfiguration& AwsS3BucketLoggingConfiguration::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("DestinationBucketName")) { m_destinationBucketName = jsonValue.GetString("DestinationBucketName"); m_destinationBucketNameHasBeenSet = true; } if(jsonValue.ValueExists("LogFilePrefix")) { m_logFilePrefix = jsonValue.GetString("LogFilePrefix"); m_logFilePrefixHasBeenSet = true; } return *this; } JsonValue AwsS3BucketLoggingConfiguration::Jsonize() const { JsonValue payload; if(m_destinationBucketNameHasBeenSet) { payload.WithString("DestinationBucketName", m_destinationBucketName); } if(m_logFilePrefixHasBeenSet) { payload.WithString("LogFilePrefix", m_logFilePrefix); } return payload; } } // namespace Model } // namespace SecurityHub } // namespace Aws
awslabs/aws-sdk-cpp
aws-cpp-sdk-securityhub/source/model/AwsS3BucketLoggingConfiguration.cpp
C++
apache-2.0
1,584
# # Author:: Adam Jacob (<adam@chef.io>) # Copyright:: Copyright 2008-2017, Chef Software Inc. # License:: Apache License, Version 2.0 # # 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. # require "spec_helper" require "ostruct" describe Chef::Provider::Package::Apt do # XXX: sorry this is ugly and was done quickly to get 12.0.2 out, this file needs a rewrite to use # let blocks and shared examples [ Chef::Resource::Package, Chef::Resource::AptPackage ].each do |resource_klass| describe "when the new_resource is a #{resource_klass}" do before(:each) do @node = Chef::Node.new @events = Chef::EventDispatch::Dispatcher.new @run_context = Chef::RunContext.new(@node, {}, @events) @new_resource = resource_klass.new("irssi", @run_context) @status = double("Status", :exitstatus => 0) @provider = Chef::Provider::Package::Apt.new(@new_resource, @run_context) @stdin = StringIO.new @stdout = <<-PKG_STATUS irssi: Installed: (none) Candidate: 0.8.14-1ubuntu4 Version table: 0.8.14-1ubuntu4 0 500 http://us.archive.ubuntu.com/ubuntu/ lucid/main Packages PKG_STATUS @stderr = "" @shell_out = OpenStruct.new(:stdout => @stdout, :stdin => @stdin, :stderr => @stderr, :status => @status, :exitstatus => 0) @timeout = 900 end describe "when loading current resource" do it "should create a current resource with the name of the new_resource" do expect(@provider).to receive(:shell_out!).with( "apt-cache", "policy", @new_resource.package_name, :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ).and_return(@shell_out) @provider.load_current_resource current_resource = @provider.current_resource expect(current_resource).to be_a(Chef::Resource::Package) expect(current_resource.name).to eq("irssi") expect(current_resource.package_name).to eq("irssi") expect(current_resource.version).to eql([nil]) end it "should set the installed version if package has one" do @stdout.replace(<<-INSTALLED) sudo: Installed: 1.7.2p1-1ubuntu5.3 Candidate: 1.7.2p1-1ubuntu5.3 Version table: *** 1.7.2p1-1ubuntu5.3 0 500 http://us.archive.ubuntu.com/ubuntu/ lucid-updates/main Packages 500 http://security.ubuntu.com/ubuntu/ lucid-security/main Packages 100 /var/lib/dpkg/status 1.7.2p1-1ubuntu5 0 500 http://us.archive.ubuntu.com/ubuntu/ lucid/main Packages INSTALLED expect(@provider).to receive(:shell_out!).and_return(@shell_out) @provider.load_current_resource expect(@provider.current_resource.version).to eq(["1.7.2p1-1ubuntu5.3"]) expect(@provider.candidate_version).to eql(["1.7.2p1-1ubuntu5.3"]) end # it is the superclasses responsibility to throw most exceptions it "if the package does not exist in the cache sets installed + candidate version to nil" do @new_resource.package_name("conic-smarms") policy_out = <<-POLICY_STDOUT N: Unable to locate package conic-smarms POLICY_STDOUT policy = double(:stdout => policy_out, :exitstatus => 0) expect(@provider).to receive(:shell_out!).with( "apt-cache", "policy", "conic-smarms", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ).and_return(policy) showpkg_out = <<-SHOWPKG_STDOUT N: Unable to locate package conic-smarms SHOWPKG_STDOUT showpkg = double(:stdout => showpkg_out, :exitstatus => 0) expect(@provider).to receive(:shell_out!).with( "apt-cache", "showpkg", "conic-smarms", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ).and_return(showpkg) @provider.load_current_resource end # libmysqlclient-dev is a real package in newer versions of debian + ubuntu # list of virtual packages: http://www.debian.org/doc/packaging-manuals/virtual-package-names-list.txt it "should not install the virtual package there is a single provider package and it is installed" do @new_resource.package_name("libmysqlclient15-dev") virtual_package_out = <<-VPKG_STDOUT libmysqlclient15-dev: Installed: (none) Candidate: (none) Version table: VPKG_STDOUT virtual_package = double(:stdout => virtual_package_out, :exitstatus => 0) expect(@provider).to receive(:shell_out!).with( "apt-cache", "policy", "libmysqlclient15-dev", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ).and_return(virtual_package) showpkg_out = <<-SHOWPKG_STDOUT Package: libmysqlclient15-dev Versions: Reverse Depends: libmysqlclient-dev,libmysqlclient15-dev libmysqlclient-dev,libmysqlclient15-dev libmysqlclient-dev,libmysqlclient15-dev libmysqlclient-dev,libmysqlclient15-dev libmysqlclient-dev,libmysqlclient15-dev libmysqlclient-dev,libmysqlclient15-dev Dependencies: Provides: Reverse Provides: libmysqlclient-dev 5.1.41-3ubuntu12.7 libmysqlclient-dev 5.1.41-3ubuntu12.10 libmysqlclient-dev 5.1.41-3ubuntu12 SHOWPKG_STDOUT showpkg = double(:stdout => showpkg_out, :exitstatus => 0) expect(@provider).to receive(:shell_out!).with( "apt-cache", "showpkg", "libmysqlclient15-dev", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ).and_return(showpkg) real_package_out = <<-RPKG_STDOUT libmysqlclient-dev: Installed: 5.1.41-3ubuntu12.10 Candidate: 5.1.41-3ubuntu12.10 Version table: *** 5.1.41-3ubuntu12.10 0 500 http://us.archive.ubuntu.com/ubuntu/ lucid-updates/main Packages 100 /var/lib/dpkg/status 5.1.41-3ubuntu12.7 0 500 http://security.ubuntu.com/ubuntu/ lucid-security/main Packages 5.1.41-3ubuntu12 0 500 http://us.archive.ubuntu.com/ubuntu/ lucid/main Packages RPKG_STDOUT real_package = double(:stdout => real_package_out, :exitstatus => 0) expect(@provider).to receive(:shell_out!).with( "apt-cache", "policy", "libmysqlclient-dev", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ).and_return(real_package) @provider.load_current_resource end it "should raise an exception if you specify a virtual package with multiple provider packages" do @new_resource.package_name("mp3-decoder") virtual_package_out = <<-VPKG_STDOUT mp3-decoder: Installed: (none) Candidate: (none) Version table: VPKG_STDOUT virtual_package = double(:stdout => virtual_package_out, :exitstatus => 0) expect(@provider).to receive(:shell_out!).with( "apt-cache", "policy", "mp3-decoder", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ).and_return(virtual_package) showpkg_out = <<-SHOWPKG_STDOUT Package: mp3-decoder Versions: Reverse Depends: nautilus,mp3-decoder vux,mp3-decoder plait,mp3-decoder ecasound,mp3-decoder nautilus,mp3-decoder Dependencies: Provides: Reverse Provides: vlc-nox 1.0.6-1ubuntu1.8 vlc 1.0.6-1ubuntu1.8 vlc-nox 1.0.6-1ubuntu1 vlc 1.0.6-1ubuntu1 opencubicplayer 1:0.1.17-2 mpg321 0.2.10.6 mpg123 1.12.1-0ubuntu1 SHOWPKG_STDOUT showpkg = double(:stdout => showpkg_out, :exitstatus => 0) expect(@provider).to receive(:shell_out!).with( "apt-cache", "showpkg", "mp3-decoder", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ).and_return(showpkg) expect { @provider.load_current_resource }.to raise_error(Chef::Exceptions::Package) end it "should run apt-cache policy with the default_release option, if there is one on the resource" do @new_resource = Chef::Resource::AptPackage.new("irssi", @run_context) @provider = Chef::Provider::Package::Apt.new(@new_resource, @run_context) @new_resource.default_release("lenny-backports") @new_resource.provider(nil) expect(@provider).to receive(:shell_out!).with( "apt-cache", "-o", "APT::Default-Release=lenny-backports", "policy", "irssi", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ).and_return(@shell_out) @provider.load_current_resource end it "raises an exception if a source is specified (CHEF-5113)" do @new_resource.source "pluto" expect(@provider).to receive(:shell_out!).with( "apt-cache", "policy", @new_resource.package_name, :env => { "DEBIAN_FRONTEND" => "noninteractive" } , :timeout => @timeout ).and_return(@shell_out) expect { @provider.run_action(:install) }.to raise_error(Chef::Exceptions::Package) end end context "after loading the current resource" do before do @current_resource = resource_klass.new("irssi", @run_context) @provider.current_resource = @current_resource allow(@provider).to receive(:package_data).and_return({ "irssi" => { virtual: false, candidate_version: "0.8.12-7", installed_version: nil, }, "libmysqlclient15-dev" => { virtual: true, candidate_version: nil, installed_version: nil, }, }) end describe "install_package" do it "should run apt-get install with the package name and version" do expect(@provider).to receive(:shell_out!). with( "apt-get", "-q", "-y", "install", "irssi=0.8.12-7", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) @provider.install_package(["irssi"], ["0.8.12-7"]) end it "should run apt-get install with the package name and version and options if specified" do expect(@provider).to receive(:shell_out!).with( "apt-get", "-q", "-y", "--force-yes", "install", "irssi=0.8.12-7", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) @new_resource.options("--force-yes") @provider.install_package(["irssi"], ["0.8.12-7"]) end it "should run apt-get install with the package name and version and default_release if there is one and provider is explicitly defined" do @new_resource = nil @new_resource = Chef::Resource::AptPackage.new("irssi", @run_context) @new_resource.default_release("lenny-backports") @new_resource.provider = nil @provider.new_resource = @new_resource expect(@provider).to receive(:shell_out!).with( "apt-get", "-q", "-y", "-o", "APT::Default-Release=lenny-backports", "install", "irssi=0.8.12-7", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) @provider.install_package(["irssi"], ["0.8.12-7"]) end it "should run apt-get install with the package name and quotes options if specified" do expect(@provider).to receive(:shell_out!).with( "apt-get", "-q", "-y", "--force-yes", "-o", "Dpkg::Options::=--force-confdef", "-o", "Dpkg::Options::=--force-confnew", "install", "irssi=0.8.12-7", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) @new_resource.options('--force-yes -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confnew"') @provider.install_package(["irssi"], ["0.8.12-7"]) end end describe resource_klass, "upgrade_package" do it "should run install_package with the name and version" do expect(@provider).to receive(:install_package).with(["irssi"], ["0.8.12-7"]) @provider.upgrade_package(["irssi"], ["0.8.12-7"]) end end describe resource_klass, "remove_package" do it "should run apt-get remove with the package name" do expect(@provider).to receive(:shell_out!).with( "apt-get", "-q", "-y", "remove", "irssi", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) @provider.remove_package(["irssi"], ["0.8.12-7"]) end it "should run apt-get remove with the package name and options if specified" do expect(@provider).to receive(:shell_out!).with( "apt-get", "-q", "-y", "--force-yes", "remove", "irssi", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) @new_resource.options("--force-yes") @provider.remove_package(["irssi"], ["0.8.12-7"]) end end describe "when purging a package" do it "should run apt-get purge with the package name" do expect(@provider).to receive(:shell_out!).with( "apt-get", "-q", "-y", "purge", "irssi", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) @provider.purge_package(["irssi"], ["0.8.12-7"]) end it "should run apt-get purge with the package name and options if specified" do expect(@provider).to receive(:shell_out!).with( "apt-get", "-q", "-y", "--force-yes", "purge", "irssi", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) @new_resource.options("--force-yes") @provider.purge_package(["irssi"], ["0.8.12-7"]) end end describe "when preseeding a package" do before(:each) do allow(@provider).to receive(:get_preseed_file).and_return("/tmp/irssi-0.8.12-7.seed") end it "should get the full path to the preseed response file" do file = "/tmp/irssi-0.8.12-7.seed" expect(@provider).to receive(:shell_out!).with( "debconf-set-selections", "/tmp/irssi-0.8.12-7.seed", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) @provider.preseed_package(file) end it "should run debconf-set-selections on the preseed file if it has changed" do expect(@provider).to receive(:shell_out!).with( "debconf-set-selections", "/tmp/irssi-0.8.12-7.seed", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) file = @provider.get_preseed_file("irssi", "0.8.12-7") @provider.preseed_package(file) end it "should not run debconf-set-selections if the preseed file has not changed" do allow(@provider).to receive(:check_all_packages_state) @current_resource.version "0.8.11" @new_resource.response_file "/tmp/file" allow(@provider).to receive(:get_preseed_file).and_return(false) expect(@provider).not_to receive(:shell_out!) @provider.run_action(:reconfig) end end describe "when reconfiguring a package" do it "should run dpkg-reconfigure package" do expect(@provider).to receive(:shell_out!).with( "dpkg-reconfigure", "irssi", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) @provider.reconfig_package("irssi", "0.8.12-7") end end describe "when locking a package" do it "should run apt-mark hold package" do expect(@provider).to receive(:shell_out!).with( "apt-mark", "hold", "irssi", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) @provider.lock_package("irssi", "0.8.12-7") end end describe "when unlocking a package" do it "should run apt-mark unhold package" do expect(@provider).to receive(:shell_out!).with( "apt-mark", "unhold", "irssi", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) @provider.unlock_package("irssi", "0.8.12-7") end end describe "when installing a virtual package" do it "should install the package without specifying a version" do @provider.package_data["libmysqlclient15-dev"][:virtual] = true expect(@provider).to receive(:shell_out!).with( "apt-get", "-q", "-y", "install", "libmysqlclient15-dev", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) @provider.install_package(["libmysqlclient15-dev"], ["not_a_real_version"]) end end describe "when removing a virtual package" do it "should remove the resolved name instead of the virtual package name" do expect(@provider).to receive(:resolve_virtual_package_name).with("libmysqlclient15-dev").and_return("libmysqlclient-dev") expect(@provider).to receive(:shell_out!).with( "apt-get", "-q", "-y", "remove", "libmysqlclient-dev", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) @provider.remove_package(["libmysqlclient15-dev"], ["not_a_real_version"]) end end describe "when purging a virtual package" do it "should purge the resolved name instead of the virtual package name" do expect(@provider).to receive(:resolve_virtual_package_name).with("libmysqlclient15-dev").and_return("libmysqlclient-dev") expect(@provider).to receive(:shell_out!).with( "apt-get", "-q", "-y", "purge", "libmysqlclient-dev", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) @provider.purge_package(["libmysqlclient15-dev"], ["not_a_real_version"]) end end describe "when installing multiple packages" do it "can install a virtual package followed by a non-virtual package" do # https://github.com/chef/chef/issues/2914 expect(@provider).to receive(:shell_out!).with( "apt-get", "-q", "-y", "install", "libmysqlclient15-dev", "irssi=0.8.12-7", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) @provider.install_package(["libmysqlclient15-dev", "irssi"], ["not_a_real_version", "0.8.12-7"]) end end describe "#action_install" do it "should run dpkg to compare versions if an existing version is installed" do allow(@provider).to receive(:get_current_versions).and_return("1.4.0") allow(@new_resource).to receive(:allow_downgrade).and_return(false) expect(@provider).to receive(:shell_out_compact_timeout).with( "dpkg", "--compare-versions", "1.4.0", "gt", "0.8.12-7" ).and_return(double(error?: false)) @provider.run_action(:upgrade) end it "should install the package if the installed version is older" do allow(@provider).to receive(:get_current_versions).and_return("0.4.0") allow(@new_resource).to receive(:allow_downgrade).and_return(false) expect(@provider).to receive(:version_compare).and_return(-1) expect(@provider).to receive(:shell_out!).with( "apt-get", "-q", "-y", "install", "irssi=0.8.12-7", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) @provider.run_action(:upgrade) end it "should not compare versions if an existing version is not installed" do allow(@provider).to receive(:get_current_versions).and_return(nil) allow(@new_resource).to receive(:allow_downgrade).and_return(false) expect(@provider).not_to receive(:version_compare) expect(@provider).to receive(:shell_out!).with( "apt-get", "-q", "-y", "install", "irssi=0.8.12-7", :env => { "DEBIAN_FRONTEND" => "noninteractive" }, :timeout => @timeout ) @provider.run_action(:upgrade) end end end end end end
mal/chef
spec/unit/provider/package/apt_spec.rb
Ruby
apache-2.0
21,755
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.Remoting; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Remote; using Microsoft.VisualStudio.LanguageServices.Remote; using Nerdbank; using Roslyn.Utilities; using StreamJsonRpc; namespace Roslyn.Test.Utilities.Remote { internal sealed class InProcRemoteHostClient : RemoteHostClient { private readonly InProcRemoteServices _inprocServices; private readonly ReferenceCountedDisposable<RemotableDataJsonRpc> _remotableDataRpc; private readonly JsonRpc _rpc; public static async Task<RemoteHostClient> CreateAsync(Workspace workspace, bool runCacheCleanup) { var inprocServices = new InProcRemoteServices(runCacheCleanup); // Create the RemotableDataJsonRpc before we create the remote host: this call implicitly sets up the remote IExperimentationService so that will be available for later calls var remotableDataRpc = new RemotableDataJsonRpc(workspace, inprocServices.Logger, await inprocServices.RequestServiceAsync(WellKnownServiceHubServices.SnapshotService).ConfigureAwait(false)); var remoteHostStream = await inprocServices.RequestServiceAsync(WellKnownRemoteHostServices.RemoteHostService).ConfigureAwait(false); var current = CreateClientId(Process.GetCurrentProcess().Id.ToString()); var instance = new InProcRemoteHostClient(current, workspace, inprocServices, new ReferenceCountedDisposable<RemotableDataJsonRpc>(remotableDataRpc), remoteHostStream); // make sure connection is done right var telemetrySession = default(string); var uiCultureLCIDE = 0; var cultureLCID = 0; var host = await instance._rpc.InvokeAsync<string>(nameof(IRemoteHostService.Connect), current, uiCultureLCIDE, cultureLCID, telemetrySession).ConfigureAwait(false); // TODO: change this to non fatal watson and make VS to use inproc implementation Contract.ThrowIfFalse(host == current.ToString()); instance.Started(); // return instance return instance; } private InProcRemoteHostClient( string clientId, Workspace workspace, InProcRemoteServices inprocServices, ReferenceCountedDisposable<RemotableDataJsonRpc> remotableDataRpc, Stream stream) : base(workspace) { Contract.ThrowIfNull(remotableDataRpc); ClientId = clientId; _inprocServices = inprocServices; _remotableDataRpc = remotableDataRpc; _rpc = stream.CreateStreamJsonRpc(target: this, inprocServices.Logger); // handle disconnected situation _rpc.Disconnected += OnRpcDisconnected; _rpc.StartListening(); } public AssetStorage AssetStorage => _inprocServices.AssetStorage; public void RegisterService(string name, Func<Stream, IServiceProvider, ServiceHubServiceBase> serviceCreator) { _inprocServices.RegisterService(name, serviceCreator); } public override string ClientId { get; } public override async Task<Connection> TryCreateConnectionAsync( string serviceName, object callbackTarget, CancellationToken cancellationToken) { // get stream from service hub to communicate service specific information // this is what consumer actually use to communicate information var serviceStream = await _inprocServices.RequestServiceAsync(serviceName).ConfigureAwait(false); return new JsonRpcConnection(_inprocServices.Logger, callbackTarget, serviceStream, _remotableDataRpc.TryAddReference()); } protected override void OnStarted() { } protected override void OnStopped() { // we are asked to disconnect. unsubscribe and dispose to disconnect _rpc.Disconnected -= OnRpcDisconnected; _rpc.Dispose(); _remotableDataRpc.Dispose(); } private void OnRpcDisconnected(object sender, JsonRpcDisconnectedEventArgs e) { Stopped(); } public class ServiceProvider : IServiceProvider { private static readonly TraceSource s_traceSource = new TraceSource("inprocRemoteClient"); private readonly AssetStorage _storage; public ServiceProvider(bool runCacheCleanup) { _storage = runCacheCleanup ? new AssetStorage(cleanupInterval: TimeSpan.FromSeconds(30), purgeAfter: TimeSpan.FromMinutes(1), gcAfter: TimeSpan.FromMinutes(5)) : new AssetStorage(); } public AssetStorage AssetStorage => _storage; public object GetService(Type serviceType) { if (typeof(TraceSource) == serviceType) { return s_traceSource; } if (typeof(AssetStorage) == serviceType) { return _storage; } throw ExceptionUtilities.UnexpectedValue(serviceType); } } private class InProcRemoteServices { private readonly ServiceProvider _serviceProvider; private readonly Dictionary<string, Func<Stream, IServiceProvider, ServiceHubServiceBase>> _creatorMap; public InProcRemoteServices(bool runCacheCleanup) { _serviceProvider = new ServiceProvider(runCacheCleanup); _creatorMap = new Dictionary<string, Func<Stream, IServiceProvider, ServiceHubServiceBase>>(); RegisterService(WellKnownRemoteHostServices.RemoteHostService, (s, p) => new RemoteHostService(s, p)); RegisterService(WellKnownServiceHubServices.CodeAnalysisService, (s, p) => new CodeAnalysisService(s, p)); RegisterService(WellKnownServiceHubServices.SnapshotService, (s, p) => new SnapshotService(s, p)); RegisterService(WellKnownServiceHubServices.RemoteSymbolSearchUpdateEngine, (s, p) => new RemoteSymbolSearchUpdateEngine(s, p)); } public AssetStorage AssetStorage => _serviceProvider.AssetStorage; public TraceSource Logger { get; } = new TraceSource("Default"); public void RegisterService(string name, Func<Stream, IServiceProvider, ServiceHubServiceBase> serviceCreator) { _creatorMap.Add(name, serviceCreator); } public Task<Stream> RequestServiceAsync(string serviceName) { if (_creatorMap.TryGetValue(serviceName, out var creator)) { var tuple = FullDuplexStream.CreateStreams(); return Task.FromResult<Stream>(new WrappedStream(creator(tuple.Item1, _serviceProvider), tuple.Item2)); } throw ExceptionUtilities.UnexpectedValue(serviceName); } private class WrappedStream : Stream { private readonly IDisposable _service; private readonly Stream _stream; public WrappedStream(IDisposable service, Stream stream) { // tie service's lifetime with that of stream _service = service; _stream = stream; } public override long Position { get { return _stream.Position; } set { _stream.Position = value; } } public override int ReadTimeout { get { return _stream.ReadTimeout; } set { _stream.ReadTimeout = value; } } public override int WriteTimeout { get { return _stream.WriteTimeout; } set { _stream.WriteTimeout = value; } } public override bool CanRead => _stream.CanRead; public override bool CanSeek => _stream.CanSeek; public override bool CanWrite => _stream.CanWrite; public override long Length => _stream.Length; public override bool CanTimeout => _stream.CanTimeout; public override void Flush() => _stream.Flush(); public override Task FlushAsync(CancellationToken cancellationToken) => _stream.FlushAsync(cancellationToken); public override long Seek(long offset, SeekOrigin origin) => _stream.Seek(offset, origin); public override void SetLength(long value) => _stream.SetLength(value); public override int ReadByte() => _stream.ReadByte(); public override void WriteByte(byte value) => _stream.WriteByte(value); public override int Read(byte[] buffer, int offset, int count) => _stream.Read(buffer, offset, count); public override void Write(byte[] buffer, int offset, int count) => _stream.Write(buffer, offset, count); public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => _stream.ReadAsync(buffer, offset, count, cancellationToken); public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => _stream.WriteAsync(buffer, offset, count, cancellationToken); public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => _stream.BeginRead(buffer, offset, count, callback, state); public override int EndRead(IAsyncResult asyncResult) => _stream.EndRead(asyncResult); public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => _stream.BeginWrite(buffer, offset, count, callback, state); public override void EndWrite(IAsyncResult asyncResult) => _stream.EndWrite(asyncResult); public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) => _stream.CopyToAsync(destination, bufferSize, cancellationToken); public override object InitializeLifetimeService() { throw new NotSupportedException(); } public override ObjRef CreateObjRef(Type requestedType) { throw new NotSupportedException(); } public override void Close() { _service.Dispose(); _stream.Close(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); _service.Dispose(); _stream.Dispose(); } } } } }
aelij/roslyn
src/EditorFeatures/TestUtilities/Remote/InProcRemostHostClient.cs
C#
apache-2.0
11,474
// Copyright 2022 Google LLC // // 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. // Generated code. DO NOT EDIT! namespace Google.Cloud.Monitoring.V3.Snippets { // [START monitoring_v3_generated_UptimeCheckService_CreateUptimeCheckConfig_sync_flattened] using Google.Cloud.Monitoring.V3; public sealed partial class GeneratedUptimeCheckServiceClientSnippets { /// <summary>Snippet for CreateUptimeCheckConfig</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void CreateUptimeCheckConfig() { // Create client UptimeCheckServiceClient uptimeCheckServiceClient = UptimeCheckServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; UptimeCheckConfig uptimeCheckConfig = new UptimeCheckConfig(); // Make the request UptimeCheckConfig response = uptimeCheckServiceClient.CreateUptimeCheckConfig(parent, uptimeCheckConfig); } } // [END monitoring_v3_generated_UptimeCheckService_CreateUptimeCheckConfig_sync_flattened] }
googleapis/google-cloud-dotnet
apis/Google.Cloud.Monitoring.V3/Google.Cloud.Monitoring.V3.GeneratedSnippets/UptimeCheckServiceClient.CreateUptimeCheckConfigSnippet.g.cs
C#
apache-2.0
1,776
package org.goodsManagement.service.impl.PoiUtils; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.goodsManagement.po.GetGoodsDto; import org.goodsManagement.vo.GetGoodsVO; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; /** * Created by lifei on 2015/9/23. */ @Component public class GetGoodsToExcel { /*public static void main(String[] args){ List<GetGoodsVO> list = new ArrayList<GetGoodsVO>(); GetGoodsVO a1 = new GetGoodsVO(); a1.setStaffname("大黄"); a1.setGoodname("屎"); a1.setGetnumber(2); a1.setGoodtype("一大坨"); list.add(a1); GetGoodsVO a2 = new GetGoodsVO(); a2.setStaffname("小黄"); a2.setGoodname("屎"); a2.setGetnumber(2); a2.setGoodtype("一桶"); list.add(a2); String path = "C:\\Users\\lifei\\Desktop\\getgood.xls"; GetGoodsToExcel.toExcel(list,path); System.out.println("导出完成"); }*/ /** * * @param list * 数据库表中人员领用记录的集合 * @param path * 要写入的文件的路径 */ public void addtoExcel(List<GetGoodsVO> list,String path){ HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("Outgoods"); String[] n = { "姓名", "物品名称号", "物品型号", "物品数量" }; Object[][] value = new Object[list.size() + 1][4]; for (int m = 0; m < n.length; m++) { value[0][m] = n[m]; } for (int i = 0; i < list.size(); i++) { GetGoodsVO getGoodsVOg= (GetGoodsVO) list.get(i); value[i + 1][0] = getGoodsVOg.getStaffname(); value[i + 1][1] = getGoodsVOg.getGoodname(); value[i + 1][2] = getGoodsVOg.getGoodtype(); value[i + 1][3] = getGoodsVOg.getGetnumber(); } ExcelUtils.writeArrayToExcel(wb, sheet, list.size() + 1, 4, value); ExcelUtils.writeWorkbook(wb, path); } }
sunshine-life/GoodsManagement
src/main/java/org/goodsManagement/service/impl/PoiUtils/GetGoodsToExcel.java
Java
apache-2.0
2,120
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.bean.validator.springboot; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Generated; import org.apache.camel.CamelContext; import org.apache.camel.component.bean.validator.BeanValidatorComponent; import org.apache.camel.spi.ComponentCustomizer; import org.apache.camel.spi.HasId; import org.apache.camel.spring.boot.CamelAutoConfiguration; import org.apache.camel.spring.boot.ComponentConfigurationProperties; import org.apache.camel.spring.boot.util.CamelPropertiesHelper; import org.apache.camel.spring.boot.util.ConditionalOnCamelContextAndAutoConfigurationBeans; import org.apache.camel.spring.boot.util.GroupCondition; import org.apache.camel.spring.boot.util.HierarchicalPropertiesEvaluator; import org.apache.camel.support.IntrospectionSupport; import org.apache.camel.util.ObjectHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; /** * Generated by camel-package-maven-plugin - do not edit this file! */ @Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo") @Configuration @Conditional({ConditionalOnCamelContextAndAutoConfigurationBeans.class, BeanValidatorComponentAutoConfiguration.GroupConditions.class}) @AutoConfigureAfter(CamelAutoConfiguration.class) @EnableConfigurationProperties({ComponentConfigurationProperties.class, BeanValidatorComponentConfiguration.class}) public class BeanValidatorComponentAutoConfiguration { private static final Logger LOGGER = LoggerFactory .getLogger(BeanValidatorComponentAutoConfiguration.class); @Autowired private ApplicationContext applicationContext; @Autowired private CamelContext camelContext; @Autowired private BeanValidatorComponentConfiguration configuration; @Autowired(required = false) private List<ComponentCustomizer<BeanValidatorComponent>> customizers; static class GroupConditions extends GroupCondition { public GroupConditions() { super("camel.component", "camel.component.bean-validator"); } } @Lazy @Bean(name = "bean-validator-component") @ConditionalOnMissingBean(BeanValidatorComponent.class) public BeanValidatorComponent configureBeanValidatorComponent() throws Exception { BeanValidatorComponent component = new BeanValidatorComponent(); component.setCamelContext(camelContext); Map<String, Object> parameters = new HashMap<>(); IntrospectionSupport.getProperties(configuration, parameters, null, false); for (Map.Entry<String, Object> entry : parameters.entrySet()) { Object value = entry.getValue(); Class<?> paramClass = value.getClass(); if (paramClass.getName().endsWith("NestedConfiguration")) { Class nestedClass = null; try { nestedClass = (Class) paramClass.getDeclaredField( "CAMEL_NESTED_CLASS").get(null); HashMap<String, Object> nestedParameters = new HashMap<>(); IntrospectionSupport.getProperties(value, nestedParameters, null, false); Object nestedProperty = nestedClass.newInstance(); CamelPropertiesHelper.setCamelProperties(camelContext, nestedProperty, nestedParameters, false); entry.setValue(nestedProperty); } catch (NoSuchFieldException e) { } } } CamelPropertiesHelper.setCamelProperties(camelContext, component, parameters, false); if (ObjectHelper.isNotEmpty(customizers)) { for (ComponentCustomizer<BeanValidatorComponent> customizer : customizers) { boolean useCustomizer = (customizer instanceof HasId) ? HierarchicalPropertiesEvaluator.evaluate( applicationContext.getEnvironment(), "camel.component.customizer", "camel.component.bean-validator.customizer", ((HasId) customizer).getId()) : HierarchicalPropertiesEvaluator.evaluate( applicationContext.getEnvironment(), "camel.component.customizer", "camel.component.bean-validator.customizer"); if (useCustomizer) { LOGGER.debug("Configure component {}, with customizer {}", component, customizer); customizer.customize(component); } } } return component; } }
kevinearls/camel
platforms/spring-boot/components-starter/camel-bean-validator-starter/src/main/java/org/apache/camel/component/bean/validator/springboot/BeanValidatorComponentAutoConfiguration.java
Java
apache-2.0
6,273
#ifndef _DICTIONARY_H_ #define _DICTIONARY_H_ #include <string> #include <unordered_map> #include <cinttypes> // This class represents a dictionary that maps integer values to strings. class Dictionary { public: typedef int32_t DiffType; // return value of compare function typedef uint32_t IntType; // int is enough, no need for int64 typedef std::string StringType; typedef std::unordered_map<IntType, IntType> TranslationTable; private: typedef std::unordered_map<IntType, StringType> IndexMap; typedef std::unordered_map<StringType, IntType> ReverseMap; public: typedef IndexMap::const_iterator const_iterator; private: // Mapping from ID to String IndexMap indexMap; // Mapping from String to ID ReverseMap reverseMap; // Mapping from ID to index in sorted order TranslationTable orderMap; // Next ID to be given IntType nextID; // Whether or not the dictionary has been modified since loading. bool modified; // Whether or not orderMap is valid bool orderValid; public: // Constructor Dictionary( void ); // Construct from dictionary name Dictionary( const std::string name ); // Destructor ~Dictionary( void ); // Look up an ID and get the String const char * Dereference( const IntType id ) const; // Look up a String and get the ID // Return invalid if not found IntType Lookup( const char * str, const IntType invalid ) const; // Insert a value into the Dictionary and return the ID. // Throw an error if the new ID is larger than maxID IntType Insert( const char * str, const IntType maxID ); // Integrate another dictionary into this one, and produce a translation // table for any values whose ID has changed. void Integrate( Dictionary& other, TranslationTable& trans ); // load/save dictionary from SQL // name specifies which dictionary to load/save void Load(const char* name); void Save(const char* name); // Compare two factors lexicographically. // The return value will be as follows: // first > second : retVal > 0 // first = second : retVal = 0 // first < second : retVal < 0 DiffType Compare( IntType firstID, IntType secondID ) const; const_iterator begin( void) const; const_iterator cbegin( void ) const; const_iterator end( void ) const; const_iterator cend( void ) const; private: // Helper method for reverse lookups IntType Lookup( const StringType& str, const IntType invalid ) const; // Helper method for inserting strings IntType Insert( StringType& str ); // Helper method to compute the sorted order. void ComputeOrder( void ); /* ***** Static Members ***** */ private: typedef std::unordered_map<std::string, Dictionary> DictionaryMap; // Storage for global dictionaries static DictionaryMap dicts; /* ***** Static Methods ***** */ public: static Dictionary & GetDictionary( const std::string name ); }; #endif //_DICTIONARY_H_
RayZ-O/grokit
src/DataTypes/headers/Dictionary.h
C
apache-2.0
3,061
//===- WriterUtils.cpp ----------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "WriterUtils.h" #include "lld/Common/ErrorHandler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/EndianStream.h" #include "llvm/Support/LEB128.h" #define DEBUG_TYPE "lld" using namespace llvm; using namespace llvm::wasm; namespace lld { std::string toString(ValType type) { switch (type) { case ValType::I32: return "i32"; case ValType::I64: return "i64"; case ValType::F32: return "f32"; case ValType::F64: return "f64"; case ValType::V128: return "v128"; case ValType::EXNREF: return "exnref"; case ValType::EXTERNREF: return "externref"; } llvm_unreachable("Invalid wasm::ValType"); } std::string toString(const WasmSignature &sig) { SmallString<128> s("("); for (ValType type : sig.Params) { if (s.size() != 1) s += ", "; s += toString(type); } s += ") -> "; if (sig.Returns.empty()) s += "void"; else s += toString(sig.Returns[0]); return std::string(s.str()); } std::string toString(const WasmGlobalType &type) { return (type.Mutable ? "var " : "const ") + toString(static_cast<ValType>(type.Type)); } std::string toString(const WasmEventType &type) { if (type.Attribute == WASM_EVENT_ATTRIBUTE_EXCEPTION) return "exception"; return "unknown"; } namespace wasm { void debugWrite(uint64_t offset, const Twine &msg) { LLVM_DEBUG(dbgs() << format(" | %08lld: ", offset) << msg << "\n"); } void writeUleb128(raw_ostream &os, uint64_t number, const Twine &msg) { debugWrite(os.tell(), msg + "[" + utohexstr(number) + "]"); encodeULEB128(number, os); } void writeSleb128(raw_ostream &os, int64_t number, const Twine &msg) { debugWrite(os.tell(), msg + "[" + utohexstr(number) + "]"); encodeSLEB128(number, os); } void writeBytes(raw_ostream &os, const char *bytes, size_t count, const Twine &msg) { debugWrite(os.tell(), msg + " [data[" + Twine(count) + "]]"); os.write(bytes, count); } void writeStr(raw_ostream &os, StringRef string, const Twine &msg) { debugWrite(os.tell(), msg + " [str[" + Twine(string.size()) + "]: " + string + "]"); encodeULEB128(string.size(), os); os.write(string.data(), string.size()); } void writeU8(raw_ostream &os, uint8_t byte, const Twine &msg) { debugWrite(os.tell(), msg + " [0x" + utohexstr(byte) + "]"); os << byte; } void writeU32(raw_ostream &os, uint32_t number, const Twine &msg) { debugWrite(os.tell(), msg + "[0x" + utohexstr(number) + "]"); support::endian::write(os, number, support::little); } void writeU64(raw_ostream &os, uint64_t number, const Twine &msg) { debugWrite(os.tell(), msg + "[0x" + utohexstr(number) + "]"); support::endian::write(os, number, support::little); } void writeValueType(raw_ostream &os, ValType type, const Twine &msg) { writeU8(os, static_cast<uint8_t>(type), msg + "[type: " + toString(type) + "]"); } void writeSig(raw_ostream &os, const WasmSignature &sig) { writeU8(os, WASM_TYPE_FUNC, "signature type"); writeUleb128(os, sig.Params.size(), "param Count"); for (ValType paramType : sig.Params) { writeValueType(os, paramType, "param type"); } writeUleb128(os, sig.Returns.size(), "result Count"); for (ValType returnType : sig.Returns) { writeValueType(os, returnType, "result type"); } } void writeI32Const(raw_ostream &os, int32_t number, const Twine &msg) { writeU8(os, WASM_OPCODE_I32_CONST, "i32.const"); writeSleb128(os, number, msg); } void writeI64Const(raw_ostream &os, int64_t number, const Twine &msg) { writeU8(os, WASM_OPCODE_I64_CONST, "i64.const"); writeSleb128(os, number, msg); } void writeMemArg(raw_ostream &os, uint32_t alignment, uint64_t offset) { writeUleb128(os, alignment, "alignment"); writeUleb128(os, offset, "offset"); } void writeInitExpr(raw_ostream &os, const WasmInitExpr &initExpr) { writeU8(os, initExpr.Opcode, "opcode"); switch (initExpr.Opcode) { case WASM_OPCODE_I32_CONST: writeSleb128(os, initExpr.Value.Int32, "literal (i32)"); break; case WASM_OPCODE_I64_CONST: writeSleb128(os, initExpr.Value.Int64, "literal (i64)"); break; case WASM_OPCODE_F32_CONST: writeU32(os, initExpr.Value.Float32, "literal (f32)"); break; case WASM_OPCODE_F64_CONST: writeU64(os, initExpr.Value.Float64, "literal (f64)"); break; case WASM_OPCODE_GLOBAL_GET: writeUleb128(os, initExpr.Value.Global, "literal (global index)"); break; case WASM_OPCODE_REF_NULL: writeValueType(os, ValType::EXTERNREF, "literal (externref type)"); break; default: fatal("unknown opcode in init expr: " + Twine(initExpr.Opcode)); } writeU8(os, WASM_OPCODE_END, "opcode:end"); } void writeLimits(raw_ostream &os, const WasmLimits &limits) { writeU8(os, limits.Flags, "limits flags"); writeUleb128(os, limits.Initial, "limits initial"); if (limits.Flags & WASM_LIMITS_FLAG_HAS_MAX) writeUleb128(os, limits.Maximum, "limits max"); } void writeGlobalType(raw_ostream &os, const WasmGlobalType &type) { // TODO: Update WasmGlobalType to use ValType and remove this cast. writeValueType(os, ValType(type.Type), "global type"); writeU8(os, type.Mutable, "global mutable"); } void writeGlobal(raw_ostream &os, const WasmGlobal &global) { writeGlobalType(os, global.Type); writeInitExpr(os, global.InitExpr); } void writeEventType(raw_ostream &os, const WasmEventType &type) { writeUleb128(os, type.Attribute, "event attribute"); writeUleb128(os, type.SigIndex, "sig index"); } void writeEvent(raw_ostream &os, const WasmEvent &event) { writeEventType(os, event.Type); } void writeTableType(raw_ostream &os, const llvm::wasm::WasmTable &type) { writeU8(os, WASM_TYPE_FUNCREF, "table type"); writeLimits(os, type.Limits); } void writeImport(raw_ostream &os, const WasmImport &import) { writeStr(os, import.Module, "import module name"); writeStr(os, import.Field, "import field name"); writeU8(os, import.Kind, "import kind"); switch (import.Kind) { case WASM_EXTERNAL_FUNCTION: writeUleb128(os, import.SigIndex, "import sig index"); break; case WASM_EXTERNAL_GLOBAL: writeGlobalType(os, import.Global); break; case WASM_EXTERNAL_EVENT: writeEventType(os, import.Event); break; case WASM_EXTERNAL_MEMORY: writeLimits(os, import.Memory); break; case WASM_EXTERNAL_TABLE: writeTableType(os, import.Table); break; default: fatal("unsupported import type: " + Twine(import.Kind)); } } void writeExport(raw_ostream &os, const WasmExport &export_) { writeStr(os, export_.Name, "export name"); writeU8(os, export_.Kind, "export kind"); switch (export_.Kind) { case WASM_EXTERNAL_FUNCTION: writeUleb128(os, export_.Index, "function index"); break; case WASM_EXTERNAL_GLOBAL: writeUleb128(os, export_.Index, "global index"); break; case WASM_EXTERNAL_EVENT: writeUleb128(os, export_.Index, "event index"); break; case WASM_EXTERNAL_MEMORY: writeUleb128(os, export_.Index, "memory index"); break; case WASM_EXTERNAL_TABLE: writeUleb128(os, export_.Index, "table index"); break; default: fatal("unsupported export type: " + Twine(export_.Kind)); } } } // namespace wasm } // namespace lld
google/llvm-propeller
lld/wasm/WriterUtils.cpp
C++
apache-2.0
7,617
# Copyright 2015 Rafe Kaplan # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from . import parser class Rule(parser.Parser): def __init__(self, expected_attr_type=None): self.__expected_attr_type = expected_attr_type @property def attr_type(self): if self.__expected_attr_type: return self.__expected_attr_type else: try: inner_parser = self.__parser except AttributeError: raise NotImplementedError else: return inner_parser.attr_type @property def parser(self): return self.__parser @parser.setter def parser(self, value): if self.__expected_attr_type and self.__expected_attr_type != value.attr_type: raise ValueError('Unexpected attribute type') self.__parser = parser.as_parser(value) def _parse(self, state, *args, **kwargs): with state.open_scope(*args, **kwargs): self.__parser._parse(state) def __imod__(self, other): self.parser = other return self def __call__(self, *args, **kwargs): return RuleCall(self, *args, **kwargs) class RuleCall(parser.Unary): def __init__(self, rule, *args, **kwargs): if not isinstance(rule, Rule): raise TypeError('Expected rule to be type Rule, was {}'.format(type(rule).__name__)) super(RuleCall, self).__init__(rule) self.__args = args self.__kwargs = kwargs @property def args(self): return self.__args @property def kwargs(self): return dict(self.__kwargs) def _parse(self, state): args = [state.invoke(a) for a in self.__args] kwargs = {k: state.invoke(v) for k, v in self.__kwargs.items()} self.parser._parse(state, *args, **kwargs)
slobberchops/booze
src/booze/gin/rule.py
Python
apache-2.0
2,341
package build import sbt._ import Keys._ import Def.SettingsDefinition final class MultiScalaProject private (private val projects: Map[String, Project]) extends CompositeProject { import MultiScalaProject._ val v2_11: Project = projects("2.11") val v2_12: Project = projects("2.12") val v2_13: Project = projects("2.13") def settings(ss: SettingsDefinition*): MultiScalaProject = transform(_.settings(ss: _*)) def enablePlugins(ns: Plugins*): MultiScalaProject = transform(_.enablePlugins(ns: _*)) def dependsOn(deps: ScopedMultiScalaProject*): MultiScalaProject = { def classpathDependency(d: ScopedMultiScalaProject) = strictMapValues(d.project.projects)(ClasspathDependency(_, d.configuration)) val depsByVersion: Map[String, Seq[ClasspathDependency]] = strictMapValues(deps.flatMap(classpathDependency).groupBy(_._1))(_.map(_._2)) zipped(depsByVersion)(_.dependsOn(_: _*)) } def configs(cs: Configuration*): MultiScalaProject = transform(_.configs(cs: _*)) def zippedSettings(that: MultiScalaProject)(ss: Project => SettingsDefinition): MultiScalaProject = zipped(that.projects)((p, sp) => p.settings(ss(sp))) def zippedSettings(project: String)(ss: LocalProject => SettingsDefinition): MultiScalaProject = zippedSettings(Seq(project))(ps => ss(ps(0))) /** Set settings on this MultiScalaProject depending on other MultiScalaProjects by name. * * For every Scala version of this MultiScalaProject, `ss` is invoked onced * with a LocalProjects corresponding to the names in projectNames with a * suffix for that version. */ def zippedSettings(projectNames: Seq[String])( ss: Seq[LocalProject] => SettingsDefinition): MultiScalaProject = { val ps = for { (v, p) <- projects } yield { val lps = projectNames.map(pn => LocalProject(projectID(pn, v))) v -> p.settings(ss(lps)) } new MultiScalaProject(ps) } def %(configuration: String) = new ScopedMultiScalaProject(this, Some(configuration)) override def componentProjects: Seq[Project] = projects.valuesIterator.toSeq private def zipped[T](that: Map[String, T])(f: (Project, T) => Project): MultiScalaProject = { val ps = for ((v, p) <- projects) yield v -> f(p, that(v)) new MultiScalaProject(ps) } private def transform(f: Project => Project): MultiScalaProject = new MultiScalaProject(strictMapValues(projects)(f)) } final class ScopedMultiScalaProject(val project: MultiScalaProject, val configuration: Option[String]) object ScopedMultiScalaProject { implicit def fromMultiScalaProject(mp: MultiScalaProject): ScopedMultiScalaProject = new ScopedMultiScalaProject(mp, None) } object MultiScalaProject { private def strictMapValues[K, U, V](v: Map[K, U])(f: U => V): Map[K, V] = v.map(v => (v._1, f(v._2))) private final val versions = Map[String, Seq[String]]( "2.11" -> Seq("2.11.12"), "2.12" -> Seq("2.12.1", "2.12.2", "2.12.3", "2.12.4", "2.12.5", "2.12.6", "2.12.7", "2.12.8", "2.12.9", "2.12.10", "2.12.11", "2.12.12", "2.12.13", "2.12.14", "2.12.15"), "2.13" -> Seq("2.13.0", "2.13.1", "2.13.2", "2.13.3", "2.13.4", "2.13.5", "2.13.6", "2.13.7", "2.13.8"), ) val Default2_11ScalaVersion = versions("2.11").last val Default2_12ScalaVersion = versions("2.12").last val Default2_13ScalaVersion = versions("2.13").last /** The default Scala version is the default 2.12 Scala version, because it * must work for sbt plugins. */ val DefaultScalaVersion = Default2_12ScalaVersion private final val ideVersion = "2.12" private def projectID(id: String, major: String) = id + major.replace('.', '_') def apply(id: String, base: File): MultiScalaProject = { val projects = for { (major, minors) <- versions } yield { val noIDEExportSettings = if (major == ideVersion) Nil else NoIDEExport.noIDEExportSettings major -> Project(id = projectID(id, major), base = new File(base, "." + major)).settings( scalaVersion := minors.last, crossScalaVersions := minors, noIDEExportSettings, ) } new MultiScalaProject(projects).settings( sourceDirectory := baseDirectory.value.getParentFile / "src", ) } }
scala-js/scala-js
project/MultiScalaProject.scala
Scala
apache-2.0
4,271
/* # Licensed Materials - Property of IBM # Copyright IBM Corp. 2019 */ package com.ibm.streamsx.topology.internal.logging; import java.util.logging.Level; import java.util.logging.Logger; public interface Logging { /** * Set the root logging levels from Python logging integer level. * @param levelS */ public static void setRootLevels(String levelS) { int loggingLevel = Integer.valueOf(levelS); Level level; if (loggingLevel >= 40) { level = Level.SEVERE; } else if (loggingLevel >= 30) { level = Level.WARNING; } else if (loggingLevel >= 20) { level = Level.CONFIG; } else { level = Level.FINE; } Logger.getLogger("").setLevel(level); } }
ddebrunner/streamsx.topology
java/src/com/ibm/streamsx/topology/internal/logging/Logging.java
Java
apache-2.0
800
package wikokit.base.wikt.db; import android.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** Decompress ziped file. * * @see http://www.jondev.net/articles/Unzipping_Files_with_Android_%28Programmatically%29 */ public class Decompressor { private String _zipFile; private String _location; public Decompressor(String zipFile, String location) { _zipFile = zipFile; _location = location; _dirChecker(""); } public void unzip() { try { FileInputStream fin = new FileInputStream(_zipFile); ZipInputStream zin = new ZipInputStream(fin); ZipEntry ze = null; while ((ze = zin.getNextEntry()) != null) { Log.v("Decompress", "Unzipping " + ze.getName()); if(ze.isDirectory()) { _dirChecker(ze.getName()); } else { FileOutputStream fout = new FileOutputStream(_location + ze.getName()); for (int c = zin.read(); c != -1; c = zin.read()) { fout.write(c); } zin.closeEntry(); fout.close(); } } zin.close(); } catch(Exception e) { Log.e("Decompress", "unzip", e); } } private void _dirChecker(String dir) { File f = new File(_location + dir); if(!f.isDirectory()) { f.mkdirs(); } } }
componavt/wikokit
android/common_wiki_android/src/wikokit/base/wikt/db/Decompressor.java
Java
apache-2.0
1,533
// -------------------------------------------------------------------------------------------------------------------- // <summary> // The chat room controller. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace WebStreams.Sample { using System; using System.Collections.Concurrent; using System.Reactive.Linq; using System.Reactive.Subjects; using Dapr.WebStreams.Server; /// <summary> /// The chat room controller. /// </summary> [RoutePrefix("/chat")] public class ChatRoomController { /// <summary> /// The chat rooms. /// </summary> private readonly ConcurrentDictionary<string, ISubject<ChatEvent>> rooms = new ConcurrentDictionary<string, ISubject<ChatEvent>>(); /// <summary> /// The stream of room updates. /// </summary> private readonly ISubject<string> roomUpdates = new Subject<string>(); /// <summary> /// Joins the calling user to a chat room. /// </summary> /// <param name="room"> /// The room name. /// </param> /// <param name="user"> /// The joining user's name. /// </param> /// <param name="messages"> /// The stream of chat messages from the user. /// </param> /// <returns> /// The stream of chat events. /// </returns> [Route("join")] public IObservable<ChatEvent> JoinRoom(string room, string user, IObservable<string> messages) { // Get or create the room being requested. var roomStream = this.GetOrAddRoom(room); // Send a happy little join message. roomStream.OnNext(new ChatEvent { User = user, Message = "Joined!", Time = DateTime.UtcNow, Type = "presence" }); // Turn incoming messages into chat events and pipe them into the room. messages.Select(message => new ChatEvent { User = user, Message = message, Time = DateTime.UtcNow }) .Subscribe( roomStream.OnNext, () => roomStream.OnNext(new ChatEvent { User = user, Message = "Left.", Time = DateTime.UtcNow, Type = "presence" })); return roomStream; } /// <summary> /// Returns the stream of chat rooms. /// </summary> /// <returns>The stream of chat rooms.</returns> [Route("rooms")] public IObservable<string> GetRooms() { var result = new ReplaySubject<string>(); this.roomUpdates.Subscribe(result); foreach (var channel in this.rooms.Keys) { result.OnNext(channel); } return result; } /// <summary> /// Returns the chat room with the provided <paramref name="name"/>. /// </summary> /// <param name="name"> /// The room name. /// </param> /// <returns> /// The chat room with the provided <paramref name="name"/>. /// </returns> private ISubject<ChatEvent> GetOrAddRoom(string name) { var added = default(ISubject<ChatEvent>); var result = this.rooms.GetOrAdd( name, _ => added = new ReplaySubject<ChatEvent>(100)); // If a new room was actually added, fire an update. if (result.Equals(added)) { this.roomUpdates.OnNext(name); } return result; } } }
daprlabs/WebStreamSamples
ChatRoomController.cs
C#
apache-2.0
4,330
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.jms.tx; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.spring.CamelSpringTestSupport; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Simple unit test for transaction client EIP pattern and JMS. */ public class JMSTransactionalClientWithRollbackTest extends CamelSpringTestSupport { protected ClassPathXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext( "/org/apache/camel/component/jms/tx/JMSTransactionalClientWithRollbackTest.xml"); } @Test public void testTransactionSuccess() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.expectedBodiesReceived("Bye World"); // success at 3rd attempt mock.message(0).header("count").isEqualTo(3); template.sendBody("activemq:queue:okay", "Hello World"); mock.assertIsSatisfied(); } public static class MyProcessor implements Processor { private int count; public void process(Exchange exchange) throws Exception { exchange.getIn().setBody("Bye World"); exchange.getIn().setHeader("count", ++count); } } }
Fabryprog/camel
components/camel-jms/src/test/java/org/apache/camel/component/jms/tx/JMSTransactionalClientWithRollbackTest.java
Java
apache-2.0
2,206
(function() { var head = document.head || document.getElementsByTagName('head')[0]; var style = null; var mobileScreenWidth = 768; // Make sure this value is equal to the width of .wy-nav-content in overrides.css. var initialContentWidth = 960; // Make sure this value is equal to the width of .wy-nav-side in theme.css. var sideWidth = 300; // Keeps the current width of .wy-nav-content. var contentWidth = initialContentWidth; // Centers the page content dynamically. function centerPage() { if (style) { head.removeChild(style); style = null; } var windowWidth = window.innerWidth; if (windowWidth <= mobileScreenWidth) { return; } var leftMargin = Math.max(0, (windowWidth - sideWidth - contentWidth) / 2); var scrollbarWidth = document.body ? windowWidth - document.body.clientWidth : 0; var css = ''; css += '.wy-nav-side { left: ' + leftMargin + 'px; }'; css += "\n"; css += '.wy-nav-content-wrap { margin-left: ' + (sideWidth + leftMargin) + 'px; }'; css += "\n"; css += '.github-fork-ribbon { margin-right: ' + (leftMargin - scrollbarWidth) + 'px; }'; css += "\n"; var newStyle = document.createElement('style'); newStyle.type = 'text/css'; if (newStyle.styleSheet) { newStyle.styleSheet.cssText = css; } else { newStyle.appendChild(document.createTextNode(css)); } head.appendChild(newStyle); style = newStyle; } centerPage(); window.addEventListener('resize', centerPage); // Adjust the position of the 'fork me at GitHub' ribbon after document.body is available, // so that we can calculate the width of the scroll bar correctly. window.addEventListener('DOMContentLoaded', centerPage); // Allow a user to drag the left or right edge of the content to resize the content. if (interact) { interact('.wy-nav-content').resizable({ edges: {left: true, right: true, bottom: false, top: false}, modifiers: [ interact.modifiers.restrictEdges({ outer: 'parent', endOnly: true }), interact.modifiers.restrictSize({ min: { width: initialContentWidth, height: 0 } }) ] }).on('resizemove', function (event) { var style = event.target.style; // Double the amount of change because the page is centered. contentWidth += event.deltaRect.width * 2; style.maxWidth = contentWidth + 'px'; centerPage(); }); } })();
trustin/sphinx-gradle-plugin
src/site/sphinx/_static/center_page.js
JavaScript
apache-2.0
2,528
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Apache License Version 2.0. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* package com.microsoft.uprove; import java.util.Arrays; /** * Specifies a U-Prove token. */ public class UProveToken { private byte[] issuerParametersUID; private byte[] publicKey; private byte[] tokenInformation; private byte[] proverInformation; private byte[] sigmaZ; private byte[] sigmaC; private byte[] sigmaR; private boolean isDeviceProtected = false; /** * Constructs a new U-Prove token. */ public UProveToken() { super(); } /** * Constructs a new U-Prove token. * @param issuerParametersUID an issuer parameters UID. * @param publicKey a public key. * @param tokenInformation a token information value. * @param proverInformation a prover information value. * @param sigmaZ a sigmaZ value. * @param sigmaC a sigmaC value. * @param sigmaR a sigmaR value. * @param isDeviceProtected indicates if the token is Device-protected. */ public UProveToken(byte[] issuerParametersUID, byte[] publicKey, byte[] tokenInformation, byte[] proverInformation, byte[] sigmaZ, byte[] sigmaC, byte[] sigmaR, boolean isDeviceProtected) { super(); this.issuerParametersUID = issuerParametersUID; this.publicKey = publicKey; this.tokenInformation = tokenInformation; this.proverInformation = proverInformation; this.sigmaZ = sigmaZ; this.sigmaC = sigmaC; this.sigmaR = sigmaR; this.isDeviceProtected = isDeviceProtected; } /** * Gets the issuer parameters UID value. * @return the issuerParameters UID value. */ public byte[] getIssuerParametersUID() { return issuerParametersUID; } /** * Sets the issuer parameters UID value. * @param issuerParametersUID the issuerParameters UID value to set. */ public void setIssuerParametersUID(byte[] issuerParametersUID) { this.issuerParametersUID = issuerParametersUID; } /** * Gets the public key value. * @return the publicKey value. */ public byte[] getPublicKey() { return publicKey; } /** * Sets the public key value. * @param publicKey the public key value to set. */ public void setPublicKey(byte[] publicKey) { this.publicKey = publicKey; } /** * Gets the token information value. * @return the token information value. */ public byte[] getTokenInformation() { return tokenInformation; } /** * Sets the token information value. * @param tokenInformation the token information value to set. */ public void setTokenInformation(byte[] tokenInformation) { this.tokenInformation = tokenInformation; } /** * Gets the prover information value. * @return the prover information value. */ public byte[] getProverInformation() { return proverInformation; } /** * Sets the prover information value. * @param proverInformation the prover information value to set. */ public void setProverInformation(byte[] proverInformation) { this.proverInformation = proverInformation; } /** * Gets the sigmaZ value. * @return the sigmaZ value. */ public byte[] getSigmaZ() { return sigmaZ; } /** * Sets the sigmaZ value. * @param sigmaZ the sigmaZ value to set. */ public void setSigmaZ(byte[] sigmaZ) { this.sigmaZ = sigmaZ; } /** * Gets the sigmaC value. * @return the sigmaC value. */ public byte[] getSigmaC() { return sigmaC; } /** * Sets the sigmaC value. * @param sigmaC the sigmaC value to set. */ public void setSigmaC(byte[] sigmaC) { this.sigmaC = sigmaC; } /** * Gets the sigmaR value. * @return the sigmaR value. */ public byte[] getSigmaR() { return sigmaR; } /** * Sets the sigmaR value. * @param sigmaR the sigmaR value to set. */ public void setSigmaR(byte[] sigmaR) { this.sigmaR = sigmaR; } /** * Returns true if the token is Device-protected, false otherwise. * @return the Device-protected boolean. */ boolean isDeviceProtected() { return isDeviceProtected; } /** * Sets the boolean indicating if the token is Device-protected. * @param isDeviceProtected true if the token is Device-protected. */ void setIsDeviceProtected(boolean isDeviceProtected) { this.isDeviceProtected = isDeviceProtected; } /** * Indicates whether some other object is "equal to" this one. * @param o the reference object with which to compare. * @return <code>true</code> if this object is the same as the * <code>o</code> argument; <code>false</code> otherwise. */ public boolean equals(final Object o) { if (o == this) { return true; } if (!(o instanceof UProveToken)) { return false; } UProveToken upt = (UProveToken) o; return Arrays.equals(this.issuerParametersUID, upt.issuerParametersUID) && Arrays.equals(this.publicKey, upt.publicKey) && Arrays.equals(this.tokenInformation, upt.tokenInformation) && Arrays.equals(this.proverInformation, upt.proverInformation) && Arrays.equals(this.sigmaZ, upt.sigmaZ) && Arrays.equals(this.sigmaC, upt.sigmaC) && Arrays.equals(this.sigmaR, upt.sigmaR) && this.isDeviceProtected == upt.isDeviceProtected; } /** * Returns a hash code value for the object. * @return a hash code value for the object. */ public int hashCode() { int result = 237; result = 201 * result + Arrays.hashCode(this.issuerParametersUID); result = 201 * result + Arrays.hashCode(this.publicKey); result = 201 * result + Arrays.hashCode(this.tokenInformation); result = 201 * result + Arrays.hashCode(this.proverInformation); result = 201 * result + Arrays.hashCode(this.sigmaZ); result = 201 * result + Arrays.hashCode(this.sigmaC); result = 201 * result + Arrays.hashCode(this.sigmaR); result = result + (this.isDeviceProtected ? 201 : 0); return result; } }
albdum/uprove
src/main/java/com/microsoft/uprove/UProveToken.java
Java
apache-2.0
6,515
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ namespace Google\Service\ServiceNetworking; class LabelDescriptor extends \Google\Model { /** * @var string */ public $description; /** * @var string */ public $key; /** * @var string */ public $valueType; /** * @param string */ public function setDescription($description) { $this->description = $description; } /** * @return string */ public function getDescription() { return $this->description; } /** * @param string */ public function setKey($key) { $this->key = $key; } /** * @return string */ public function getKey() { return $this->key; } /** * @param string */ public function setValueType($valueType) { $this->valueType = $valueType; } /** * @return string */ public function getValueType() { return $this->valueType; } } // Adding a class alias for backwards compatibility with the previous class name. class_alias(LabelDescriptor::class, 'Google_Service_ServiceNetworking_LabelDescriptor');
googleapis/google-api-php-client-services
src/ServiceNetworking/LabelDescriptor.php
PHP
apache-2.0
1,643
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.olio.webapp.cache; /** * The cache interface provides all operations necessary for the cache. * We could have extended java.util.Map but that would make a lot of * unnecessary work for the scope of this project. We can always implement that * interface later if desired. */ public interface Cache { /** * Gets the cached value based on a key. * @param key The key * @return The cached object, or null if none is available */ Object get(String key); /** * Sets a cached item using a key. * @param key The key * @param value The object to cache. */ void put(String key, Object value); /** * Sets a cached item using a key. * @param key The key * @param value The object to cache. * @param timeToLive Time to cache this object in seconds */ void put(String key, Object value, long timeToLive); /** * Invalidates a cached item using a key * @param key * @return success */ boolean invalidate(String key); /* * Check if cache needs refresh based on existence cached object and of Semaphore * @param key The key * @param cacheObjPresent false if the cache object for this key exists * @return true if the cache object needs a refresh */ boolean needsRefresh (boolean cacheObjPresent, String key); void doneRefresh (String key, long timeToNextRefresh) throws CacheException; boolean isLocal(); }
shanti/olio
webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/cache/Cache.java
Java
apache-2.0
2,298
/* * 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. */ // script.aculo.us unittest.js v1.8.0_pre1, Fri Oct 12 21:34:51 +0200 2007 // Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // (c) 2005-2007 Jon Tirsen (http://www.tirsen.com) // (c) 2005-2007 Michael Schuerig (http://www.schuerig.de/michael/) // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ // experimental, Firefox-only Event.simulateMouse = function(element, eventName) { var options = Object.extend({ pointerX: 0, pointerY: 0, buttons: 0, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false }, arguments[2] || {}); var oEvent = document.createEvent("MouseEvents"); oEvent.initMouseEvent(eventName, true, true, document.defaultView, options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 0, $(element)); if(this.mark) Element.remove(this.mark); this.mark = document.createElement('div'); this.mark.appendChild(document.createTextNode(" ")); document.body.appendChild(this.mark); this.mark.style.position = 'absolute'; this.mark.style.top = options.pointerY + "px"; this.mark.style.left = options.pointerX + "px"; this.mark.style.width = "5px"; this.mark.style.height = "5px;"; this.mark.style.borderTop = "1px solid red;" this.mark.style.borderLeft = "1px solid red;" if(this.step) alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options)); $(element).dispatchEvent(oEvent); }; // Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2. // You need to downgrade to 1.0.4 for now to get this working // See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much Event.simulateKey = function(element, eventName) { var options = Object.extend({ ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, keyCode: 0, charCode: 0 }, arguments[2] || {}); var oEvent = document.createEvent("KeyEvents"); oEvent.initKeyEvent(eventName, true, true, window, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.keyCode, options.charCode ); $(element).dispatchEvent(oEvent); }; Event.simulateKeys = function(element, command) { for(var i=0; i<command.length; i++) { Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)}); } }; var Test = {} Test.Unit = {}; // security exception workaround Test.Unit.inspect = Object.inspect; Test.Unit.Logger = Class.create(); Test.Unit.Logger.prototype = { initialize: function(log) { this.log = $(log); if (this.log) { this._createLogTable(); } }, start: function(testName) { if (!this.log) return; this.testName = testName; this.lastLogLine = document.createElement('tr'); this.statusCell = document.createElement('td'); this.nameCell = document.createElement('td'); this.nameCell.className = "nameCell"; this.nameCell.appendChild(document.createTextNode(testName)); this.messageCell = document.createElement('td'); this.lastLogLine.appendChild(this.statusCell); this.lastLogLine.appendChild(this.nameCell); this.lastLogLine.appendChild(this.messageCell); this.loglines.appendChild(this.lastLogLine); }, finish: function(status, summary) { if (!this.log) return; this.lastLogLine.className = status; this.statusCell.innerHTML = status; this.messageCell.innerHTML = this._toHTML(summary); this.addLinksToResults(); }, message: function(message) { if (!this.log) return; this.messageCell.innerHTML = this._toHTML(message); }, summary: function(summary) { if (!this.log) return; this.logsummary.innerHTML = this._toHTML(summary); }, _createLogTable: function() { this.log.innerHTML = '<div id="logsummary"></div>' + '<table id="logtable">' + '<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>' + '<tbody id="loglines"></tbody>' + '</table>'; this.logsummary = $('logsummary') this.loglines = $('loglines'); }, _toHTML: function(txt) { return txt.escapeHTML().replace(/\n/g,"<br/>"); }, addLinksToResults: function(){ $$("tr.failed .nameCell").each( function(td){ // todo: limit to children of this.log td.title = "Run only this test" Event.observe(td, 'click', function(){ window.location.search = "?tests=" + td.innerHTML;}); }); $$("tr.passed .nameCell").each( function(td){ // todo: limit to children of this.log td.title = "Run all tests" Event.observe(td, 'click', function(){ window.location.search = "";}); }); } } Test.Unit.Runner = Class.create(); Test.Unit.Runner.prototype = { initialize: function(testcases) { this.options = Object.extend({ testLog: 'testlog' }, arguments[1] || {}); this.options.resultsURL = this.parseResultsURLQueryParameter(); this.options.tests = this.parseTestsQueryParameter(); if (this.options.testLog) { this.options.testLog = $(this.options.testLog) || null; } if(this.options.tests) { this.tests = []; for(var i = 0; i < this.options.tests.length; i++) { if(/^test/.test(this.options.tests[i])) { this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"])); } } } else { if (this.options.test) { this.tests = [new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])]; } else { this.tests = []; for(var testcase in testcases) { if(/^test/.test(testcase)) { this.tests.push( new Test.Unit.Testcase( this.options.context ? ' -> ' + this.options.titles[testcase] : testcase, testcases[testcase], testcases["setup"], testcases["teardown"] )); } } } } this.currentTest = 0; this.logger = new Test.Unit.Logger(this.options.testLog); setTimeout(this.runTests.bind(this), 1000); }, parseResultsURLQueryParameter: function() { return window.location.search.parseQuery()["resultsURL"]; }, parseTestsQueryParameter: function(){ if (window.location.search.parseQuery()["tests"]){ return window.location.search.parseQuery()["tests"].split(','); }; }, // Returns: // "ERROR" if there was an error, // "FAILURE" if there was a failure, or // "SUCCESS" if there was neither getResult: function() { var hasFailure = false; for(var i=0;i<this.tests.length;i++) { if (this.tests[i].errors > 0) { return "ERROR"; } if (this.tests[i].failures > 0) { hasFailure = true; } } if (hasFailure) { return "FAILURE"; } else { return "SUCCESS"; } }, postResults: function() { if (this.options.resultsURL) { new Ajax.Request(this.options.resultsURL, { method: 'get', parameters: 'result=' + this.getResult(), asynchronous: false }); } }, runTests: function() { var test = this.tests[this.currentTest]; if (!test) { // finished! this.postResults(); this.logger.summary(this.summary()); return; } if(!test.isWaiting) { this.logger.start(test.name); } test.run(); if(test.isWaiting) { this.logger.message("Waiting for " + test.timeToWait + "ms"); setTimeout(this.runTests.bind(this), test.timeToWait || 1000); } else { this.logger.finish(test.status(), test.summary()); this.currentTest++; // tail recursive, hopefully the browser will skip the stackframe this.runTests(); } }, summary: function() { var assertions = 0; var failures = 0; var errors = 0; var messages = []; for(var i=0;i<this.tests.length;i++) { assertions += this.tests[i].assertions; failures += this.tests[i].failures; errors += this.tests[i].errors; } return ( (this.options.context ? this.options.context + ': ': '') + this.tests.length + " tests, " + assertions + " assertions, " + failures + " failures, " + errors + " errors"); } } Test.Unit.Assertions = Class.create(); Test.Unit.Assertions.prototype = { initialize: function() { this.assertions = 0; this.failures = 0; this.errors = 0; this.messages = []; }, summary: function() { return ( this.assertions + " assertions, " + this.failures + " failures, " + this.errors + " errors" + "\n" + this.messages.join("\n")); }, pass: function() { this.assertions++; }, fail: function(message) { this.failures++; this.messages.push("Failure: " + message); }, info: function(message) { this.messages.push("Info: " + message); }, error: function(error) { this.errors++; this.messages.push(error.name + ": "+ error.message + "(" + Test.Unit.inspect(error) +")"); }, status: function() { if (this.failures > 0) return 'failed'; if (this.errors > 0) return 'error'; return 'passed'; }, assert: function(expression) { var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"'; try { expression ? this.pass() : this.fail(message); } catch(e) { this.error(e); } }, assertEqual: function(expected, actual) { var message = arguments[2] || "assertEqual"; try { (expected == actual) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertInspect: function(expected, actual) { var message = arguments[2] || "assertInspect"; try { (expected == actual.inspect()) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertEnumEqual: function(expected, actual) { var message = arguments[2] || "assertEnumEqual"; try { $A(expected).length == $A(actual).length && expected.zip(actual).all(function(pair) { return pair[0] == pair[1] }) ? this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) + ', actual ' + Test.Unit.inspect(actual)); } catch(e) { this.error(e); } }, assertNotEqual: function(expected, actual) { var message = arguments[2] || "assertNotEqual"; try { (expected != actual) ? this.pass() : this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertIdentical: function(expected, actual) { var message = arguments[2] || "assertIdentical"; try { (expected === actual) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertNotIdentical: function(expected, actual) { var message = arguments[2] || "assertNotIdentical"; try { !(expected === actual) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertNull: function(obj) { var message = arguments[1] || 'assertNull' try { (obj==null) ? this.pass() : this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"'); } catch(e) { this.error(e); } }, assertMatch: function(expected, actual) { var message = arguments[2] || 'assertMatch'; var regex = new RegExp(expected); try { (regex.exec(actual)) ? this.pass() : this.fail(message + ' : regex: "' + Test.Unit.inspect(expected) + ' did not match: ' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertHidden: function(element) { var message = arguments[1] || 'assertHidden'; this.assertEqual("none", element.style.display, message); }, assertNotNull: function(object) { var message = arguments[1] || 'assertNotNull'; this.assert(object != null, message); }, assertType: function(expected, actual) { var message = arguments[2] || 'assertType'; try { (actual.constructor == expected) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + (actual.constructor) + '"'); } catch(e) { this.error(e); } }, assertNotOfType: function(expected, actual) { var message = arguments[2] || 'assertNotOfType'; try { (actual.constructor != expected) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + (actual.constructor) + '"'); } catch(e) { this.error(e); } }, assertInstanceOf: function(expected, actual) { var message = arguments[2] || 'assertInstanceOf'; try { (actual instanceof expected) ? this.pass() : this.fail(message + ": object was not an instance of the expected type"); } catch(e) { this.error(e); } }, assertNotInstanceOf: function(expected, actual) { var message = arguments[2] || 'assertNotInstanceOf'; try { !(actual instanceof expected) ? this.pass() : this.fail(message + ": object was an instance of the not expected type"); } catch(e) { this.error(e); } }, assertRespondsTo: function(method, obj) { var message = arguments[2] || 'assertRespondsTo'; try { (obj[method] && typeof obj[method] == 'function') ? this.pass() : this.fail(message + ": object doesn't respond to [" + method + "]"); } catch(e) { this.error(e); } }, assertReturnsTrue: function(method, obj) { var message = arguments[2] || 'assertReturnsTrue'; try { var m = obj[method]; if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)]; m() ? this.pass() : this.fail(message + ": method returned false"); } catch(e) { this.error(e); } }, assertReturnsFalse: function(method, obj) { var message = arguments[2] || 'assertReturnsFalse'; try { var m = obj[method]; if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)]; !m() ? this.pass() : this.fail(message + ": method returned true"); } catch(e) { this.error(e); } }, assertRaise: function(exceptionName, method) { var message = arguments[2] || 'assertRaise'; try { method(); this.fail(message + ": exception expected but none was raised"); } catch(e) { ((exceptionName == null) || (e.name==exceptionName)) ? this.pass() : this.error(e); } }, assertElementsMatch: function() { var expressions = $A(arguments), elements = $A(expressions.shift()); if (elements.length != expressions.length) { this.fail('assertElementsMatch: size mismatch: ' + elements.length + ' elements, ' + expressions.length + ' expressions'); return false; } elements.zip(expressions).all(function(pair, index) { var element = $(pair.first()), expression = pair.last(); if (element.match(expression)) return true; this.fail('assertElementsMatch: (in index ' + index + ') expected ' + expression.inspect() + ' but got ' + element.inspect()); }.bind(this)) && this.pass(); }, assertElementMatches: function(element, expression) { this.assertElementsMatch([element], expression); }, benchmark: function(operation, iterations) { var startAt = new Date(); (iterations || 1).times(operation); var timeTaken = ((new Date())-startAt); this.info((arguments[2] || 'Operation') + ' finished ' + iterations + ' iterations in ' + (timeTaken/1000)+'s' ); return timeTaken; }, _isVisible: function(element) { element = $(element); if(!element.parentNode) return true; this.assertNotNull(element); if(element.style && Element.getStyle(element, 'display') == 'none') return false; return this._isVisible(element.parentNode); }, assertNotVisible: function(element) { this.assert(!this._isVisible(element), Test.Unit.inspect(element) + " was not hidden and didn't have a hidden parent either. " + ("" || arguments[1])); }, assertVisible: function(element) { this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1])); }, benchmark: function(operation, iterations) { var startAt = new Date(); (iterations || 1).times(operation); var timeTaken = ((new Date())-startAt); this.info((arguments[2] || 'Operation') + ' finished ' + iterations + ' iterations in ' + (timeTaken/1000)+'s' ); return timeTaken; } } Test.Unit.Testcase = Class.create(); Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), { initialize: function(name, test, setup, teardown) { Test.Unit.Assertions.prototype.initialize.bind(this)(); this.name = name; if(typeof test == 'string') { test = test.gsub(/(\.should[^\(]+\()/,'#{0}this,'); test = test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)'); this.test = function() { eval('with(this){'+test+'}'); } } else { this.test = test || function() {}; } this.setup = setup || function() {}; this.teardown = teardown || function() {}; this.isWaiting = false; this.timeToWait = 1000; }, wait: function(time, nextPart) { this.isWaiting = true; this.test = nextPart; this.timeToWait = time; }, run: function() { try { try { if (!this.isWaiting) this.setup.bind(this)(); this.isWaiting = false; this.test.bind(this)(); } finally { if(!this.isWaiting) { this.teardown.bind(this)(); } } } catch(e) { this.error(e); } } }); // *EXPERIMENTAL* BDD-style testing to please non-technical folk // This draws many ideas from RSpec http://rspec.rubyforge.org/ Test.setupBDDExtensionMethods = function(){ var METHODMAP = { shouldEqual: 'assertEqual', shouldNotEqual: 'assertNotEqual', shouldEqualEnum: 'assertEnumEqual', shouldBeA: 'assertType', shouldNotBeA: 'assertNotOfType', shouldBeAn: 'assertType', shouldNotBeAn: 'assertNotOfType', shouldBeNull: 'assertNull', shouldNotBeNull: 'assertNotNull', shouldBe: 'assertReturnsTrue', shouldNotBe: 'assertReturnsFalse', shouldRespondTo: 'assertRespondsTo' }; var makeAssertion = function(assertion, args, object) { this[assertion].apply(this,(args || []).concat([object])); } Test.BDDMethods = {}; $H(METHODMAP).each(function(pair) { Test.BDDMethods[pair.key] = function() { var args = $A(arguments); var scope = args.shift(); makeAssertion.apply(scope, [pair.value, args, this]); }; }); [Array.prototype, String.prototype, Number.prototype, Boolean.prototype].each( function(p){ Object.extend(p, Test.BDDMethods) } ); } Test.context = function(name, spec, log){ Test.setupBDDExtensionMethods(); var compiledSpec = {}; var titles = {}; for(specName in spec) { switch(specName){ case "setup": case "teardown": compiledSpec[specName] = spec[specName]; break; default: var testName = 'test'+specName.gsub(/\s+/,'-').camelize(); var body = spec[specName].toString().split('\n').slice(1); if(/^\{/.test(body[0])) body = body.slice(1); body.pop(); body = body.map(function(statement){ return statement.strip() }); compiledSpec[testName] = body.join('\n'); titles[testName] = specName; } } new Test.Unit.Runner(compiledSpec, { titles: titles, testLog: log || 'testlog', context: name }); };
shanti/olio
webapp/rails/trunk/vendor/plugins/rspec/story_server/prototype/javascripts/unittest.js
JavaScript
apache-2.0
21,009
/* * Copyright (c) 2020 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ /* Performs initialization of Direction Finding in Host */ int le_df_init(void); void hci_df_prepare_connectionless_iq_report(struct net_buf *buf, struct bt_df_per_adv_sync_iq_samples_report *report, struct bt_le_per_adv_sync **per_adv_sync_to_report);
finikorg/zephyr
subsys/bluetooth/host/direction_internal.h
C
apache-2.0
371
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_45) on Thu Nov 13 21:22:01 UTC 2014 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class org.apache.hadoop.yarn.applications.distributedshell.ApplicationMaster (Apache Hadoop Main 2.6.0 API) </TITLE> <META NAME="date" CONTENT="2014-11-13"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.yarn.applications.distributedshell.ApplicationMaster (Apache Hadoop Main 2.6.0 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/yarn/applications/distributedshell/ApplicationMaster.html" title="class in org.apache.hadoop.yarn.applications.distributedshell"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/hadoop/yarn/applications/distributedshell//class-useApplicationMaster.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ApplicationMaster.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.hadoop.yarn.applications.distributedshell.ApplicationMaster</B></H2> </CENTER> No usage of org.apache.hadoop.yarn.applications.distributedshell.ApplicationMaster <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/yarn/applications/distributedshell/ApplicationMaster.html" title="class in org.apache.hadoop.yarn.applications.distributedshell"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/hadoop/yarn/applications/distributedshell//class-useApplicationMaster.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ApplicationMaster.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2014 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved. </BODY> </HTML>
SAT-Hadoop/hadoop-2.6.0
share/doc/hadoop/api/org/apache/hadoop/yarn/applications/distributedshell/class-use/ApplicationMaster.html
HTML
apache-2.0
6,562
// Copyright 2004 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry.vlib.ejb; import java.rmi.RemoteException; import javax.ejb.EJBObject; /** * Remote interface for the BookQuery stateless session bean. * * @version $Id$ * @author Howard Lewis Ship * **/ public interface IBookQuery extends EJBObject { /** * Returns the total number of results rows in the query. * **/ public int getResultCount() throws RemoteException; /** * Returns a selected subset of the results. * **/ public Book[] get(int offset, int length) throws RemoteException; /** * Performs a query of books with the matching title and (optionally) publisher. * * @param parameters defines subset of books to return. * @param sortOrdering order of items in result set. * **/ public int masterQuery(MasterQueryParameters parameters, SortOrdering sortOrdering) throws RemoteException; /** * Queries on books owned by a given person. * **/ public int ownerQuery(Integer ownerPK, SortOrdering sortOrdering) throws RemoteException; /** * Queries on books held by a given person. * **/ public int holderQuery(Integer holderPK, SortOrdering sortOrdering) throws RemoteException; /** * Queries the list of books held by the borrower but not owned by the borrower. * **/ public int borrowerQuery(Integer borrowerPK, SortOrdering sortOrdering) throws RemoteException; }
apache/tapestry3
tapestry-examples/VlibBeans/src/org/apache/tapestry/vlib/ejb/IBookQuery.java
Java
apache-2.0
2,080
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.structuralsearch.impl.matcher.compiler; import com.intellij.codeInsight.template.Template; import com.intellij.codeInsight.template.TemplateManager; import com.intellij.dupLocator.util.NodeFilter; import com.intellij.lang.Language; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiErrorElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiRecursiveElementWalkingVisitor; import com.intellij.psi.impl.source.tree.LeafElement; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.util.PsiUtilCore; import com.intellij.structuralsearch.*; import com.intellij.structuralsearch.impl.matcher.CompiledPattern; import com.intellij.structuralsearch.impl.matcher.MatcherImplUtil; import com.intellij.structuralsearch.impl.matcher.PatternTreeContext; import com.intellij.structuralsearch.impl.matcher.filters.LexicalNodesFilter; import com.intellij.structuralsearch.impl.matcher.handlers.MatchingHandler; import com.intellij.structuralsearch.impl.matcher.handlers.SubstitutionHandler; import com.intellij.structuralsearch.impl.matcher.predicates.*; import com.intellij.structuralsearch.plugin.ui.Configuration; import com.intellij.util.IncorrectOperationException; import com.intellij.util.SmartList; import gnu.trove.TIntArrayList; import gnu.trove.TIntHashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Compiles the handlers for usability */ public class PatternCompiler { private static CompileContext lastTestingContext; public static CompiledPattern compilePattern(final Project project, final MatchOptions options) throws MalformedPatternException, NoMatchFoundException, UnsupportedOperationException { FileType fileType = options.getFileType(); assert fileType instanceof LanguageFileType; Language language = ((LanguageFileType)fileType).getLanguage(); StructuralSearchProfile profile = StructuralSearchUtil.getProfileByLanguage(language); assert profile != null; CompiledPattern result = profile.createCompiledPattern(); final String[] prefixes = result.getTypedVarPrefixes(); assert prefixes.length > 0; final CompileContext context = new CompileContext(result, options, project); if (ApplicationManager.getApplication().isUnitTestMode()) lastTestingContext = context; try { List<PsiElement> elements = compileByAllPrefixes(project, options, result, context, prefixes); final CompiledPattern pattern = context.getPattern(); checkForUnknownVariables(pattern, elements); pattern.setNodes(elements); if (context.getSearchHelper().doOptimizing() && context.getSearchHelper().isScannedSomething()) { final Set<PsiFile> set = context.getSearchHelper().getFilesSetToScan(); final List<PsiFile> filesToScan = new SmartList<>(); final GlobalSearchScope scope = (GlobalSearchScope)options.getScope(); for (final PsiFile file : set) { if (!scope.contains(file.getVirtualFile())) { continue; } filesToScan.add(file); } if (filesToScan.size() == 0) { throw new NoMatchFoundException(SSRBundle.message("ssr.will.not.find.anything", scope.getDisplayName())); } result.setScope(new LocalSearchScope(PsiUtilCore.toPsiElementArray(filesToScan))); } } finally { context.clear(); } return result; } private static void checkForUnknownVariables(final CompiledPattern pattern, List<PsiElement> elements) { for (PsiElement element : elements) { element.accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(PsiElement element) { if (element.getUserData(CompiledPattern.HANDLER_KEY) != null) { return; } super.visitElement(element); if (!(element instanceof LeafElement) || !pattern.isTypedVar(element)) { return; } final MatchingHandler handler = pattern.getHandler(pattern.getTypedVarString(element)); if (handler == null) { throw new MalformedPatternException(); } } }); } } public static String getLastFindPlan() { return ((TestModeOptimizingSearchHelper)lastTestingContext.getSearchHelper()).getSearchPlan(); } @NotNull private static List<PsiElement> compileByAllPrefixes(Project project, MatchOptions options, CompiledPattern pattern, CompileContext context, String[] applicablePrefixes) throws MalformedPatternException { if (applicablePrefixes.length == 0) { return Collections.emptyList(); } List<PsiElement> elements = doCompile(project, options, pattern, new ConstantPrefixProvider(applicablePrefixes[0]), context); if (elements.isEmpty()) { return elements; } final PsiFile file = elements.get(0).getContainingFile(); if (file == null) { return elements; } final PsiElement last = elements.get(elements.size() - 1); final Pattern[] patterns = new Pattern[applicablePrefixes.length]; for (int i = 0; i < applicablePrefixes.length; i++) { patterns[i] = Pattern.compile(StructuralSearchUtil.shieldRegExpMetaChars(applicablePrefixes[i]) + "\\w+\\b"); } final int[] varEndOffsets = findAllTypedVarOffsets(file, patterns); final int patternEndOffset = last.getTextRange().getEndOffset(); if (elements.size() == 0 || checkErrorElements(file, patternEndOffset, patternEndOffset, varEndOffsets, true) != Boolean.TRUE) { return elements; } final int varCount = varEndOffsets.length; final String[] prefixSequence = new String[varCount]; for (int i = 0; i < varCount; i++) { prefixSequence[i] = applicablePrefixes[0]; } final List<PsiElement> finalElements = compileByPrefixes(project, options, pattern, context, applicablePrefixes, patterns, prefixSequence, 0); return finalElements != null ? finalElements : doCompile(project, options, pattern, new ConstantPrefixProvider(applicablePrefixes[0]), context); } @Nullable private static List<PsiElement> compileByPrefixes(Project project, MatchOptions options, CompiledPattern pattern, CompileContext context, String[] applicablePrefixes, Pattern[] substitutionPatterns, String[] prefixSequence, int index) throws MalformedPatternException { if (index >= prefixSequence.length) { final List<PsiElement> elements = doCompile(project, options, pattern, new ArrayPrefixProvider(prefixSequence), context); if (elements.isEmpty()) { return elements; } final PsiElement parent = elements.get(0).getParent(); final PsiElement last = elements.get(elements.size() - 1); final int[] varEndOffsets = findAllTypedVarOffsets(parent.getContainingFile(), substitutionPatterns); final int patternEndOffset = last.getTextRange().getEndOffset(); return checkErrorElements(parent, patternEndOffset, patternEndOffset, varEndOffsets, false) != Boolean.TRUE ? elements : null; } String[] alternativeVariant = null; for (String applicablePrefix : applicablePrefixes) { prefixSequence[index] = applicablePrefix; List<PsiElement> elements = doCompile(project, options, pattern, new ArrayPrefixProvider(prefixSequence), context); if (elements.isEmpty()) { return elements; } final PsiFile file = elements.get(0).getContainingFile(); if (file == null) { return elements; } final int[] varEndOffsets = findAllTypedVarOffsets(file, substitutionPatterns); final int offset = varEndOffsets[index]; final int patternEndOffset = elements.get(elements.size() - 1).getTextRange().getEndOffset(); final Boolean result = checkErrorElements(file, offset, patternEndOffset, varEndOffsets, false); if (result == Boolean.TRUE) { continue; } if (result == Boolean.FALSE || (result == null && alternativeVariant == null)) { final List<PsiElement> finalElements = compileByPrefixes(project, options, pattern, context, applicablePrefixes, substitutionPatterns, prefixSequence, index + 1); if (finalElements != null) { if (result == Boolean.FALSE) { return finalElements; } alternativeVariant = new String[prefixSequence.length]; System.arraycopy(prefixSequence, 0, alternativeVariant, 0, prefixSequence.length); } } } return alternativeVariant != null ? compileByPrefixes(project, options, pattern, context, applicablePrefixes, substitutionPatterns, alternativeVariant, index + 1) : null; } @NotNull private static int[] findAllTypedVarOffsets(final PsiFile file, final Pattern[] substitutionPatterns) { final TIntHashSet result = new TIntHashSet(); file.accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(PsiElement element) { super.visitElement(element); if (element instanceof LeafElement) { final String text = element.getText(); for (Pattern pattern : substitutionPatterns) { final Matcher matcher = pattern.matcher(text); while (matcher.find()) { result.add(element.getTextRange().getStartOffset() + matcher.end()); } } } } }); final int[] resultArray = result.toArray(); Arrays.sort(resultArray); return resultArray; } /** * False: there are no error elements before offset, except patternEndOffset * Null: there are only error elements located exactly after template variables or at the end of the pattern * True: otherwise */ @Nullable private static Boolean checkErrorElements(PsiElement element, final int offset, final int patternEndOffset, final int[] varEndOffsets, final boolean strict) { final TIntArrayList errorOffsets = new TIntArrayList(); final boolean[] containsErrorTail = {false}; final TIntHashSet varEndOffsetsSet = new TIntHashSet(varEndOffsets); element.accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitErrorElement(PsiErrorElement element) { super.visitErrorElement(element); final int startOffset = element.getTextRange().getStartOffset(); if ((strict || !varEndOffsetsSet.contains(startOffset)) && startOffset != patternEndOffset) { errorOffsets.add(startOffset); } if (startOffset == offset) { containsErrorTail[0] = true; } } }); for (int i = 0; i < errorOffsets.size(); i++) { final int errorOffset = errorOffsets.get(i); if (errorOffset <= offset) { return true; } } return containsErrorTail[0] ? null : false; } private interface PrefixProvider { String getPrefix(int varIndex); } private static class ConstantPrefixProvider implements PrefixProvider { private final String myPrefix; ConstantPrefixProvider(String prefix) { myPrefix = prefix; } @Override public String getPrefix(int varIndex) { return myPrefix; } } private static class ArrayPrefixProvider implements PrefixProvider { private final String[] myPrefixes; ArrayPrefixProvider(String[] prefixes) { myPrefixes = prefixes; } @Override public String getPrefix(int varIndex) { if (varIndex >= myPrefixes.length) return null; return myPrefixes[varIndex]; } } private static List<PsiElement> doCompile(Project project, MatchOptions options, CompiledPattern result, PrefixProvider prefixProvider, CompileContext context) throws MalformedPatternException { result.clearHandlers(); final StringBuilder buf = new StringBuilder(); Template template = TemplateManager.getInstance(project).createTemplate("","",options.getSearchPattern()); int segmentsCount = template.getSegmentsCount(); String text = template.getTemplateText(); int prevOffset = 0; for(int i=0;i<segmentsCount;++i) { final int offset = template.getSegmentOffset(i); final String name = template.getSegmentName(i); final String prefix = prefixProvider.getPrefix(i); if (prefix == null) { throw new MalformedPatternException(); } buf.append(text.substring(prevOffset,offset)); buf.append(prefix); buf.append(name); MatchVariableConstraint constraint = options.getVariableConstraint(name); if (constraint==null) { // we do not edited the constraints constraint = new MatchVariableConstraint(); constraint.setName( name ); options.addVariableConstraint(constraint); } SubstitutionHandler handler = result.createSubstitutionHandler( name, prefix + name, constraint.isPartOfSearchResults(), constraint.getMinCount(), constraint.getMaxCount(), constraint.isGreedy() ); if(constraint.isWithinHierarchy()) { handler.setSubtype(true); } if(constraint.isStrictlyWithinHierarchy()) { handler.setStrictSubtype(true); } MatchPredicate predicate; if (!StringUtil.isEmptyOrSpaces(constraint.getRegExp())) { predicate = new RegExpPredicate( constraint.getRegExp(), options.isCaseSensitiveMatch(), name, constraint.isWholeWordsOnly(), constraint.isPartOfSearchResults() ); if (constraint.isInvertRegExp()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.isReference()) { predicate = new ReferencePredicate( constraint.getNameOfReferenceVar() ); if (constraint.isInvertReference()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } addExtensionPredicates(options, constraint, handler); addScriptConstraint(project, name, constraint, handler); if (!StringUtil.isEmptyOrSpaces(constraint.getContainsConstraint())) { predicate = new ContainsPredicate(name, constraint.getContainsConstraint()); if (constraint.isInvertContainsConstraint()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (!StringUtil.isEmptyOrSpaces(constraint.getWithinConstraint())) { assert false; } prevOffset = offset; } MatchVariableConstraint constraint = options.getVariableConstraint(Configuration.CONTEXT_VAR_NAME); if (constraint != null) { SubstitutionHandler handler = result.createSubstitutionHandler( Configuration.CONTEXT_VAR_NAME, Configuration.CONTEXT_VAR_NAME, constraint.isPartOfSearchResults(), constraint.getMinCount(), constraint.getMaxCount(), constraint.isGreedy() ); if (!StringUtil.isEmptyOrSpaces(constraint.getWithinConstraint())) { MatchPredicate predicate = new WithinPredicate(constraint.getWithinConstraint(), options.getFileType(), project); if (constraint.isInvertWithinConstraint()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } addExtensionPredicates(options, constraint, handler); addScriptConstraint(project, Configuration.CONTEXT_VAR_NAME, constraint, handler); } buf.append(text.substring(prevOffset,text.length())); PsiElement[] matchStatements; try { matchStatements = MatcherImplUtil.createTreeFromText(buf.toString(), PatternTreeContext.Block, options.getFileType(), options.getDialect(), options.getPatternContext(), project, false); if (matchStatements.length==0) throw new MalformedPatternException(); } catch (IncorrectOperationException e) { throw new MalformedPatternException(e.getMessage()); } NodeFilter filter = LexicalNodesFilter.getInstance(); GlobalCompilingVisitor compilingVisitor = new GlobalCompilingVisitor(); compilingVisitor.compile(matchStatements,context); List<PsiElement> elements = new SmartList<>(); for (PsiElement matchStatement : matchStatements) { if (!filter.accepts(matchStatement)) { elements.add(matchStatement); } } new DeleteNodesAction(compilingVisitor.getLexicalNodes()).run(); return elements; } private static void addExtensionPredicates(MatchOptions options, MatchVariableConstraint constraint, SubstitutionHandler handler) { Set<MatchPredicate> predicates = new LinkedHashSet<>(); for (MatchPredicateProvider matchPredicateProvider : Extensions.getExtensions(MatchPredicateProvider.EP_NAME)) { matchPredicateProvider.collectPredicates(constraint, handler.getName(), options, predicates); } for (MatchPredicate matchPredicate : predicates) { addPredicate(handler, matchPredicate); } } private static void addScriptConstraint(Project project, String name, MatchVariableConstraint constraint, SubstitutionHandler handler) throws MalformedPatternException { if (constraint.getScriptCodeConstraint()!= null && constraint.getScriptCodeConstraint().length() > 2) { final String script = StringUtil.unquoteString(constraint.getScriptCodeConstraint()); final String problem = ScriptSupport.checkValidScript(script); if (problem != null) { throw new MalformedPatternException("Script constraint for " + constraint.getName() + " has problem " + problem); } addPredicate(handler, new ScriptPredicate(project, name, script)); } } private static void addPredicate(SubstitutionHandler handler, MatchPredicate predicate) { if (handler.getPredicate()==null) { handler.setPredicate(predicate); } else { handler.setPredicate(new AndPredicate(handler.getPredicate(), predicate)); } } }
apixandru/intellij-community
platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/PatternCompiler.java
Java
apache-2.0
20,077
package examples.model; import java.util.ArrayList; import java.util.Collection; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; @Entity public class Department { @Id private int id; private String name; @OneToMany(mappedBy="department") private Collection<Employee> employees; public Department() { employees = new ArrayList<Employee>(); } public int getId() { return id; } public String getName() { return name; } public Collection<Employee> getEmployees() { return employees; } public String toString() { return "Department no: " + getId() + ", name: " + getName(); } }
velmuruganvelayutham/jpa
examples/Chapter7/02-namedQueryExample/src/model/examples/model/Department.java
Java
apache-2.0
759
##===- lib/Transforms/NaCl/Makefile-------------------------*- Makefile -*-===## # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # ##===----------------------------------------------------------------------===## LEVEL = ../../.. LIBRARYNAME = LLVMNaClTransforms BUILD_ARCHIVE = 1 include $(LEVEL)/Makefile.common
slightperturbation/Cobalt
ext/emsdk_portable/clang/tag-e1.34.1/src/lib/Transforms/NaCl/Makefile
Makefile
apache-2.0
439
/** * @file * CSS for Cesium Cartesian3. */ div.form-item table .form-type-textfield, div.form-item table .form-type-textfield * { display: inline-block; }
maikuru/cesium-drupal
cesium_cartesian3/cesium_cartesian3.css
CSS
apache-2.0
163
export const FILLPATTERN = { none: '', crossHatched: 'Crosshatched', hatched: 'Hatched', solid: 'Solid' }; export const STROKEPATTERN = { none: '', dashed: 'Dashed', dotted: 'Dotted', solid: 'Solid' }; export const ALTITUDEMODE = { NONE: '', ABSOLUTE: 'Absolute', RELATIVE_TO_GROUND: 'Relative to ground', CLAMP_TO_GROUND: 'Clamp to ground' }; export const ICONSIZE = { none: '', verySmall: 'Very Small', small: 'Small', medium: 'Medium', large: 'Large', extraLarge: 'Extra Large' }; export const ACMATTRIBUTES = { innerRadius: 'Inner Radius', leftAzimuth: 'Left Azimuth', rightAzimuth: 'Right Azimuth', minAlt: 'Minimum Altitude', maxAlt: 'Maximum Altitude', leftWidth: 'Left Width', rightWidth: 'Right Width', radius: 'Radius', turn: 'Turn', width: 'Width' }; export const WMSVERSION = { WMS: 'none', WMS1_1: '1.0', WMS1_1_1: '1.1.1', WMS1_3_0: '1.3.0' }; export const WMTSVERSION = { WMTS: 'none', WMTS1_0_0: '1.0.0' };
missioncommand/emp3-web
src/validation/js/constants/PropertyConstants.js
JavaScript
apache-2.0
997
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- using System; using System.IO; namespace Microsoft.WindowsAzure.MobileServices { /// <summary> /// Provides access to platform specific functionality for the current client platform. /// </summary> public class CurrentPlatform : IPlatform { /// <summary> /// You must call this method from your application in order to ensure /// that this platform specific assembly is included in your app. /// </summary> public static void Init() { } /// <summary> /// Returns a platform-specific implemention of application storage. /// </summary> IApplicationStorage IPlatform.ApplicationStorage { get { return ApplicationStorage.Instance; } } /// <summary> /// Returns a platform-specific implemention of platform information. /// </summary> IPlatformInformation IPlatform.PlatformInformation { get { return PlatformInformation.Instance; } } /// <summary> /// Returns a platform-specific implementation of a utility class /// that provides functionality for manipulating /// <see cref="System.Linq.Expressions.Expression"/> instances. /// </summary> IExpressionUtility IPlatform.ExpressionUtility { get { return ExpressionUtility.Instance; } } /// <summary> /// Returns a platform-specific implementation of a utility class /// that provides functionality for platform-specifc push capabilities. /// </summary> IPushUtility IPlatform.PushUtility { get { return Microsoft.WindowsAzure.MobileServices.PushUtility.Instance; } } /// <summary> /// Returns a platform-specific path for storing offline databases /// that are not fully-qualified. /// </summary> string IPlatform.DefaultDatabasePath { get { return Environment.GetFolderPath(Environment.SpecialFolder.Personal); } } /// <summary> /// Retrieves an ApplicationStorage where all items stored are segmented from other stored items /// </summary> /// <param name="name">The name of the segemented area in application storage</param> /// <returns>The specific instance of that segment</returns> IApplicationStorage IPlatform.GetNamedApplicationStorage(string name) { return new ApplicationStorage(name); } /// <summary> /// Ensures that a file exists, creating it if necessary /// </summary> /// <param name="path">The fully-qualified pathname to check</param> public void EnsureFileExists(string path) { if (!File.Exists(path)) { File.Create(path); } } } }
MatkovIvan/azure-mobile-apps-net-client
src/Microsoft.Azure.Mobile.Client/Platforms/ios/CurrentPlatform.cs
C#
apache-2.0
3,139
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ namespace Google\Service\ChromePolicy; class GoogleChromePolicyV1PolicySchemaFieldDescription extends \Google\Collection { protected $collection_key = 'nestedFieldDescriptions'; /** * @var string */ public $description; /** * @var string */ public $field; protected $fieldDependenciesType = GoogleChromePolicyV1PolicySchemaFieldDependencies::class; protected $fieldDependenciesDataType = 'array'; /** * @var string */ public $inputConstraint; protected $knownValueDescriptionsType = GoogleChromePolicyV1PolicySchemaFieldKnownValueDescription::class; protected $knownValueDescriptionsDataType = 'array'; protected $nestedFieldDescriptionsType = GoogleChromePolicyV1PolicySchemaFieldDescription::class; protected $nestedFieldDescriptionsDataType = 'array'; /** * @param string */ public function setDescription($description) { $this->description = $description; } /** * @return string */ public function getDescription() { return $this->description; } /** * @param string */ public function setField($field) { $this->field = $field; } /** * @return string */ public function getField() { return $this->field; } /** * @param GoogleChromePolicyV1PolicySchemaFieldDependencies[] */ public function setFieldDependencies($fieldDependencies) { $this->fieldDependencies = $fieldDependencies; } /** * @return GoogleChromePolicyV1PolicySchemaFieldDependencies[] */ public function getFieldDependencies() { return $this->fieldDependencies; } /** * @param string */ public function setInputConstraint($inputConstraint) { $this->inputConstraint = $inputConstraint; } /** * @return string */ public function getInputConstraint() { return $this->inputConstraint; } /** * @param GoogleChromePolicyV1PolicySchemaFieldKnownValueDescription[] */ public function setKnownValueDescriptions($knownValueDescriptions) { $this->knownValueDescriptions = $knownValueDescriptions; } /** * @return GoogleChromePolicyV1PolicySchemaFieldKnownValueDescription[] */ public function getKnownValueDescriptions() { return $this->knownValueDescriptions; } /** * @param GoogleChromePolicyV1PolicySchemaFieldDescription[] */ public function setNestedFieldDescriptions($nestedFieldDescriptions) { $this->nestedFieldDescriptions = $nestedFieldDescriptions; } /** * @return GoogleChromePolicyV1PolicySchemaFieldDescription[] */ public function getNestedFieldDescriptions() { return $this->nestedFieldDescriptions; } } // Adding a class alias for backwards compatibility with the previous class name. class_alias(GoogleChromePolicyV1PolicySchemaFieldDescription::class, 'Google_Service_ChromePolicy_GoogleChromePolicyV1PolicySchemaFieldDescription');
googleapis/google-api-php-client-services
src/ChromePolicy/GoogleChromePolicyV1PolicySchemaFieldDescription.php
PHP
apache-2.0
3,468
#dcwp-avatar {float: left; display: block; width: 32px; height: 32px; background: url(images/dc_icon32.png) no-repeat 0 0; margin: 0 5px 0 0;} .dcwp-box.postbox {margin-bottom: 10px;} .dcwp-box .hndle {margin-bottom: 10px;} .dcwp-box p, .dcwp-box ul, .widget .widget-inside p.dcwp-box {padding: 0 10px; margin: 0 0 3px 0; line-height: 1.5em;} .dcwp-box ul.bullet, ul.dcwp-rss {list-style: square; margin-left: 15px;} .dcwp-form {padding: 0 10px;} .dcwp-intro {padding: 10px;} .dcwp-form li {display: block; width: 100%; overflow: hidden; margin: 0 0 5px 0; padding: 5px 0; clear: both; } .dcwp-form li h4 {margin: 15px 0 0 0;} .dcwp-form li label {float: left; width: 25%; display: block; padding: 5px 0 0 0;} span.dcwp-note {display: block; padding: 5px 0 0 25%; font-size: 11px;} label span.dcwp-note {padding: 2px 0 0 0; font-size: 11px;} .dcwp-checkbox {} .dcwp-rss-item {} .dcwp-icon-rss {} .dcwp-icon-twitter {} .dcwp-input-l {width: 70%;} .dcwp-input-m {width: 50%;} .dcwp-input-s {width: 30%;} .dcwp-textarea {width: 70%;} #social-media-tabs-donatebox.dcwp-box {border: 1px solid #016f02; background: #fff;} #social-media-tabs-donatebox.dcwp-box h3 {color: #016f02; padding: 7px 15px;} #social-media-tabs-donatebox.dcwp-box p {padding: 0 7px;} #form-dcwp-donate {text-align: center; padding-bottom: 10px;} /* Widgets */ .dcwp-widget-text {width: 98%; height: 65px;} .dcwp-widget-input {width: 100%;} .dcwp-widget-label {display: block;} p.dcwp-row {margin-bottom: 3px; width: 100%; overflow: hidden;} p.dcwp-row.half {width: 50%; float: left;} p.dcwp-row label {float: left; width: 70px; padding-top: 3px; display: block;} .dcsmt-ul li {width: 100%; overflow: hidden;} .dcsmt-ul .dcwp-widget-input, .dcsmt-ul h4.left {float: left; width: 60%;} .dcsmt-ul select, .dcsmt-ul h4.right {float: right; width: 35%;} .dcsmt-ul h4 {margin: 0;} .dcsmt-ul label {display: none;} .dcsmt-ul select, .dcsmt-ul .dcwp-widget-input {font-size: 11px;} /* Share */ .dcwp-box ul#dc-share {width: 100%; overflow: hidden; margin: 0; padding: 0; line-height: 1em;} .dcwp-box ul#dc-share li {float: left; padding: 0 3px; margin: 0; height: 75px;} /* Plugin Specific */ #dcsmt_redirect {width: 140px;} .dcwp-form li.dcsmt-icon {position: relative; width: 48%; float: left; height: 26px; clear: none; margin-right: 2%;} .dcwp-form li.dcsmt-icon label {text-transform: capitalize;} .dcsmt-icon img {position: absolute; top: 0; right: 0;}
peter-watters/WebPortfolio
physiodublin/wp-content/plugins/social-media-tabs/css/dcsmt_admin.css
CSS
apache-2.0
2,428
package water.jdbc; import org.junit.Test; import org.junit.runner.RunWith; import water.Key; import water.Keyed; import water.fvec.Frame; import water.runner.CloudSize; import water.runner.H2ORunner; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.junit.Assert.*; @RunWith(H2ORunner.class) @CloudSize(1) public class SQLManagerKeyOverwiteTest { @Test public void nextKeyHasRightPrefixAndPostfix() { final String prefix = "foo"; final String postfix = "bar"; final Key<Frame> key = SQLManager.nextTableKey(prefix, postfix); assertTrue(key.toString().startsWith(prefix)); assertTrue(key.toString().endsWith(postfix)); } @Test public void nextKeyKeyHasNoWhitechars() { final Key<Frame> key = SQLManager.nextTableKey("f o o ", "b a r"); assertFalse(key.toString().contains("\\W")); } @Test public void makeRandomKeyCreatesUniqueKeys() { final int count = 1000; final long actualCount = IntStream.range(0, count) .boxed() .parallel() .map(i -> SQLManager.nextTableKey("foo", "bar")) .map(Key::toString) .count(); assertEquals(count, actualCount); } }
michalkurka/h2o-3
h2o-core/src/test/java/water/jdbc/SQLManagerKeyOverwiteTest.java
Java
apache-2.0
1,246
<?php namespace EventEspresso\core\services\commands\registration; use EventEspresso\core\services\commands\Command; if ( ! defined( 'EVENT_ESPRESSO_VERSION' ) ) { exit( 'No direct script access allowed' ); } /** * Class SingleRegistrationCommand * DTO for passing data a single EE_Registration object to a CommandHandler * * @package Event Espresso * @author Brent Christensen * @since 4.9.0 */ abstract class SingleRegistrationCommand extends Command { /** * @var \EE_Registration $registration */ private $registration; /** * CancelRegistrationAndTicketLineItemCommand constructor. * * @param \EE_Registration $registration */ public function __construct( \EE_Registration $registration ) { $this->registration = $registration; } /** * @return \EE_Registration */ public function registration() { return $this->registration; } } // End of file SingleRegistrationCommand.php // Location: /SingleRegistrationCommand.php
yoanngern/iahm_2016
wp-content/plugins/event-espresso-core-reg/core/services/commands/registration/SingleRegistrationCommand.php
PHP
apache-2.0
998
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ /** * Service definition for FactCheckTools (v1alpha1). * * <p> </p> * * <p> * For more information about this service, see the API * <a href="https://developers.google.com/fact-check/tools/api/" target="_blank">Documentation</a> * </p> * * @author Google, Inc. */ class Google_Service_FactCheckTools extends Google_Service { /** View your email address. */ const USERINFO_EMAIL = "https://www.googleapis.com/auth/userinfo.email"; public $claims; public $pages; /** * Constructs the internal representation of the FactCheckTools service. * * @param Google_Client $client The client used to deliver requests. * @param string $rootUrl The root URL used for requests to the service. */ public function __construct(Google_Client $client, $rootUrl = null) { parent::__construct($client); $this->rootUrl = $rootUrl ?: 'https://factchecktools.googleapis.com/'; $this->servicePath = ''; $this->batchPath = 'batch'; $this->version = 'v1alpha1'; $this->serviceName = 'factchecktools'; $this->claims = new Google_Service_FactCheckTools_Resource_Claims( $this, $this->serviceName, 'claims', array( 'methods' => array( 'search' => array( 'path' => 'v1alpha1/claims:search', 'httpMethod' => 'GET', 'parameters' => array( 'languageCode' => array( 'location' => 'query', 'type' => 'string', ), 'maxAgeDays' => array( 'location' => 'query', 'type' => 'integer', ), 'offset' => array( 'location' => 'query', 'type' => 'integer', ), 'pageSize' => array( 'location' => 'query', 'type' => 'integer', ), 'pageToken' => array( 'location' => 'query', 'type' => 'string', ), 'query' => array( 'location' => 'query', 'type' => 'string', ), 'reviewPublisherSiteFilter' => array( 'location' => 'query', 'type' => 'string', ), ), ), ) ) ); $this->pages = new Google_Service_FactCheckTools_Resource_Pages( $this, $this->serviceName, 'pages', array( 'methods' => array( 'create' => array( 'path' => 'v1alpha1/pages', 'httpMethod' => 'POST', 'parameters' => array(), ),'delete' => array( 'path' => 'v1alpha1/{+name}', 'httpMethod' => 'DELETE', 'parameters' => array( 'name' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ),'get' => array( 'path' => 'v1alpha1/{+name}', 'httpMethod' => 'GET', 'parameters' => array( 'name' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ),'list' => array( 'path' => 'v1alpha1/pages', 'httpMethod' => 'GET', 'parameters' => array( 'offset' => array( 'location' => 'query', 'type' => 'integer', ), 'organization' => array( 'location' => 'query', 'type' => 'string', ), 'pageSize' => array( 'location' => 'query', 'type' => 'integer', ), 'pageToken' => array( 'location' => 'query', 'type' => 'string', ), 'url' => array( 'location' => 'query', 'type' => 'string', ), ), ),'update' => array( 'path' => 'v1alpha1/{+name}', 'httpMethod' => 'PUT', 'parameters' => array( 'name' => array( 'location' => 'path', 'type' => 'string', 'required' => true, ), ), ), ) ) ); } }
tsugiproject/tsugi
vendor/google/apiclient-services/src/Google/Service/FactCheckTools.php
PHP
apache-2.0
5,227
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.impl.statistics; import com.intellij.execution.Executor; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationType; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.execution.executors.ExecutorGroup; import com.intellij.execution.target.TargetEnvironmentAwareRunProfile; import com.intellij.execution.target.TargetEnvironmentConfiguration; import com.intellij.execution.target.TargetEnvironmentType; import com.intellij.execution.target.TargetEnvironmentsManager; import com.intellij.internal.statistic.IdeActivityDefinition; import com.intellij.internal.statistic.StructuredIdeActivity; import com.intellij.internal.statistic.eventLog.EventLogGroup; import com.intellij.internal.statistic.eventLog.events.*; import com.intellij.internal.statistic.eventLog.validator.ValidationResultType; import com.intellij.internal.statistic.eventLog.validator.rules.EventContext; import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule; import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector; import com.intellij.internal.statistic.utils.PluginInfo; import com.intellij.internal.statistic.utils.PluginInfoDetectorKt; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.concurrency.NonUrgentExecutor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; import static com.intellij.execution.impl.statistics.RunConfigurationTypeUsagesCollector.createFeatureUsageData; public final class RunConfigurationUsageTriggerCollector extends CounterUsagesCollector { public static final String GROUP_NAME = "run.configuration.exec"; private static final EventLogGroup GROUP = new EventLogGroup(GROUP_NAME, 62); private static final ObjectEventField ADDITIONAL_FIELD = EventFields.createAdditionalDataField(GROUP_NAME, "started"); private static final StringEventField EXECUTOR = EventFields.StringValidatedByCustomRule("executor", "run_config_executor"); private static final StringEventField TARGET = EventFields.StringValidatedByCustomRule("target", RunConfigurationUsageTriggerCollector.RunTargetValidator.RULE_ID); private static final EnumEventField<RunConfigurationFinishType> FINISH_TYPE = EventFields.Enum("finish_type", RunConfigurationFinishType.class); private static final IdeActivityDefinition ACTIVITY_GROUP = GROUP.registerIdeActivity(null, new EventField<?>[]{ADDITIONAL_FIELD, EXECUTOR, TARGET, RunConfigurationTypeUsagesCollector.FACTORY_FIELD, RunConfigurationTypeUsagesCollector.ID_FIELD, EventFields.PluginInfo}, new EventField<?>[]{FINISH_TYPE}); public static final VarargEventId UI_SHOWN_STAGE = ACTIVITY_GROUP.registerStage("ui.shown"); @Override public EventLogGroup getGroup() { return GROUP; } @NotNull public static StructuredIdeActivity trigger(@NotNull Project project, @NotNull ConfigurationFactory factory, @NotNull Executor executor, @Nullable RunConfiguration runConfiguration) { return ACTIVITY_GROUP .startedAsync(project, () -> ReadAction.nonBlocking(() -> buildContext(project, factory, executor, runConfiguration)) .expireWith(project) .submit(NonUrgentExecutor.getInstance())); } private static @NotNull List<EventPair<?>> buildContext(@NotNull Project project, @NotNull ConfigurationFactory factory, @NotNull Executor executor, @Nullable RunConfiguration runConfiguration) { final ConfigurationType configurationType = factory.getType(); List<EventPair<?>> eventPairs = createFeatureUsageData(configurationType, factory); ExecutorGroup<?> group = ExecutorGroup.getGroupIfProxy(executor); eventPairs.add(EXECUTOR.with(group != null ? group.getId() : executor.getId())); if (runConfiguration instanceof FusAwareRunConfiguration) { List<EventPair<?>> additionalData = ((FusAwareRunConfiguration)runConfiguration).getAdditionalUsageData(); ObjectEventData objectEventData = new ObjectEventData(additionalData); eventPairs.add(ADDITIONAL_FIELD.with(objectEventData)); } if (runConfiguration instanceof TargetEnvironmentAwareRunProfile) { String defaultTargetName = ((TargetEnvironmentAwareRunProfile)runConfiguration).getDefaultTargetName(); if (defaultTargetName != null) { TargetEnvironmentConfiguration target = TargetEnvironmentsManager.getInstance(project).getTargets().findByName(defaultTargetName); if (target != null) { eventPairs.add(TARGET.with(target.getTypeId())); } } } return eventPairs; } public static void logProcessFinished(@Nullable StructuredIdeActivity activity, RunConfigurationFinishType finishType) { if (activity != null) { activity.finished(() -> Collections.singletonList(FINISH_TYPE.with(finishType))); } } public static class RunConfigurationExecutorUtilValidator extends CustomValidationRule { @Override public boolean acceptRuleId(@Nullable String ruleId) { return "run_config_executor".equals(ruleId); } @NotNull @Override protected ValidationResultType doValidate(@NotNull String data, @NotNull EventContext context) { for (Executor executor : Executor.EXECUTOR_EXTENSION_NAME.getExtensions()) { if (StringUtil.equals(executor.getId(), data)) { final PluginInfo info = PluginInfoDetectorKt.getPluginInfo(executor.getClass()); return info.isSafeToReport() ? ValidationResultType.ACCEPTED : ValidationResultType.THIRD_PARTY; } } return ValidationResultType.REJECTED; } } public static class RunTargetValidator extends CustomValidationRule { public static final String RULE_ID = "run_target"; @Override public boolean acceptRuleId(@Nullable String ruleId) { return RULE_ID.equals(ruleId); } @NotNull @Override protected ValidationResultType doValidate(@NotNull String data, @NotNull EventContext context) { for (TargetEnvironmentType<?> type : TargetEnvironmentType.EXTENSION_NAME.getExtensions()) { if (StringUtil.equals(type.getId(), data)) { final PluginInfo info = PluginInfoDetectorKt.getPluginInfo(type.getClass()); return info.isSafeToReport() ? ValidationResultType.ACCEPTED : ValidationResultType.THIRD_PARTY; } } return ValidationResultType.REJECTED; } } public enum RunConfigurationFinishType {FAILED_TO_START, UNKNOWN} }
GunoH/intellij-community
platform/execution-impl/src/com/intellij/execution/impl/statistics/RunConfigurationUsageTriggerCollector.java
Java
apache-2.0
7,712
# ****************************************************************************** # Copyright 2014-2018 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ******************************************************************************
NervanaSystems/neon
neon/backends/kernels/cuda/__init__.py
Python
apache-2.0
748
/** * Copyright (c) 2010 RedEngine Ltd, http://www.redengine.co.nz. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package net.stickycode.deploy.sample.helloworld; public class HelloWorld implements Runnable { public void hello() { System.out.println("Hello World!"); } @Override public void run() { System.out.println("Hello Embedded World!"); try { Thread.sleep(5000); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
walterDurin/stickycode
net.stickycode.deploy.samples/sticky-deploy-sample-helloworld/src/main/java/net/stickycode/deploy/sample/helloworld/HelloWorld.java
Java
apache-2.0
1,097
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Kafka.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Kafka.Tests")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("66f1ff2f-b823-4438-89ce-5cbb46893242")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("Kafka.Console")] [assembly: log4net.Config.XmlConfigurator(Watch = true)]
Aware360/kafka-net
src/Kafka/Kafka.Tests/Properties/AssemblyInfo.cs
C#
apache-2.0
1,503
<include file='public:header'/> <div class="mainBt"> <ul> <li class="li1">系统</li> <li class="li2">数据库</li> <li class="li2 li3">数据库还原</li> </ul> </div> <div class="main-jsgl"> <p class="attention"><span>注意:</span>谨慎操作!</p> <div class="jsglNr"> <div class="selectNr"> <div class="left"> <a href="<{:U('database/index')}>">备份数据库</a> </div> <div class="right"> </div> </div> <form id="export-form" target="baocms_frm" method="post" action="<{:U('export')}>"> <div class="tableBox"> <table bordercolor="#e1e6eb" cellspacing="0" width="100%" border="1px" style=" border-collapse: collapse; margin:0px; vertical-align:middle; background-color:#FFF;" > <tr> <td>备份名称</td> <td>卷数</td> <td>压缩</td> <td>数据大小</td> <td>备份时间</td> <td>状态</th> <td>操作</td> </tr> <volist name="list" id="data"> <tr> <td><{$data.time|date='Ymd-His',###}></td> <td><{$data.part}></td> <td><{$data.compress}></td> <td><{$data.size|format_bytes}></td> <td><{$key}></td> <td>-</td> <td class="action"> <a class="db-import" href="<{:U('import?time='.$data['time'])}>">还原</a>&nbsp; <a class="ajax-get confirm" href="<{:U('del?time='.$data['time'])}>">删除</a> </td> </tr> </volist> </table> <{$page}> </div> </form> </div> </div> <script type="text/javascript"> $(".db-import").click(function(){ var self = this, status = "."; $.get(self.href, success, "json"); window.onbeforeunload = function(){ return "正在还原数据库,请不要关闭!" } return false; function success(data){ if(data.status){ if(data.gz){ data.info += status; if(status.length === 5){ status = "."; } else { status += "."; } } $(self).parent().prev().text(data.info); if(data.part){ $.get(self.href, {"part" : data.part, "start" : data.start}, success, "json" ); } else { window.onbeforeunload = function(){ return null; } } } else { alert(data.info); } } }); </script>
ksyydream/api_llx
Baocms/Tpl/database/import.html
HTML
apache-2.0
3,289
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.parser.rule; import lombok.Getter; import org.apache.shardingsphere.infra.rule.identifier.scope.GlobalRule; import org.apache.shardingsphere.parser.config.SQLParserRuleConfiguration; import org.apache.shardingsphere.sql.parser.api.CacheOption; /** * SQL parser rule. */ @Getter public final class SQLParserRule implements GlobalRule { private final boolean sqlCommentParseEnabled; private final CacheOption sqlStatementCache; private final CacheOption parseTreeCache; public SQLParserRule(final SQLParserRuleConfiguration ruleConfig) { sqlCommentParseEnabled = ruleConfig.isSqlCommentParseEnabled(); sqlStatementCache = ruleConfig.getSqlStatementCache(); parseTreeCache = ruleConfig.getParseTreeCache(); } @Override public String getType() { return SQLParserRule.class.getSimpleName(); } }
apache/incubator-shardingsphere
shardingsphere-kernel/shardingsphere-parser/shardingsphere-parser-core/src/main/java/org/apache/shardingsphere/parser/rule/SQLParserRule.java
Java
apache-2.0
1,720
package org.locationtech.geomesa.core.process.proximity import com.typesafe.scalalogging.slf4j.Logging import com.vividsolutions.jts.geom.GeometryFactory import org.geotools.data.Query import org.geotools.data.simple.{SimpleFeatureCollection, SimpleFeatureSource} import org.geotools.data.store.ReTypingFeatureCollection import org.geotools.factory.CommonFactoryFinder import org.geotools.feature.DefaultFeatureCollection import org.geotools.feature.visitor.{AbstractCalcResult, CalcResult, FeatureCalc} import org.geotools.process.factory.{DescribeParameter, DescribeProcess, DescribeResult} import org.geotools.util.NullProgressListener import org.locationtech.geomesa.core.data.AccumuloFeatureCollection import org.locationtech.geomesa.utils.geotools.Conversions._ import org.opengis.feature.Feature import org.opengis.feature.simple.SimpleFeature import org.opengis.filter.Filter @DescribeProcess( title = "Geomesa-enabled Proximity Search", description = "Performs a proximity search on a Geomesa feature collection using another feature collection as input" ) class ProximitySearchProcess extends Logging { @DescribeResult(description = "Output feature collection") def execute( @DescribeParameter( name = "inputFeatures", description = "Input feature collection that defines the proximity search") inputFeatures: SimpleFeatureCollection, @DescribeParameter( name = "dataFeatures", description = "The data set to query for matching features") dataFeatures: SimpleFeatureCollection, @DescribeParameter( name = "bufferDistance", description = "Buffer size in meters") bufferDistance: java.lang.Double ): SimpleFeatureCollection = { logger.info("Attempting Geomesa Proximity Search on collection type " + dataFeatures.getClass.getName) if(!dataFeatures.isInstanceOf[AccumuloFeatureCollection]) { logger.warn("The provided data feature collection type may not support geomesa proximity search: "+dataFeatures.getClass.getName) } if(dataFeatures.isInstanceOf[ReTypingFeatureCollection]) { logger.warn("WARNING: layer name in geoserver must match feature type name in geomesa") } val visitor = new ProximityVisitor(inputFeatures, dataFeatures, bufferDistance) dataFeatures.accepts(visitor, new NullProgressListener) visitor.getResult.asInstanceOf[ProximityResult].results } } class ProximityVisitor(inputFeatures: SimpleFeatureCollection, dataFeatures: SimpleFeatureCollection, bufferDistance: java.lang.Double) extends FeatureCalc with Logging { val geoFac = new GeometryFactory val ff = CommonFactoryFinder.getFilterFactory2 var manualFilter: Filter = _ val manualVisitResults = new DefaultFeatureCollection(null, dataFeatures.getSchema) // Called for non AccumuloFeactureCollections - here we use degrees for our filters // since we are manually evaluating them. def visit(feature: Feature): Unit = { manualFilter = Option(manualFilter).getOrElse(dwithinFilters("degrees")) val sf = feature.asInstanceOf[SimpleFeature] if(manualFilter.evaluate(sf)) { manualVisitResults.add(sf) } } var resultCalc: ProximityResult = new ProximityResult(manualVisitResults) override def getResult: CalcResult = resultCalc def setValue(r: SimpleFeatureCollection) = resultCalc = ProximityResult(r) def proximitySearch(source: SimpleFeatureSource, query: Query) = { logger.info("Running Geomesa Proximity Search on source type "+source.getClass.getName) val combinedFilter = ff.and(query.getFilter, dwithinFilters("meters")) source.getFeatures(combinedFilter) } def dwithinFilters(requestedUnit: String) = { import org.locationtech.geomesa.utils.geotools.Conversions.RichGeometry import scala.collection.JavaConversions._ val geomProperty = ff.property(dataFeatures.getSchema.getGeometryDescriptor.getName) val geomFilters = inputFeatures.features().map { sf => val dist: Double = requestedUnit match { case "degrees" => sf.geometry.distanceDegrees(bufferDistance) case _ => bufferDistance } ff.dwithin(geomProperty, ff.literal(sf.geometry), dist, "meters") } ff.or(geomFilters.toSeq) } } case class ProximityResult(results: SimpleFeatureCollection) extends AbstractCalcResult
jwkessi/geomesa
geomesa-core/src/main/scala/org/locationtech/geomesa/core/process/proximity/ProximitySearchProcess.scala
Scala
apache-2.0
4,530
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.hyracks.algebricks.runtime.operators.sort; import java.nio.ByteBuffer; import java.util.List; import org.apache.hyracks.algebricks.common.exceptions.NotImplementedException; import org.apache.hyracks.algebricks.runtime.operators.base.AbstractOneInputOneOutputPushRuntime; import org.apache.hyracks.algebricks.runtime.operators.base.AbstractOneInputOneOutputRuntimeFactory; import org.apache.hyracks.api.comm.IFrameWriter; import org.apache.hyracks.api.context.IHyracksTaskContext; import org.apache.hyracks.api.dataflow.value.IBinaryComparator; import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory; import org.apache.hyracks.api.dataflow.value.INormalizedKeyComputer; import org.apache.hyracks.api.dataflow.value.INormalizedKeyComputerFactory; import org.apache.hyracks.api.exceptions.HyracksDataException; import org.apache.hyracks.api.resources.IDeallocatable; import org.apache.hyracks.api.util.CleanupUtils; import org.apache.hyracks.dataflow.common.io.GeneratedRunFileReader; import org.apache.hyracks.dataflow.std.buffermanager.EnumFreeSlotPolicy; import org.apache.hyracks.dataflow.std.sort.Algorithm; import org.apache.hyracks.dataflow.std.sort.ExternalSortRunGenerator; import org.apache.hyracks.dataflow.std.sort.ExternalSortRunMerger; public class MicroSortRuntimeFactory extends AbstractOneInputOneOutputRuntimeFactory { private static final long serialVersionUID = 1L; private final int framesLimit; private final int[] sortFields; private final INormalizedKeyComputerFactory[] keyNormalizerFactories; private final IBinaryComparatorFactory[] comparatorFactories; public MicroSortRuntimeFactory(int[] sortFields, INormalizedKeyComputerFactory firstKeyNormalizerFactory, IBinaryComparatorFactory[] comparatorFactories, int[] projectionList, int framesLimit) { this(sortFields, firstKeyNormalizerFactory != null ? new INormalizedKeyComputerFactory[] { firstKeyNormalizerFactory } : null, comparatorFactories, projectionList, framesLimit); } public MicroSortRuntimeFactory(int[] sortFields, INormalizedKeyComputerFactory[] keyNormalizerFactories, IBinaryComparatorFactory[] comparatorFactories, int[] projectionList, int framesLimit) { super(projectionList); // Obs: the projection list is currently ignored. if (projectionList != null) { throw new NotImplementedException("Cannot push projection into InMemorySortRuntime."); } this.sortFields = sortFields; this.keyNormalizerFactories = keyNormalizerFactories; this.comparatorFactories = comparatorFactories; this.framesLimit = framesLimit; } @Override public AbstractOneInputOneOutputPushRuntime createOneOutputPushRuntime(final IHyracksTaskContext ctx) throws HyracksDataException { InMemorySortPushRuntime pushRuntime = new InMemorySortPushRuntime(ctx); ctx.registerDeallocatable(pushRuntime); return pushRuntime; } private class InMemorySortPushRuntime extends AbstractOneInputOneOutputPushRuntime implements IDeallocatable { final IHyracksTaskContext ctx; ExternalSortRunGenerator runsGenerator = null; ExternalSortRunMerger runsMerger = null; IFrameWriter wrappingWriter = null; private InMemorySortPushRuntime(IHyracksTaskContext ctx) { this.ctx = ctx; } @Override public void open() throws HyracksDataException { if (runsGenerator == null) { runsGenerator = new ExternalSortRunGenerator(ctx, sortFields, keyNormalizerFactories, comparatorFactories, outputRecordDesc, Algorithm.MERGE_SORT, EnumFreeSlotPolicy.LAST_FIT, framesLimit, Integer.MAX_VALUE); } // next writer will be opened later when preparing the merger isOpen = true; runsGenerator.open(); runsGenerator.getSorter().reset(); } @Override public void nextFrame(ByteBuffer buffer) throws HyracksDataException { runsGenerator.nextFrame(buffer); } @Override public void close() throws HyracksDataException { Throwable failure = null; if (isOpen) { try { if (!failed) { runsGenerator.close(); createOrResetRunsMerger(); if (runsGenerator.getRuns().isEmpty()) { wrappingWriter = runsMerger.prepareSkipMergingFinalResultWriter(writer); wrappingWriter.open(); if (runsGenerator.getSorter().hasRemaining()) { runsGenerator.getSorter().flush(wrappingWriter); } } else { wrappingWriter = runsMerger.prepareFinalMergeResultWriter(writer); wrappingWriter.open(); runsMerger.process(wrappingWriter); } } } catch (Throwable th) { failure = th; fail(th); } finally { failure = CleanupUtils.close(wrappingWriter, failure); wrappingWriter = null; } } isOpen = false; if (failure != null) { throw HyracksDataException.create(failure); } } @Override public void fail() throws HyracksDataException { failed = true; // clean up the runs if some have been generated. double close should be idempotent. if (runsGenerator != null) { List<GeneratedRunFileReader> runs = runsGenerator.getRuns(); for (int i = 0, size = runs.size(); i < size; i++) { try { runs.get(i).close(); } catch (Throwable th) { // ignore } } } if (wrappingWriter != null) { wrappingWriter.fail(); } } @Override public void deallocate() { if (runsGenerator != null) { try { runsGenerator.getSorter().close(); } catch (Exception e) { // ignore } } } private void createOrResetRunsMerger() { if (runsMerger == null) { IBinaryComparator[] comparators = new IBinaryComparator[comparatorFactories.length]; for (int i = 0; i < comparatorFactories.length; ++i) { comparators[i] = comparatorFactories[i].createBinaryComparator(); } INormalizedKeyComputer nmkComputer = keyNormalizerFactories == null ? null : keyNormalizerFactories[0].createNormalizedKeyComputer(); runsMerger = new ExternalSortRunMerger(ctx, runsGenerator.getRuns(), sortFields, comparators, nmkComputer, outputRecordDesc, framesLimit, Integer.MAX_VALUE); } else { runsMerger.reset(runsGenerator.getRuns()); } } } }
apache/incubator-asterixdb
hyracks-fullstack/algebricks/algebricks-runtime/src/main/java/org/apache/hyracks/algebricks/runtime/operators/sort/MicroSortRuntimeFactory.java
Java
apache-2.0
8,262
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.core; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import org.apache.solr.cloud.ZkController; import org.apache.solr.cloud.ZkSolrResourceLoader; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException.ErrorCode; import org.apache.solr.common.util.ExecutorUtil; import org.apache.solr.handler.RequestHandlerBase; import org.apache.solr.handler.admin.CollectionsHandler; import org.apache.solr.handler.admin.CoreAdminHandler; import org.apache.solr.handler.admin.InfoHandler; import org.apache.solr.handler.component.ShardHandlerFactory; import org.apache.solr.logging.LogWatcher; import org.apache.solr.request.SolrRequestHandler; import org.apache.solr.update.UpdateShardHandler; import org.apache.solr.util.DefaultSolrThreadFactory; import org.apache.solr.util.FileUtils; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static com.google.common.base.Preconditions.checkNotNull; /** * * @since solr 1.3 */ public class CoreContainer { protected static final Logger log = LoggerFactory.getLogger(CoreContainer.class); final SolrCores solrCores = new SolrCores(this); public static class CoreLoadFailure { public final CoreDescriptor cd; public final Exception exception; public CoreLoadFailure(CoreDescriptor cd, Exception loadFailure) { this.cd = cd; this.exception = loadFailure; } } protected final Map<String, CoreLoadFailure> coreInitFailures = new ConcurrentHashMap<>(); protected CoreAdminHandler coreAdminHandler = null; protected CollectionsHandler collectionsHandler = null; private InfoHandler infoHandler; protected Properties containerProperties; private ConfigSetService coreConfigService; protected ZkContainer zkSys = new ZkContainer(); protected ShardHandlerFactory shardHandlerFactory; private UpdateShardHandler updateShardHandler; protected LogWatcher logging = null; private CloserThread backgroundCloser = null; protected final ConfigSolr cfg; protected final SolrResourceLoader loader; protected final String solrHome; protected final CoresLocator coresLocator; private String hostName; private final JarRepository jarRepository = new JarRepository(this); public static final String CORES_HANDLER_PATH = "/admin/cores"; public static final String COLLECTIONS_HANDLER_PATH = "/admin/collections"; public static final String INFO_HANDLER_PATH = "/admin/info"; private Map<String, SolrRequestHandler> containerHandlers = new HashMap<>(); public SolrRequestHandler getRequestHandler(String path) { return RequestHandlerBase.getRequestHandler(path, containerHandlers); } public Map<String, SolrRequestHandler> getRequestHandlers(){ return this.containerHandlers; } // private ClientConnectionManager clientConnectionManager = new PoolingClientConnectionManager(); { log.info("New CoreContainer " + System.identityHashCode(this)); } /** * Create a new CoreContainer using system properties to detect the solr home * directory. The container's cores are not loaded. * @see #load() */ public CoreContainer() { this(new SolrResourceLoader(SolrResourceLoader.locateSolrHome())); } /** * Create a new CoreContainer using the given SolrResourceLoader. The container's * cores are not loaded. * @param loader the SolrResourceLoader * @see #load() */ public CoreContainer(SolrResourceLoader loader) { this(ConfigSolr.fromSolrHome(loader, loader.getInstanceDir())); } /** * Create a new CoreContainer using the given solr home directory. The container's * cores are not loaded. * @param solrHome a String containing the path to the solr home directory * @see #load() */ public CoreContainer(String solrHome) { this(new SolrResourceLoader(solrHome)); } /** * Create a new CoreContainer using the given SolrResourceLoader, * configuration and CoresLocator. The container's cores are * not loaded. * @param config a ConfigSolr representation of this container's configuration * @see #load() */ public CoreContainer(ConfigSolr config) { this(config, config.getCoresLocator()); } public CoreContainer(ConfigSolr config, CoresLocator locator) { this.loader = config.getSolrResourceLoader(); this.solrHome = loader.getInstanceDir(); this.cfg = checkNotNull(config); this.coresLocator = locator; } /** * This method allows subclasses to construct a CoreContainer * without any default init behavior. * * @param testConstructor pass (Object)null. * @lucene.experimental */ protected CoreContainer(Object testConstructor) { solrHome = null; loader = null; coresLocator = null; cfg = null; } /** * Create a new CoreContainer and load its cores * @param solrHome the solr home directory * @param configFile the file containing this container's configuration * @return a loaded CoreContainer */ public static CoreContainer createAndLoad(String solrHome, File configFile) { SolrResourceLoader loader = new SolrResourceLoader(solrHome); CoreContainer cc = new CoreContainer(ConfigSolr.fromFile(loader, configFile)); try { cc.load(); } catch (Exception e) { cc.shutdown(); throw e; } return cc; } public Properties getContainerProperties() { return containerProperties; } //------------------------------------------------------------------- // Initialization / Cleanup //------------------------------------------------------------------- /** * Load the cores defined for this CoreContainer */ public void load() { log.info("Loading cores into CoreContainer [instanceDir={}]", loader.getInstanceDir()); // add the sharedLib to the shared resource loader before initializing cfg based plugins String libDir = cfg.getSharedLibDirectory(); if (libDir != null) { File f = FileUtils.resolvePath(new File(solrHome), libDir); log.info("loading shared library: " + f.getAbsolutePath()); loader.addToClassLoader(libDir, null, false); loader.reloadLuceneSPI(); } shardHandlerFactory = ShardHandlerFactory.newInstance(cfg.getShardHandlerFactoryPluginInfo(), loader); updateShardHandler = new UpdateShardHandler(cfg); solrCores.allocateLazyCores(cfg.getTransientCacheSize(), loader); logging = LogWatcher.newRegisteredLogWatcher(cfg.getLogWatcherConfig(), loader); hostName = cfg.getHost(); log.info("Host Name: " + hostName); zkSys.initZooKeeper(this, solrHome, cfg); collectionsHandler = createHandler(cfg.getCollectionsHandlerClass(), CollectionsHandler.class); containerHandlers.put(COLLECTIONS_HANDLER_PATH, collectionsHandler); infoHandler = createHandler(cfg.getInfoHandlerClass(), InfoHandler.class); containerHandlers.put(INFO_HANDLER_PATH, infoHandler); coreAdminHandler = createHandler(cfg.getCoreAdminHandlerClass(), CoreAdminHandler.class); containerHandlers.put(CORES_HANDLER_PATH, coreAdminHandler); coreConfigService = cfg.createCoreConfigService(loader, zkSys.getZkController()); containerProperties = cfg.getSolrProperties(); // setup executor to load cores in parallel // do not limit the size of the executor in zk mode since cores may try and wait for each other. ExecutorService coreLoadExecutor = Executors.newFixedThreadPool( ( zkSys.getZkController() == null ? cfg.getCoreLoadThreadCount() : Integer.MAX_VALUE ), new DefaultSolrThreadFactory("coreLoadExecutor") ); try { List<CoreDescriptor> cds = coresLocator.discover(this); checkForDuplicateCoreNames(cds); List<Callable<SolrCore>> creators = new ArrayList<>(); for (final CoreDescriptor cd : cds) { if (cd.isTransient() || !cd.isLoadOnStartup()) { solrCores.putDynamicDescriptor(cd.getName(), cd); } if (cd.isLoadOnStartup()) { creators.add(new Callable<SolrCore>() { @Override public SolrCore call() throws Exception { if (zkSys.getZkController() != null) { zkSys.getZkController().throwErrorIfReplicaReplaced(cd); } return create(cd, false); } }); } } try { coreLoadExecutor.invokeAll(creators); } catch (InterruptedException e) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Interrupted while loading cores"); } // Start the background thread backgroundCloser = new CloserThread(this, solrCores, cfg); backgroundCloser.start(); } finally { ExecutorUtil.shutdownNowAndAwaitTermination(coreLoadExecutor); } if (isZooKeeperAware()) { // register in zk in background threads Collection<SolrCore> cores = getCores(); if (cores != null) { for (SolrCore core : cores) { try { zkSys.registerInZk(core, true); } catch (Throwable t) { SolrException.log(log, "Error registering SolrCore", t); } } } zkSys.getZkController().checkOverseerDesignate(); } } private static void checkForDuplicateCoreNames(List<CoreDescriptor> cds) { Map<String, String> addedCores = Maps.newHashMap(); for (CoreDescriptor cd : cds) { final String name = cd.getName(); if (addedCores.containsKey(name)) throw new SolrException(ErrorCode.SERVER_ERROR, String.format(Locale.ROOT, "Found multiple cores with the name [%s], with instancedirs [%s] and [%s]", name, addedCores.get(name), cd.getInstanceDir())); addedCores.put(name, cd.getInstanceDir()); } } private volatile boolean isShutDown = false; public boolean isShutDown() { return isShutDown; } /** * Stops all cores. */ public void shutdown() { log.info("Shutting down CoreContainer instance=" + System.identityHashCode(this)); isShutDown = true; if (isZooKeeperAware()) { cancelCoreRecoveries(); zkSys.publishCoresAsDown(solrCores.getCores()); } try { if (coreAdminHandler != null) coreAdminHandler.shutdown(); } catch (Exception e) { log.warn("Error shutting down CoreAdminHandler. Continuing to close CoreContainer.", e); } try { // First wake up the closer thread, it'll terminate almost immediately since it checks isShutDown. synchronized (solrCores.getModifyLock()) { solrCores.getModifyLock().notifyAll(); // wake up anyone waiting } if (backgroundCloser != null) { // Doesn't seem right, but tests get in here without initializing the core. try { backgroundCloser.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); if (log.isDebugEnabled()) { log.debug("backgroundCloser thread was interrupted before finishing"); } } } // Now clear all the cores that are being operated upon. solrCores.close(); // It's still possible that one of the pending dynamic load operation is waiting, so wake it up if so. // Since all the pending operations queues have been drained, there should be nothing to do. synchronized (solrCores.getModifyLock()) { solrCores.getModifyLock().notifyAll(); // wake up the thread } } finally { try { if (shardHandlerFactory != null) { shardHandlerFactory.close(); } } finally { try { if (updateShardHandler != null) { updateShardHandler.close(); } } finally { // we want to close zk stuff last zkSys.close(); } } } org.apache.lucene.util.IOUtils.closeWhileHandlingException(loader); // best effort } public void cancelCoreRecoveries() { List<SolrCore> cores = solrCores.getCores(); // we must cancel without holding the cores sync // make sure we wait for any recoveries to stop for (SolrCore core : cores) { try { core.getSolrCoreState().cancelRecovery(); } catch (Exception e) { SolrException.log(log, "Error canceling recovery for core", e); } } } @Override protected void finalize() throws Throwable { try { if(!isShutDown){ log.error("CoreContainer was not close prior to finalize(), indicates a bug -- POSSIBLE RESOURCE LEAK!!! instance=" + System.identityHashCode(this)); } } finally { super.finalize(); } } public CoresLocator getCoresLocator() { return coresLocator; } protected SolrCore registerCore(String name, SolrCore core, boolean registerInZk) { if( core == null ) { throw new RuntimeException( "Can not register a null core." ); } if( name == null || name.indexOf( '/' ) >= 0 || name.indexOf( '\\' ) >= 0 ){ throw new RuntimeException( "Invalid core name: "+name ); } // We can register a core when creating them via the admin UI, so we need to insure that the dynamic descriptors // are up to date CoreDescriptor cd = core.getCoreDescriptor(); if ((cd.isTransient() || ! cd.isLoadOnStartup()) && solrCores.getDynamicDescriptor(name) == null) { // Store it away for later use. includes non-transient but not // loaded at startup cores. solrCores.putDynamicDescriptor(name, cd); } SolrCore old = null; if (isShutDown) { core.close(); throw new IllegalStateException("This CoreContainer has been close"); } if (cd.isTransient()) { old = solrCores.putTransientCore(cfg, name, core, loader); } else { old = solrCores.putCore(name, core); } /* * set both the name of the descriptor and the name of the * core, since the descriptors name is used for persisting. */ core.setName(name); coreInitFailures.remove(name); if( old == null || old == core) { log.info( "registering core: "+name ); if (registerInZk) { zkSys.registerInZk(core, false); } return null; } else { log.info( "replacing core: "+name ); old.close(); if (registerInZk) { zkSys.registerInZk(core, false); } return old; } } /** * Creates a new core based on a CoreDescriptor, publishing the core state to the cluster * @param cd the CoreDescriptor * @return the newly created core */ public SolrCore create(CoreDescriptor cd) { return create(cd, true); } /** * Creates a new core based on a CoreDescriptor. * * @param dcore a core descriptor * @param publishState publish core state to the cluster if true * * @return the newly created core */ public SolrCore create(CoreDescriptor dcore, boolean publishState) { if (isShutDown) { throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, "Solr has close."); } try { if (zkSys.getZkController() != null) { zkSys.getZkController().preRegister(dcore); } ConfigSet coreConfig = coreConfigService.getConfig(dcore); log.info("Creating SolrCore '{}' using configuration from {}", dcore.getName(), coreConfig.getName()); SolrCore core = new SolrCore(dcore, coreConfig); solrCores.addCreated(core); // always kick off recovery if we are in non-Cloud mode if (!isZooKeeperAware() && core.getUpdateHandler().getUpdateLog() != null) { core.getUpdateHandler().getUpdateLog().recoverFromLog(); } registerCore(dcore.getName(), core, publishState); return core; } catch (Exception e) { coreInitFailures.put(dcore.getName(), new CoreLoadFailure(dcore, e)); log.error("Error creating core [{}]: {}", dcore.getName(), e.getMessage(), e); throw new SolrException(ErrorCode.SERVER_ERROR, "Unable to create core [" + dcore.getName() + "]", e); } catch (Throwable t) { SolrException e = new SolrException(ErrorCode.SERVER_ERROR, "JVM Error creating core [" + dcore.getName() + "]: " + t.getMessage(), t); log.error("Error creating core [{}]: {}", dcore.getName(), t.getMessage(), t); coreInitFailures.put(dcore.getName(), new CoreLoadFailure(dcore, e)); throw t; } } /** * @return a Collection of registered SolrCores */ public Collection<SolrCore> getCores() { return solrCores.getCores(); } /** * @return a Collection of the names that cores are mapped to */ public Collection<String> getCoreNames() { return solrCores.getCoreNames(); } /** This method is currently experimental. * @return a Collection of the names that a specific core is mapped to. */ public Collection<String> getCoreNames(SolrCore core) { return solrCores.getCoreNames(core); } /** * get a list of all the cores that are currently loaded * @return a list of al lthe available core names in either permanent or transient core lists. */ public Collection<String> getAllCoreNames() { return solrCores.getAllCoreNames(); } /** * Returns an immutable Map of Exceptions that occured when initializing * SolrCores (either at startup, or do to runtime requests to create cores) * keyed off of the name (String) of the SolrCore that had the Exception * during initialization. * <p> * While the Map returned by this method is immutable and will not change * once returned to the client, the source data used to generate this Map * can be changed as various SolrCore operations are performed: * </p> * <ul> * <li>Failed attempts to create new SolrCores will add new Exceptions.</li> * <li>Failed attempts to re-create a SolrCore using a name already contained in this Map will replace the Exception.</li> * <li>Failed attempts to reload a SolrCore will cause an Exception to be added to this list -- even though the existing SolrCore with that name will continue to be available.</li> * <li>Successful attempts to re-created a SolrCore using a name already contained in this Map will remove the Exception.</li> * <li>Registering an existing SolrCore with a name already contained in this Map (ie: ALIAS or SWAP) will remove the Exception.</li> * </ul> */ public Map<String, CoreLoadFailure> getCoreInitFailures() { return ImmutableMap.copyOf(coreInitFailures); } // ---------------- Core name related methods --------------- /** * Recreates a SolrCore. * While the new core is loading, requests will continue to be dispatched to * and processed by the old core * * @param name the name of the SolrCore to reload */ public void reload(String name) { SolrCore core = solrCores.getCoreFromAnyList(name, false); if (core == null) throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "No such core: " + name ); CoreDescriptor cd = core.getCoreDescriptor(); try { solrCores.waitAddPendingCoreOps(name); ConfigSet coreConfig = coreConfigService.getConfig(cd); log.info("Reloading SolrCore '{}' using configuration from {}", cd.getName(), coreConfig.getName()); SolrCore newCore = core.reload(coreConfig); registerCore(name, newCore, false); } catch (Exception e) { coreInitFailures.put(cd.getName(), new CoreLoadFailure(cd, e)); throw new SolrException(ErrorCode.SERVER_ERROR, "Unable to reload core [" + cd.getName() + "]", e); } finally { solrCores.removeFromPendingOps(name); } } /** * Swaps two SolrCore descriptors. */ public void swap(String n0, String n1) { if( n0 == null || n1 == null ) { throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "Can not swap unnamed cores." ); } solrCores.swap(n0, n1); coresLocator.swap(this, solrCores.getCoreDescriptor(n0), solrCores.getCoreDescriptor(n1)); log.info("swapped: "+n0 + " with " + n1); } /** * Unload a core from this container, leaving all files on disk * @param name the name of the core to unload */ public void unload(String name) { unload(name, false, false, false); } /** * Unload a core from this container, optionally removing the core's data and configuration * * @param name the name of the core to unload * @param deleteIndexDir if true, delete the core's index on close * @param deleteDataDir if true, delete the core's data directory on close * @param deleteInstanceDir if true, delete the core's instance directory on close */ public void unload(String name, boolean deleteIndexDir, boolean deleteDataDir, boolean deleteInstanceDir) { // check for core-init errors first CoreLoadFailure loadFailure = coreInitFailures.remove(name); if (loadFailure != null) { // getting the index directory requires opening a DirectoryFactory with a SolrConfig, etc, // which we may not be able to do because of the init error. So we just go with what we // can glean from the CoreDescriptor - datadir and instancedir SolrCore.deleteUnloadedCore(loadFailure.cd, deleteDataDir, deleteInstanceDir); return; } CoreDescriptor cd = solrCores.getCoreDescriptor(name); if (cd == null) throw new SolrException(ErrorCode.BAD_REQUEST, "Cannot unload non-existent core [" + name + "]"); boolean close = solrCores.isLoadedNotPendingClose(name); SolrCore core = solrCores.remove(name); coresLocator.delete(this, cd); if (core == null) { // transient core SolrCore.deleteUnloadedCore(cd, deleteDataDir, deleteInstanceDir); return; } if (zkSys.getZkController() != null) { // cancel recovery in cloud mode core.getSolrCoreState().cancelRecovery(); } String configSetZkPath = core.getResourceLoader() instanceof ZkSolrResourceLoader ? ((ZkSolrResourceLoader)core.getResourceLoader()).getConfigSetZkPath() : null; core.unloadOnClose(deleteIndexDir, deleteDataDir, deleteInstanceDir); if (close) core.close(); if (zkSys.getZkController() != null) { try { zkSys.getZkController().unregister(name, cd, configSetZkPath); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new SolrException(ErrorCode.SERVER_ERROR, "Interrupted while unregistering core [" + name + "] from cloud state"); } catch (KeeperException e) { throw new SolrException(ErrorCode.SERVER_ERROR, "Error unregistering core [" + name + "] from cloud state", e); } } } public void rename(String name, String toName) { try (SolrCore core = getCore(name)) { if (core != null) { registerCore(toName, core, true); SolrCore old = solrCores.remove(name); coresLocator.rename(this, old.getCoreDescriptor(), core.getCoreDescriptor()); } } } /** * Get the CoreDescriptors for all cores managed by this container * @return a List of CoreDescriptors */ public List<CoreDescriptor> getCoreDescriptors() { return solrCores.getCoreDescriptors(); } public CoreDescriptor getCoreDescriptor(String coreName) { // TODO make this less hideous! for (CoreDescriptor cd : getCoreDescriptors()) { if (cd.getName().equals(coreName)) return cd; } return null; } public String getCoreRootDirectory() { return cfg.getCoreRootDirectory(); } /** * Gets a core by name and increase its refcount. * * @see SolrCore#close() * @param name the core name * @return the core if found, null if a SolrCore by this name does not exist * @exception SolrException if a SolrCore with this name failed to be initialized */ public SolrCore getCore(String name) { // Do this in two phases since we don't want to lock access to the cores over a load. SolrCore core = solrCores.getCoreFromAnyList(name, true); if (core != null) { return core; } // OK, it's not presently in any list, is it in the list of dynamic cores but not loaded yet? If so, load it. CoreDescriptor desc = solrCores.getDynamicDescriptor(name); if (desc == null) { //Nope, no transient core with this name // if there was an error initalizing this core, throw a 500 // error with the details for clients attempting to access it. CoreLoadFailure loadFailure = getCoreInitFailures().get(name); if (null != loadFailure) { throw new SolrException(ErrorCode.SERVER_ERROR, "SolrCore '" + name + "' is not available due to init failure: " + loadFailure.exception.getMessage(), loadFailure.exception); } // otherwise the user is simply asking for something that doesn't exist. return null; } // This will put an entry in pending core ops if the core isn't loaded core = solrCores.waitAddPendingCoreOps(name); if (isShutDown) return null; // We're quitting, so stop. This needs to be after the wait above since we may come off // the wait as a consequence of shutting down. try { if (core == null) { if (zkSys.getZkController() != null) { zkSys.getZkController().throwErrorIfReplicaReplaced(desc); } core = create(desc); // This should throw an error if it fails. } core.open(); } finally { solrCores.removeFromPendingOps(name); } return core; } public JarRepository getJarRepository(){ return jarRepository; } // ---------------- CoreContainer request handlers -------------- protected <T> T createHandler(String handlerClass, Class<T> clazz) { return loader.newInstance(handlerClass, clazz, null, new Class[] { CoreContainer.class }, new Object[] { this }); } public CoreAdminHandler getMultiCoreHandler() { return coreAdminHandler; } public CollectionsHandler getCollectionsHandler() { return collectionsHandler; } public InfoHandler getInfoHandler() { return infoHandler; } public String getHostName() { return this.hostName; } /** * Gets the alternate path for multicore handling: * This is used in case there is a registered unnamed core (aka name is "") to * declare an alternate way of accessing named cores. * This can also be used in a pseudo single-core environment so admins can prepare * a new version before swapping. */ public String getManagementPath() { return cfg.getManagementPath(); } public LogWatcher getLogging() { return logging; } /** * Determines whether the core is already loaded or not but does NOT load the core * */ public boolean isLoaded(String name) { return solrCores.isLoaded(name); } public boolean isLoadedNotPendingClose(String name) { return solrCores.isLoadedNotPendingClose(name); } /** * Gets a solr core descriptor for a core that is not loaded. Note that if the caller calls this on a * loaded core, the unloaded descriptor will be returned. * * @param cname - name of the unloaded core descriptor to load. NOTE: * @return a coreDescriptor. May return null */ public CoreDescriptor getUnloadedCoreDescriptor(String cname) { return solrCores.getUnloadedCoreDescriptor(cname); } public String getSolrHome() { return solrHome; } public boolean isZooKeeperAware() { return zkSys.getZkController() != null; } public ZkController getZkController() { return zkSys.getZkController(); } public ConfigSolr getConfig() { return cfg; } /** The default ShardHandlerFactory used to communicate with other solr instances */ public ShardHandlerFactory getShardHandlerFactory() { return shardHandlerFactory; } public UpdateShardHandler getUpdateShardHandler() { return updateShardHandler; } public SolrResourceLoader getResourceLoader() { return loader; } } class CloserThread extends Thread { CoreContainer container; SolrCores solrCores; ConfigSolr cfg; CloserThread(CoreContainer container, SolrCores solrCores, ConfigSolr cfg) { this.container = container; this.solrCores = solrCores; this.cfg = cfg; } // It's important that this be the _only_ thread removing things from pendingDynamicCloses! // This is single-threaded, but I tried a multi-threaded approach and didn't see any performance gains, so // there's no good justification for the complexity. I suspect that the locking on things like DefaultSolrCoreState // essentially create a single-threaded process anyway. @Override public void run() { while (! container.isShutDown()) { synchronized (solrCores.getModifyLock()) { // need this so we can wait and be awoken. try { solrCores.getModifyLock().wait(); } catch (InterruptedException e) { // Well, if we've been told to stop, we will. Otherwise, continue on and check to see if there are // any cores to close. } } for (SolrCore removeMe = solrCores.getCoreToClose(); removeMe != null && !container.isShutDown(); removeMe = solrCores.getCoreToClose()) { try { removeMe.close(); } finally { solrCores.removeFromPendingOps(removeMe.getName()); } } } } }
visouza/solr-5.0.0
solr/core/src/java/org/apache/solr/core/CoreContainer.java
Java
apache-2.0
30,728
<!doctype html><html lang=en><head><title>Redirecting&hellip;</title><link rel=canonical href=/v1.2/docs/tasks/traffic-management/egress/egress-control/><meta name=robots content=noindex><meta charset=utf-8><meta http-equiv=refresh content="0; url=/v1.2/docs/tasks/traffic-management/egress/egress-control/"></head><body><h1>Redirecting&hellip;</h1><a href=/v1.2/docs/tasks/traffic-management/egress/egress-control/>Click here if you are not redirected.</a></body></html>
istio/istio.io
archive/v1.2/docs/tasks/egress/index.html
HTML
apache-2.0
471
package gov.va.medora.mdws.emrsvc; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="fromDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="toDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nNotes" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "fromDate", "toDate", "nNotes" }) @XmlRootElement(name = "getDischargeSummaries") public class GetDischargeSummaries { protected String fromDate; protected String toDate; protected int nNotes; /** * Gets the value of the fromDate property. * * @return * possible object is * {@link String } * */ public String getFromDate() { return fromDate; } /** * Sets the value of the fromDate property. * * @param value * allowed object is * {@link String } * */ public void setFromDate(String value) { this.fromDate = value; } /** * Gets the value of the toDate property. * * @return * possible object is * {@link String } * */ public String getToDate() { return toDate; } /** * Sets the value of the toDate property. * * @param value * allowed object is * {@link String } * */ public void setToDate(String value) { this.toDate = value; } /** * Gets the value of the nNotes property. * */ public int getNNotes() { return nNotes; } /** * Sets the value of the nNotes property. * */ public void setNNotes(int value) { this.nNotes = value; } }
VHAINNOVATIONS/TheDailyPlan
LegacyApp/tdpWeb/src/main/java/gov/va/medora/mdws/emrsvc/GetDischargeSummaries.java
Java
apache-2.0
2,528
# Systemd Unit If you are using distribution packages or the copr repository, you don't need to deal with these files! The unit file in this directory is to be put into `/etc/systemd/system`. It needs a user named `node_exporter`, whose shell should be `/sbin/nologin` and should not have any special privileges. It needs a sysconfig file in `/etc/sysconfig/node_exporter`. It needs a directory named `/var/lib/node_exporter/textfile_collector`, whose owner should be `node_exporter`:`node_exporter`. A sample file can be found in `sysconfig.node_exporter`.
prometheus/node_exporter
examples/systemd/README.md
Markdown
apache-2.0
560
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pig.test; import static java.util.regex.Matcher.quoteReplacement; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringReader; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.log4j.Appender; import org.apache.log4j.FileAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.SimpleLayout; import org.apache.log4j.WriterAppender; import org.apache.pig.ExecType; import org.apache.pig.ExecTypeProvider; import org.apache.pig.LoadCaster; import org.apache.pig.PigException; import org.apache.pig.PigServer; import org.apache.pig.ResourceSchema.ResourceFieldSchema; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.backend.hadoop.datastorage.ConfigurationUtil; import org.apache.pig.backend.hadoop.executionengine.HExecutionEngine; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MRCompiler; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MRConfiguration; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans.MROperPlan; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhysicalPlan; import org.apache.pig.backend.hadoop.executionengine.tez.TezResourceManager; import org.apache.pig.backend.hadoop.executionengine.util.MapRedUtil; import org.apache.pig.builtin.Utf8StorageConverter; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.DefaultBagFactory; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.PigContext; import org.apache.pig.impl.io.FileLocalizer; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.apache.pig.impl.logicalLayer.schema.Schema.FieldSchema; import org.apache.pig.impl.util.LogUtils; import org.apache.pig.newplan.logical.optimizer.LogicalPlanPrinter; import org.apache.pig.newplan.logical.optimizer.SchemaResetter; import org.apache.pig.newplan.logical.optimizer.UidResetter; import org.apache.pig.newplan.logical.relational.LogToPhyTranslationVisitor; import org.apache.pig.newplan.logical.relational.LogicalPlan; import org.apache.pig.newplan.logical.relational.LogicalSchema; import org.apache.pig.newplan.logical.relational.LogicalSchema.LogicalFieldSchema; import org.apache.pig.newplan.logical.visitor.DanglingNestedNodeRemover; import org.apache.pig.newplan.logical.visitor.SortInfoSetter; import org.apache.pig.newplan.logical.visitor.StoreAliasSetter; import org.apache.pig.parser.ParserException; import org.apache.pig.parser.QueryParserDriver; import org.apache.pig.tools.grunt.GruntParser; import org.apache.pig.tools.pigstats.ScriptState; import org.apache.spark.package$; import org.junit.Assert; import com.google.common.base.Function; import com.google.common.collect.Lists; public class Util { private static BagFactory mBagFactory = BagFactory.getInstance(); private static TupleFactory mTupleFactory = TupleFactory.getInstance(); // Commonly-checked system state // ================= public static final boolean WINDOWS /* borrowed from Path.WINDOWS, Shell.WINDOWS */ = System.getProperty("os.name").startsWith("Windows"); public static final String TEST_DIR = System.getProperty("test.build.dir", "build/test"); // Helper Functions // ================= static public Tuple loadFlatTuple(Tuple t, int[] input) throws ExecException { for (int i = 0; i < input.length; i++) { t.set(i, new Integer(input[i])); } return t; } static public Tuple loadTuple(Tuple t, String[] input) throws ExecException { for (int i = 0; i < input.length; i++) { t.set(i, input[i]); } return t; } static public Tuple loadTuple(Tuple t, DataByteArray[] input) throws ExecException { for (int i = 0; i < input.length; i++) { t.set(i, input[i]); } return t; } static public Tuple loadNestTuple(Tuple t, int[] input) throws ExecException { DataBag bag = BagFactory.getInstance().newDefaultBag(); for(int i = 0; i < input.length; i++) { Tuple f = TupleFactory.getInstance().newTuple(1); f.set(0, input[i]); bag.add(f); } t.set(0, bag); return t; } static public Tuple loadNestTuple(Tuple t, long[] input) throws ExecException { DataBag bag = BagFactory.getInstance().newDefaultBag(); for(int i = 0; i < input.length; i++) { Tuple f = TupleFactory.getInstance().newTuple(1); f.set(0, new Long(input[i])); bag.add(f); } t.set(0, bag); return t; } // this one should handle String, DataByteArray, Long, Integer etc.. static public <T> Tuple loadNestTuple(Tuple t, T[] input) throws ExecException { DataBag bag = BagFactory.getInstance().newDefaultBag(); for(int i = 0; i < input.length; i++) { Tuple f = TupleFactory.getInstance().newTuple(1); f.set(0, input[i]); bag.add(f); } t.set(0, bag); return t; } /** * Create an array of tuple bags with specified size created by splitting * the input array of primitive types * * @param input Array of primitive types * @param bagSize The number of tuples to be split and copied into each bag * * @return an array of tuple bags with each bag containing bagSize tuples split from the input */ static public <T> Tuple[] splitCreateBagOfTuples(T[] input, int bagSize) throws ExecException { List<Tuple> result = new ArrayList<Tuple>(); for (int from = 0; from < input.length; from += bagSize) { Tuple t = TupleFactory.getInstance().newTuple(1); int to = from + bagSize < input.length ? from + bagSize : input.length; T[] array = Arrays.copyOfRange(input, from, to); result.add(loadNestTuple(t, array)); } return result.toArray(new Tuple[0]); } static public <T>void addToTuple(Tuple t, T[] b) { for(int i = 0; i < b.length; i++) t.append(b[i]); } static public Tuple buildTuple(Object... args) throws ExecException { return TupleFactory.getInstance().newTupleNoCopy(Lists.newArrayList(args)); } static public Tuple buildBinTuple(final Object... args) throws IOException { return TupleFactory.getInstance().newTuple(Lists.transform( Lists.newArrayList(args), new Function<Object, DataByteArray>() { @Override public DataByteArray apply(Object o) { if (o == null) { return null; } try { return new DataByteArray(DataType.toBytes(o)); } catch (ExecException e) { return null; } } })); } static public <T>Tuple createTuple(T[] s) { Tuple t = mTupleFactory.newTuple(); addToTuple(t, s); return t; } static public DataBag createBag(Tuple[] t) { DataBag b = mBagFactory.newDefaultBag(); for(int i = 0; i < t.length; i++)b.add(t[i]); return b; } static public<T> DataBag createBagOfOneColumn(T[] input) throws ExecException { DataBag result = mBagFactory.newDefaultBag(); for (int i = 0; i < input.length; i++) { Tuple t = mTupleFactory.newTuple(1); t.set(0, input[i]); result.add(t); } return result; } static public Map<String, Object> createMap(String[] contents) { Map<String, Object> m = new HashMap<String, Object>(); for(int i = 0; i < contents.length; ) { m.put(contents[i], contents[i+1]); i += 2; } return m; } static public<T> DataByteArray[] toDataByteArrays(T[] input) { DataByteArray[] dbas = new DataByteArray[input.length]; for (int i = 0; i < input.length; i++) { dbas[i] = (input[i] == null)?null:new DataByteArray(input[i].toString().getBytes()); } return dbas; } static public Tuple loadNestTuple(Tuple t, int[][] input) throws ExecException { for (int i = 0; i < input.length; i++) { DataBag bag = BagFactory.getInstance().newDefaultBag(); Tuple f = loadFlatTuple(TupleFactory.getInstance().newTuple(input[i].length), input[i]); bag.add(f); t.set(i, bag); } return t; } static public Tuple loadTuple(Tuple t, String[][] input) throws ExecException { for (int i = 0; i < input.length; i++) { DataBag bag = BagFactory.getInstance().newDefaultBag(); Tuple f = loadTuple(TupleFactory.getInstance().newTuple(input[i].length), input[i]); bag.add(f); t.set(i, bag); } return t; } /** * Helper to remove colons (if any exist) from paths to sanitize them for * consumption by hdfs. * * @param origPath original path name * @return String sanitized path with anything prior to : removed * @throws IOException */ static public String removeColon(String origPath) { return origPath.replaceAll(":", ""); } /** * Helper to convert \r\n to \n for cross-platform string * matching with checked-in baselines. * * @param origPath original string * @return String newline-standardized string * @throws IOException */ static public String standardizeNewline(String origPath) { return origPath.replaceAll("\r\n", "\n"); } /** * Helper to create a temporary file with given input data for use in test cases. * * @param tmpFilenamePrefix file-name prefix * @param tmpFilenameSuffix file-name suffix * @param inputData input for test cases, each string in inputData[] is written * on one line * @return {@link File} handle to the created temporary file * @throws IOException */ static public File createInputFile(String tmpFilenamePrefix, String tmpFilenameSuffix, String[] inputData) throws IOException { File f = File.createTempFile(tmpFilenamePrefix, tmpFilenameSuffix); f.deleteOnExit(); writeToFile(f, inputData); return f; } static public File createLocalInputFile(String filename, String[] inputData) throws IOException { File f = new File(filename); f.deleteOnExit(); writeToFile(f, inputData); return f; } public static void writeToFile(File f, String[] inputData) throws IOException { PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8")); for (int i=0; i<inputData.length; i++){ pw.print(inputData[i]); pw.print("\n"); } pw.close(); } /** * Helper to create a dfs file on the Minicluster DFS with given * input data for use in test cases. * * @param miniCluster reference to the Minicluster where the file should be created * @param fileName pathname of the file to be created * @param inputData input for test cases, each string in inputData[] is written * on one line * @throws IOException */ static public void createInputFile(MiniGenericCluster miniCluster, String fileName, String[] inputData) throws IOException { FileSystem fs = miniCluster.getFileSystem(); createInputFile(fs, fileName, inputData); } static public void createInputFile(FileSystem fs, String fileName, String[] inputData) throws IOException { if(Util.WINDOWS){ fileName = fileName.replace('\\','/'); } if(fs.exists(new Path(fileName))) { throw new IOException("File " + fileName + " already exists on the FileSystem"); } FSDataOutputStream stream = fs.create(new Path(fileName)); PrintWriter pw = new PrintWriter(new OutputStreamWriter(stream, "UTF-8")); for (int i=0; i<inputData.length; i++){ pw.print(inputData[i]); pw.print("\n"); } pw.close(); } static public String[] readOutput(FileSystem fs, String fileName) throws IOException { if(Util.WINDOWS){ fileName = fileName.replace('\\','/'); } Path path = new Path(fileName); if(!fs.exists(path)) { throw new IOException("Path " + fileName + " does not exist on the FileSystem"); } FileStatus fileStatus = fs.getFileStatus(path); FileStatus[] files; if (fileStatus.isDirectory()) { files = fs.listStatus(path, new PathFilter() { @Override public boolean accept(Path p) { return !p.getName().startsWith("_"); } }); } else { files = new FileStatus[] { fileStatus }; } List<String> result = new ArrayList<String>(); for (FileStatus f : files) { FSDataInputStream stream = fs.open(f.getPath()); BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8")); String line; while ((line = br.readLine()) != null) { result.add(line); } br.close(); } return result.toArray(new String[result.size()]); } /** * Helper to create a dfs file on the MiniCluster dfs. This returns an * outputstream that can be used in test cases to write data. * * @param cluster * reference to the MiniCluster where the file should be created * @param fileName * pathname of the file to be created * @return OutputStream to write any data to the file created on the * MiniCluster. * @throws IOException */ static public OutputStream createInputFile(MiniGenericCluster cluster, String fileName) throws IOException { FileSystem fs = cluster.getFileSystem(); if(Util.WINDOWS){ fileName = fileName.replace('\\','/'); } if (fs.exists(new Path(fileName))) { throw new IOException("File " + fileName + " already exists on the minicluster"); } return fs.create(new Path(fileName)); } /** * Helper to create an empty temp file on local file system * which will be deleted on exit * @param prefix * @param suffix * @return File denoting a newly-created empty file * @throws IOException */ static public File createTempFileDelOnExit(String prefix, String suffix) throws IOException { File tmpFile = File.createTempFile(prefix, suffix); tmpFile.deleteOnExit(); return tmpFile; } /** * Helper to remove a dfs file from the minicluster DFS * * @param miniCluster reference to the Minicluster where the file should be deleted * @param fileName pathname of the file to be deleted * @throws IOException */ static public void deleteFile(MiniGenericCluster miniCluster, String fileName) throws IOException { FileSystem fs = miniCluster.getFileSystem(); if(Util.WINDOWS){ fileName = fileName.replace('\\','/'); } fs.delete(new Path(fileName), true); } /** * Deletes a dfs file from the MiniCluster DFS quietly * * @param miniCluster the MiniCluster where the file should be deleted * @param fileName the path of the file to be deleted */ public static void deleteQuietly(MiniGenericCluster miniCluster, String fileName) { try { deleteFile(miniCluster, fileName); } catch (IOException ignored) { } } static public void deleteFile(PigContext pigContext, String fileName) throws IOException { Configuration conf = ConfigurationUtil.toConfiguration( pigContext.getProperties()); FileSystem fs = FileSystem.get(conf); if(Util.WINDOWS){ fileName = fileName.replace('\\','/'); } fs.delete(new Path(fileName), true); } static public boolean exists(PigContext pigContext, String fileName) throws IOException { Configuration conf = ConfigurationUtil.toConfiguration( pigContext.getProperties()); FileSystem fs = FileSystem.get(conf); if(Util.WINDOWS){ fileName = fileName.replace('\\','/'); } return fs.exists(new Path(fileName)); } /** * Helper function to check if the result of a Pig Query is in line with * expected results. * * @param actualResults Result of the executed Pig query * @param expectedResults Expected results Array to validate against */ static public void checkQueryOutputs(Iterator<Tuple> actualResults, Tuple[] expectedResults) { checkQueryOutputs(actualResults, Arrays.asList(expectedResults)); } /** * Helper function to check if the result of a Pig Query is in line with * expected results. * * @param actualResults Result of the executed Pig query * @param expectedResults Expected results List to validate against */ static public void checkQueryOutputs(Iterator<Tuple> actualResults, List<Tuple> expectedResults) { checkQueryOutputs(actualResults, expectedResults.iterator(), null ); } /** * Helper function to check if the result of a Pig Query is in line with * expected results. * * @param actualResults Result of the executed Pig query * @param expectedResults Expected results List to validate against */ static public void checkQueryOutputs(Iterator<Tuple> actualResults, Iterator<Tuple> expectedResults, Integer expectedRows) { int count = 0; while (expectedResults.hasNext()) { Tuple expected = expectedResults.next(); Assert.assertTrue("Actual result has less records than expected results", actualResults.hasNext()); Tuple actual = actualResults.next(); // If this tuple contains any bags, bags will be sorted before comparisons if( !expected.equals(actual) ) { // Using string comparisons since error message is more readable // (only showing the part which differs) Assert.assertEquals(expected.toString(), actual.toString()); // if above goes through, simply failing with object comparisons Assert.assertEquals(expected, actual); } count++; } Assert.assertFalse("Actual result has more records than expected results", actualResults.hasNext()); if (expectedRows != null) { Assert.assertEquals((int)expectedRows, count); } } /** * Helper function to check if the result of a Pig Query is in line with * expected results. It sorts actual and expected results before comparison * * @param actualResultsIt Result of the executed Pig query * @param expectedResList Expected results to validate against */ static public void checkQueryOutputsAfterSort(Iterator<Tuple> actualResultsIt, List<Tuple> expectedResList) { List<Tuple> actualResList = new ArrayList<Tuple>(); while(actualResultsIt.hasNext()){ actualResList.add(actualResultsIt.next()); } checkQueryOutputsAfterSort(actualResList, expectedResList); } /** * Helper function to check if the result of Pig Query is in line with expected results. * It sorts actual and expected results before comparison. * The tuple size in the tuple list can vary. Pass by a two-dimension array, it will be converted to be a tuple list. * e.g. expectedTwoDimensionObjects is [{{10, "will_join", 10, "will_join"}, {11, "will_not_join", null}, {null, 12, "will_not_join"}}], * the field size of these 3 tuples are [4,3,3] * * @param actualResultsIt * @param expectedTwoDimensionObjects represents a tuple list, in which the tuple can have variable size. */ static public void checkQueryOutputsAfterSort(Iterator<Tuple> actualResultsIt, Object[][] expectedTwoDimensionObjects) { List<Tuple> expectedResTupleList = new ArrayList<Tuple>(); for (int i = 0; i < expectedTwoDimensionObjects.length; ++i) { Tuple t = TupleFactory.getInstance().newTuple(); for (int j = 0; j < expectedTwoDimensionObjects[i].length; ++j) { t.append(expectedTwoDimensionObjects[i][j]); } expectedResTupleList.add(t); } checkQueryOutputsAfterSort(actualResultsIt, expectedResTupleList); } static public void checkQueryOutputsAfterSort( List<Tuple> actualResList, List<Tuple> expectedResList) { Collections.sort(actualResList); Collections.sort(expectedResList); checkQueryOutputs(actualResList.iterator(), expectedResList); } /** * Check if subStr is a subString of str . calls org.junit.Assert.fail if it is not * @param str * @param subStr */ static public void checkStrContainsSubStr(String str, String subStr){ if(!str.contains(subStr)){ fail("String '"+ subStr + "' is not a substring of '" + str + "'"); } } /** * Check if query plan for alias argument produces exception with expected * error message in expectedErr argument. * @param query * @param alias * @param expectedErr * @throws IOException */ static public void checkExceptionMessage(String query, String alias, String expectedErr) throws IOException { PigServer pig = new PigServer(ExecType.LOCAL); boolean foundEx = false; try{ Util.registerMultiLineQuery(pig, query); pig.explain(alias, System.out); }catch(FrontendException e){ foundEx = true; checkMessageInException(e, expectedErr); } if(!foundEx) fail("No exception thrown. Exception is expected."); } public static void checkMessageInException(FrontendException e, String expectedErr) { PigException pigEx = LogUtils.getPigException(e); String message = pigEx.getMessage(); checkErrorMessageContainsExpected(message, expectedErr); } public static void checkErrorMessageContainsExpected(String message, String expectedMessage){ if(!message.contains(expectedMessage)){ String msg = "Expected error message containing '" + expectedMessage + "' but got '" + message + "'" ; fail(msg); } } static private String getFSMkDirCommand(String fileName) { Path parentDir = new Path(fileName).getParent(); String mkdirCommand = parentDir.getName().isEmpty() ? "" : "fs -mkdir -p " + parentDir + "\n"; return mkdirCommand; } /** * Utility method to copy a file form local filesystem to the dfs on * the minicluster for testing in mapreduce mode * @param cluster a reference to the minicluster * @param localFileName the pathname of local file * @param fileNameOnCluster the name with which the file should be created on the minicluster * @throws IOException */ static public void copyFromLocalToCluster(MiniGenericCluster cluster, String localFileName, String fileNameOnCluster) throws IOException { if(Util.WINDOWS){ if (!localFileName.contains(":")) { localFileName = localFileName.replace('\\','/'); } else { localFileName = localFileName.replace('/','\\'); } fileNameOnCluster = fileNameOnCluster.replace('\\','/'); } PigServer ps = new PigServer(cluster.getExecType(), cluster.getProperties()); String script = getFSMkDirCommand(fileNameOnCluster) + "fs -put " + localFileName + " " + fileNameOnCluster; GruntParser parser = new GruntParser(new StringReader(script), ps); parser.setInteractive(false); try { parser.parseStopOnError(); } catch (org.apache.pig.tools.pigscript.parser.ParseException e) { throw new IOException(e); } } static public void copyFromLocalToLocal(String fromLocalFileName, String toLocalFileName) throws IOException { FileUtils.copyFile(new File(fromLocalFileName), new File(toLocalFileName)); } static public void copyFromClusterToLocal(MiniGenericCluster cluster, String fileNameOnCluster, String localFileName) throws IOException { if(Util.WINDOWS){ fileNameOnCluster = fileNameOnCluster.replace('\\','/'); localFileName = localFileName.replace('\\','/'); } File parent = new File(localFileName).getParentFile(); if (!parent.exists()) { parent.mkdirs(); } PrintWriter writer = new PrintWriter(new FileWriter(localFileName)); FileSystem fs = FileSystem.get(ConfigurationUtil.toConfiguration( cluster.getProperties())); if(!fs.exists(new Path(fileNameOnCluster))) { throw new IOException("File " + fileNameOnCluster + " does not exists on the minicluster"); } String line = null; FileStatus fst = fs.getFileStatus(new Path(fileNameOnCluster)); if(fst.isDirectory()) { throw new IOException("Only files from cluster can be copied locally," + " " + fileNameOnCluster + " is a directory"); } FSDataInputStream stream = fs.open(new Path(fileNameOnCluster)); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); while( (line = reader.readLine()) != null) { writer.println(line); } reader.close(); writer.close(); } static public void printQueryOutput(Iterator<Tuple> actualResults, Tuple[] expectedResults) { System.out.println("Expected :") ; for (Tuple expected : expectedResults) { System.out.println(expected.toString()) ; } System.out.println("---End----") ; System.out.println("Actual :") ; while (actualResults.hasNext()) { System.out.println(actualResults.next().toString()) ; } System.out.println("---End----") ; } /** * Helper method to replace all occurrences of "\" with "\\" in a * string. This is useful to fix the file path string on Windows * where "\" is used as the path separator. * * @param str Any string * @return The resulting string */ public static String encodeEscape(String str) { String regex = "\\\\"; String replacement = quoteReplacement("\\\\"); return str.replaceAll(regex, replacement); } public static String generateURI(String filename, PigContext context) throws IOException { if(Util.WINDOWS){ filename = filename.replace('\\','/'); } if (context.getExecType() == ExecType.MAPREDUCE || context.getExecType().name().equals("TEZ") || context.getExecType().name().equals("SPARK")) { return FileLocalizer.hadoopify(filename, context); } else if (context.getExecType().isLocal()) { return filename; } else { throw new IllegalStateException("ExecType: " + context.getExecType()); } } public static Object getPigConstant(String pigConstantAsString) throws ParserException { QueryParserDriver queryParser = new QueryParserDriver( new PigContext(), "util", new HashMap<String, String>() ) ; return queryParser.parseConstant(pigConstantAsString); } /** * Parse list of strings in to list of tuples, convert quoted strings into * @param tupleConstants * @return * @throws ParserException */ public static List<Tuple> getTuplesFromConstantTupleStrings(String[] tupleConstants) throws ParserException { List<Tuple> result = new ArrayList<Tuple>(tupleConstants.length); for(int i = 0; i < tupleConstants.length; i++) { result.add((Tuple) getPigConstant(tupleConstants[i])); } return result; } /** * Parse list of strings in to list of tuples, convert quoted strings into * DataByteArray * @param tupleConstants * @return * @throws ParserException * @throws ExecException */ public static List<Tuple> getTuplesFromConstantTupleStringAsByteArray(String[] tupleConstants) throws ParserException, ExecException { List<Tuple> tuples = getTuplesFromConstantTupleStrings(tupleConstants); for(Tuple t : tuples){ convertStringToDataByteArray(t); } return tuples; } /** * Convert String objects in argument t to DataByteArray objects * @param t * @throws ExecException */ private static void convertStringToDataByteArray(Tuple t) throws ExecException { if(t == null) return; for(int i=0; i<t.size(); i++){ Object col = t.get(i); if(col == null) continue; if(col instanceof String){ DataByteArray dba = (col == null) ? null : new DataByteArray((String)col); t.set(i, dba); }else if(col instanceof Tuple){ convertStringToDataByteArray((Tuple)col); }else if(col instanceof DataBag){ Iterator<Tuple> it = ((DataBag)col).iterator(); while(it.hasNext()){ convertStringToDataByteArray(it.next()); } } } } public static File createFile(String[] data) throws Exception{ return createFile(null,data); } public static File createFile(String filePath, String[] data) throws Exception { File f; if( null == filePath || filePath.isEmpty() ) { f = File.createTempFile("tmp", ""); } else { f = new File(filePath); } if (f.getParent() != null && !(new File(f.getParent())).exists()) { (new File(f.getParent())).mkdirs(); } f.deleteOnExit(); PrintWriter pw = new PrintWriter(f); for (int i=0; i<data.length; i++){ pw.println(data[i]); } pw.close(); return f; } /** * Run default set of optimizer rules on new logical plan * @param lp * @return optimized logical plan * @throws FrontendException */ public static LogicalPlan optimizeNewLP( LogicalPlan lp) throws FrontendException{ DanglingNestedNodeRemover DanglingNestedNodeRemover = new DanglingNestedNodeRemover( lp ); DanglingNestedNodeRemover.visit(); UidResetter uidResetter = new UidResetter( lp ); uidResetter.visit(); SchemaResetter schemaResetter = new SchemaResetter( lp, true /*disable duplicate uid check*/ ); schemaResetter.visit(); StoreAliasSetter storeAliasSetter = new StoreAliasSetter( lp ); storeAliasSetter.visit(); // run optimizer org.apache.pig.newplan.logical.optimizer.LogicalPlanOptimizer optimizer = new org.apache.pig.newplan.logical.optimizer.LogicalPlanOptimizer(lp, 100, null); optimizer.optimize(); SortInfoSetter sortInfoSetter = new SortInfoSetter( lp ); sortInfoSetter.visit(); return lp; } /** * migrate old LP(logical plan) to new LP, optimize it, and build physical * plan * @param lp * @param pc PigContext * @return physical plan * @throws Exception */ public static PhysicalPlan buildPhysicalPlanFromNewLP( LogicalPlan lp, PigContext pc) throws Exception { LogToPhyTranslationVisitor visitor = new LogToPhyTranslationVisitor(lp); visitor.setPigContext(pc); visitor.visit(); return visitor.getPhysicalPlan(); } public static MROperPlan buildMRPlan(PhysicalPlan pp, PigContext pc) throws Exception{ MRCompiler comp = new MRCompiler(pp, pc); comp.compile(); comp.aggregateScalarsFiles(); comp.connectSoftLink(); return comp.getMRPlan(); } public static MROperPlan buildMRPlanWithOptimizer(PhysicalPlan pp, PigContext pc) throws Exception { MapRedUtil.checkLeafIsStore(pp, pc); MapReduceLauncher launcher = new MapReduceLauncher(); return launcher.compile(pp,pc); } public static MROperPlan buildMRPlan(String query, PigContext pc) throws Exception { LogicalPlan lp = Util.parse(query, pc); Util.optimizeNewLP(lp); PhysicalPlan pp = Util.buildPhysicalPlanFromNewLP(lp, pc); MROperPlan mrp = Util.buildMRPlanWithOptimizer(pp, pc); return mrp; } public static void registerMultiLineQuery(PigServer pigServer, String query) throws IOException { File f = File.createTempFile("tmp", ""); PrintWriter pw = new PrintWriter(f); pw.println(query); pw.close(); pigServer.registerScript(f.getCanonicalPath()); } public static int executeJavaCommand(String cmd) throws Exception { return executeJavaCommandAndReturnInfo(cmd).exitCode; } public static class ReadStream implements Runnable { InputStream is; Thread thread; String message = ""; public ReadStream(InputStream is) { this.is = is; } public void start () { thread = new Thread (this); thread.start (); } @Override public void run () { try { InputStreamReader isr = new InputStreamReader (is); BufferedReader br = new BufferedReader (isr); while (true) { String s = br.readLine (); if (s == null) break; if (!message.isEmpty()) { message += "\n"; } message += s; } is.close (); } catch (Exception ex) { ex.printStackTrace (); } } public String getMessage() { return message; } } public static ProcessReturnInfo executeJavaCommandAndReturnInfo(String cmd) throws Exception { String javaHome = System.getenv("JAVA_HOME"); if(javaHome != null) { String fileSeparator = System.getProperty("file.separator"); cmd = javaHome + fileSeparator + "bin" + fileSeparator + cmd; } Process cmdProc = Runtime.getRuntime().exec(cmd); ProcessReturnInfo pri = new ProcessReturnInfo(); ReadStream stdoutStream = new ReadStream(cmdProc.getInputStream ()); ReadStream stderrStream = new ReadStream(cmdProc.getErrorStream ()); stdoutStream.start(); stderrStream.start(); cmdProc.waitFor(); pri.exitCode = cmdProc.exitValue(); pri.stdoutContents = stdoutStream.getMessage(); pri.stderrContents = stderrStream.getMessage(); return pri; } public static class ProcessReturnInfo { public int exitCode; public String stderrContents; public String stdoutContents; @Override public String toString() { return "[Exit code: " + exitCode + ", stdout: <" + stdoutContents + ">, " + "stderr: <" + stderrContents + ">"; } } static public boolean deleteDirectory(File path) { if(path.exists()) { File[] files = path.listFiles(); for(int i=0; i<files.length; i++) { if(files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } return(path.delete()); } /** * @param pigContext * @param fileName * @param input * @throws IOException */ public static void createInputFile(PigContext pigContext, String fileName, String[] input) throws IOException { Configuration conf = ConfigurationUtil.toConfiguration( pigContext.getProperties()); createInputFile(FileSystem.get(conf), fileName, input); } public static String[] readOutput(PigContext pigContext, String fileName) throws IOException { Configuration conf = ConfigurationUtil.toConfiguration( pigContext.getProperties()); return readOutput(FileSystem.get(conf), fileName); } public static void printPlan(LogicalPlan logicalPlan ) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(out); LogicalPlanPrinter pp = new LogicalPlanPrinter(logicalPlan,ps); pp.visit(); System.err.println(out.toString()); } public static void printPlan(PhysicalPlan physicalPlan) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(out); physicalPlan.explain(ps, "text", true); System.err.println(out.toString()); } public static List<Tuple> readFile2TupleList(String file, String delimiter) throws IOException{ List<Tuple> tuples=new ArrayList<Tuple>(); String line=null; BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(file))); while((line=reader.readLine())!=null){ String[] tokens=line.split(delimiter); Tuple tuple=TupleFactory.getInstance().newTuple(Arrays.asList(tokens)); tuples.add(tuple); } reader.close(); return tuples; } /** * Delete the existing logFile for the class and set the logging to a * use a new log file and set log level to DEBUG * @param clazz class for which the log file is being set * @param logFile current log file * @return new log file * @throws Exception */ public static File resetLog(Class<?> clazz, File logFile) throws Exception { if (logFile != null) logFile.delete(); Logger logger = Logger.getLogger(clazz); logger.removeAllAppenders(); logger.setLevel(Level.DEBUG); SimpleLayout layout = new SimpleLayout(); File newLogFile = File.createTempFile("log", ""); FileAppender appender = new FileAppender(layout, newLogFile.toString(), false, false, 0); logger.addAppender(appender); return newLogFile; } /** * Check if logFile (does not/)contains the given list of messages. * @param logFile * @param messages * @param expected if true, the messages are expected in the logFile, * otherwise messages should not be there in the log */ public static void checkLogFileMessage(File logFile, String[] messages, boolean expected) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(logFile)); String logMessage = ""; String line; while ((line = reader.readLine()) != null) { logMessage = logMessage + line + "\n"; } reader.close(); for (int i = 0; i < messages.length; i++) { boolean present = logMessage.contains(messages[i]); if (expected) { if(!present){ fail("The message " + messages[i] + " is not present in" + "log file contents: " + logMessage); } }else{ if(present){ fail("The message " + messages[i] + " is present in" + "log file contents: " + logMessage); } } } return ; } catch (IOException e) { fail("caught exception while checking log message :" + e); } } public static LogicalPlan buildLp(PigServer pigServer, String query) throws Exception { pigServer.setBatchOn(); pigServer.registerQuery( query ); java.lang.reflect.Method buildLp = pigServer.getClass().getDeclaredMethod("buildLp"); buildLp.setAccessible(true); return (LogicalPlan ) buildLp.invoke( pigServer ); } public static PhysicalPlan buildPp(PigServer pigServer, String query) throws Exception { LogicalPlan lp = buildLp( pigServer, query ); lp.optimize(pigServer.getPigContext()); return ((HExecutionEngine)pigServer.getPigContext().getExecutionEngine()).compile(lp, pigServer.getPigContext().getProperties()); } public static LogicalPlan parse(String query, PigContext pc) throws FrontendException { Map<String, String> fileNameMap = new HashMap<String, String>(); QueryParserDriver parserDriver = new QueryParserDriver( pc, "test", fileNameMap ); org.apache.pig.newplan.logical.relational.LogicalPlan lp = parserDriver.parse( query ); lp.validate(pc, "test", false); return lp; } public static LogicalPlan parseAndPreprocess(String query, PigContext pc) throws FrontendException { Map<String, String> fileNameMap = new HashMap<String, String>(); QueryParserDriver parserDriver = new QueryParserDriver( pc, "test", fileNameMap ); org.apache.pig.newplan.logical.relational.LogicalPlan lp = parserDriver.parse( query ); lp.validate(pc, "test", false); return lp; } /** * Replaces any alias in given schema that has name that starts with * "NullAlias" with null . it does a case insensitive comparison of * the alias name * @param sch */ public static void schemaReplaceNullAlias(Schema sch){ if(sch == null) return ; for(FieldSchema fs : sch.getFields()){ if(fs.alias != null && fs.alias.toLowerCase().startsWith("nullalias")){ fs.alias = null; } schemaReplaceNullAlias(fs.schema); } } static public void checkQueryOutputsAfterSort(Iterator<Tuple> actualResultsIt, Tuple[] expectedResArray) { List<Tuple> list = new ArrayList<Tuple>(); Collections.addAll(list, expectedResArray); checkQueryOutputsAfterSort(actualResultsIt, list); } static public void convertBagToSortedBag(Tuple t) { for (int i=0;i<t.size();i++) { Object obj = null; try { obj = t.get(i); } catch (ExecException e) { // shall not happen } if (obj instanceof DataBag) { DataBag bag = (DataBag)obj; Iterator<Tuple> iter = bag.iterator(); DataBag sortedBag = DefaultBagFactory.getInstance().newSortedBag(null); while (iter.hasNext()) { Tuple t2 = iter.next(); sortedBag.add(t2); convertBagToSortedBag(t2); } try { t.set(i, sortedBag); } catch (ExecException e) { // shall not happen } } } } static public void checkQueryOutputsAfterSortRecursive(Iterator<Tuple> actualResultsIt, String[] expectedResArray, String schemaString) throws IOException { LogicalSchema resultSchema = org.apache.pig.impl.util.Utils.parseSchema(schemaString); checkQueryOutputsAfterSortRecursive(actualResultsIt, expectedResArray, resultSchema); } /** * Helper function to check if the result of a Pig Query is in line with * expected results. It sorts actual and expected string results before comparison * * @param actualResultsIt Result of the executed Pig query * @param expectedResArray Expected string results to validate against * @param schema fieldSchema of expecteResArray * @throws IOException */ static public void checkQueryOutputsAfterSortRecursive(Iterator<Tuple> actualResultsIt, String[] expectedResArray, LogicalSchema schema) throws IOException { LogicalFieldSchema fs = new LogicalFieldSchema("tuple", schema, DataType.TUPLE); ResourceFieldSchema rfs = new ResourceFieldSchema(fs); LoadCaster caster = new Utf8StorageConverter(); List<Tuple> actualResList = new ArrayList<Tuple>(); while(actualResultsIt.hasNext()){ actualResList.add(actualResultsIt.next()); } List<Tuple> expectedResList = new ArrayList<Tuple>(); for (String str : expectedResArray) { Tuple newTuple = caster.bytesToTuple(str.getBytes(), rfs); expectedResList.add(newTuple); } for (Tuple t : actualResList) { convertBagToSortedBag(t); } for (Tuple t : expectedResList) { convertBagToSortedBag(t); } Collections.sort(actualResList); Collections.sort(expectedResList); Assert.assertEquals("Comparing actual and expected results. ", expectedResList, actualResList); } public static String readFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String result = ""; String line; while ((line=reader.readLine())!=null) { result += line; result += "\n"; } reader.close(); return result; } /** * this removes the signature from the serialized plan changing the way the * unique signature is generated should not break this test * @param plan the plan to canonicalize * @return the cleaned up plan */ public static String removeSignature(String plan) { return plan.replaceAll("','','[^']*','scope','true'\\)\\)", "','','','scope','true'))"); } public static boolean isHadoop203plus() { String version = org.apache.hadoop.util.VersionInfo.getVersion(); if (version.matches("\\b0\\.20\\.2\\b")) return false; return true; } public static boolean isHadoop205() { String version = org.apache.hadoop.util.VersionInfo.getVersion(); if (version.matches("\\b0\\.20\\.205\\..+")) return true; return false; } public static boolean isHadoop1_x() { String version = org.apache.hadoop.util.VersionInfo.getVersion(); if (version.matches("\\b1\\.*\\..+")) return true; return false; } public static boolean isSpark2_2_plus() throws IOException { String sparkVersion = package$.MODULE$.SPARK_VERSION(); return sparkVersion != null && sparkVersion.matches("2\\.([\\d&&[^01]]|[\\d]{2,})\\..*"); } public static void sortQueryOutputsIfNeed(List<Tuple> actualResList, boolean toSort){ if( toSort == true) { for (Tuple t : actualResList) { Util.convertBagToSortedBag(t); } Collections.sort(actualResList); } } public static void checkQueryOutputs(Iterator<Tuple> actualResults, List<Tuple> expectedResults, boolean checkAfterSort) { if (checkAfterSort) { checkQueryOutputsAfterSort(actualResults, expectedResults); } else { checkQueryOutputs(actualResults, expectedResults); } } static public void checkQueryOutputs(Iterator<Tuple> actualResultsIt, String[] expectedResArray, LogicalSchema schema, boolean checkAfterSort) throws IOException { if (checkAfterSort) { checkQueryOutputsAfterSortRecursive(actualResultsIt, expectedResArray, schema); } else { checkQueryOutputs(actualResultsIt, expectedResArray, schema); } } static void checkQueryOutputs(Iterator<Tuple> actualResultsIt, String[] expectedResArray, LogicalSchema schema) throws IOException { LogicalFieldSchema fs = new LogicalFieldSchema("tuple", schema, DataType.TUPLE); ResourceFieldSchema rfs = new ResourceFieldSchema(fs); LoadCaster caster = new Utf8StorageConverter(); List<Tuple> actualResList = new ArrayList<Tuple>(); while (actualResultsIt.hasNext()) { actualResList.add(actualResultsIt.next()); } List<Tuple> expectedResList = new ArrayList<Tuple>(); for (String str : expectedResArray) { Tuple newTuple = caster.bytesToTuple(str.getBytes(), rfs); expectedResList.add(newTuple); } for (Tuple t : actualResList) { convertBagToSortedBag(t); } for (Tuple t : expectedResList) { convertBagToSortedBag(t); } Assert.assertEquals("Comparing actual and expected results. ", expectedResList, actualResList); } public static void assertParallelValues(long defaultParallel, long requestedParallel, long estimatedParallel, long runtimeParallel, Configuration conf) { assertConfLong(conf, "pig.info.reducers.default.parallel", defaultParallel); assertConfLong(conf, "pig.info.reducers.requested.parallel", requestedParallel); assertConfLong(conf, "pig.info.reducers.estimated.parallel", estimatedParallel); assertConfLong(conf, MRConfiguration.REDUCE_TASKS, runtimeParallel); } public static void assertConfLong(Configuration conf, String param, long expected) { assertEquals("Unexpected value found in configs for " + param, expected, conf.getLong(param, -1)); } /** * Returns a PathFilter that filters out filenames that start with _. * @return PathFilter */ public static PathFilter getSuccessMarkerPathFilter() { return new PathFilter() { @Override public boolean accept(Path p) { return !p.getName().startsWith("_"); } }; } /** * * @param expected * Exception class that is expected to be thrown * @param found * Exception that occurred in the test * @param message * expected String to verify against */ public static void assertExceptionAndMessage(Class<?> expected, Exception found, String message) { assertEquals(expected, found.getClass()); assertEquals(found.getMessage(), message); } /** * Called to reset ThreadLocal or static states that PigServer depends on * when a test suite has testcases switching between LOCAL and MAPREDUCE/TEZ * execution modes */ public static void resetStateForExecModeSwitch() { FileLocalizer.setInitialized(false); // For tez testing, we want to avoid TezResourceManager/LocalResource reuse // (when switching between local and mapreduce/tez) TezResourceManager.dropInstance(); // TODO: once we have Tez local mode, we can get rid of this. For now, // if we run this test suite in Tez mode and there are some tests // in LOCAL mode, we need to set ScriptState to // null to force ScriptState gets initialized every time. ScriptState.start(null); } public static boolean isMapredExecType(ExecType execType) { return execType == ExecType.MAPREDUCE; } public static boolean isTezExecType(ExecType execType) { if (execType.name().toLowerCase().startsWith("tez")) { return true; } return false; } public static boolean isSparkExecType(ExecType execType) { if (execType.name().toLowerCase().startsWith("spark")) { return true; } return false; } public static String findPigJarName() { final String suffix = System.getProperty("hadoopversion").equals("20") ? "1" : "2"; File baseDir = new File("."); String[] jarNames = baseDir.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (!name.matches("pig.*h" + suffix + "\\.jar")) { return false; } if (name.contains("all")) { return false; } return true; } }); if (jarNames==null || jarNames.length!=1) { throw new RuntimeException("Cannot find pig.jar"); } return jarNames[0]; } public static ExecType getLocalTestMode() throws Exception { String execType = System.getProperty("test.exec.type"); if (execType != null) { if (execType.equals("tez")) { return ExecTypeProvider.fromString("tez_local"); } else if (execType.equals("spark")) { return ExecTypeProvider.fromString("spark_local"); } } return ExecTypeProvider.fromString("local"); } public static void createLogAppender(String appenderName, Writer writer, Class...clazzes) { WriterAppender writerAppender = new WriterAppender(new PatternLayout("%d [%t] %-5p %c %x - %m%n"), writer); writerAppender.setName(appenderName); for (Class clazz : clazzes) { Logger logger = Logger.getLogger(clazz); logger.addAppender(writerAppender); } } public static void removeLogAppender(String appenderName, Class...clazzes) { for (Class clazz : clazzes) { Logger logger = Logger.getLogger(clazz); Appender appender = logger.getAppender(appenderName); appender.close(); logger.removeAppender(appenderName); } } public static Path getFirstPartFile(Path path) throws Exception { FileStatus[] parts = FileSystem.get(path.toUri(), new Configuration()).listStatus(path, new PathFilter() { @Override public boolean accept(Path path) { return path.getName().startsWith("part-"); } }); return parts[0].getPath(); } public static File getFirstPartFile(File dir) throws Exception { File[] parts = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith("part-"); }; }); return parts[0]; } @SuppressWarnings("rawtypes") public static String getTestDirectory(Class testClass) { return TEST_DIR + Path.SEPARATOR + "testdata" + Path.SEPARATOR +testClass.getSimpleName(); } }
apache/pig
test/org/apache/pig/test/Util.java
Java
apache-2.0
58,248
FROM balenalib/amd64-alpine:3.6 RUN apk add --update \ openrc \ && rm -rf /var/cache/apk/* # Config OpenRC RUN sed -i '/tty/d' /etc/inittab COPY rc.conf /etc/ COPY resin /etc/init.d/ RUN rc-update add resin default COPY entry.sh /usr/bin/entry.sh ENTRYPOINT ["/usr/bin/entry.sh"]
nghiant2710/base-images
examples/INITSYSTEM/openrc/Dockerfile
Dockerfile
apache-2.0
306
import os import sys import argparse from pandaharvester.harvesterconfig import harvester_config from pandaharvester.harvestermisc.selfcheck import harvesterPackageInfo def main(): oparser = argparse.ArgumentParser(prog='prescript', add_help=True) oparser.add_argument('-f', '--local_info_file', action='store', dest='local_info_file', help='path of harvester local info file') if len(sys.argv) == 1: print('No argument or flag specified. Did nothing') sys.exit(0) args = oparser.parse_args(sys.argv[1:]) local_info_file = os.path.normpath(args.local_info_file) hpi = harvesterPackageInfo(local_info_file=local_info_file) if hpi.package_changed: print('Harvester package changed') #TODO pass hpi.renew_local_info() else: print('Harvester package unchanged. Skipped') if __name__ == '__main__': main()
dougbenjamin/panda-harvester
pandaharvester/harvesterscripts/prescript.py
Python
apache-2.0
901
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class StringConcatTests : CSharpTestBase { [Fact] public void ConcatConsts() { var source = @" using System; public class Test { static void Main() { Console.WriteLine(""A"" + ""B""); Console.WriteLine(""A"" + (string)null); Console.WriteLine(""A"" + (object)null); Console.WriteLine(""A"" + (object)null + ""A"" + (object)null); Console.WriteLine((string)null + ""B""); Console.WriteLine((object)null + ""B""); Console.WriteLine((string)null + (object)null); Console.WriteLine(""#""); Console.WriteLine((object)null + (string)null); Console.WriteLine(""#""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"AB A A AA B B # #"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 101 (0x65) .maxstack 1 IL_0000: ldstr ""AB"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ldstr ""A"" IL_000f: call ""void System.Console.WriteLine(string)"" IL_0014: ldstr ""A"" IL_0019: call ""void System.Console.WriteLine(string)"" IL_001e: ldstr ""AA"" IL_0023: call ""void System.Console.WriteLine(string)"" IL_0028: ldstr ""B"" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ldstr ""B"" IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ldstr """" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: ldstr ""#"" IL_004b: call ""void System.Console.WriteLine(string)"" IL_0050: ldstr """" IL_0055: call ""void System.Console.WriteLine(string)"" IL_005a: ldstr ""#"" IL_005f: call ""void System.Console.WriteLine(string)"" IL_0064: ret } "); } [Fact] public void ConcatDefaults() { var source = @" using System; public class Test { static void Main() { Console.WriteLine(""A"" + ""B""); Console.WriteLine(""A"" + default(string)); Console.WriteLine(""A"" + default(object)); Console.WriteLine(""A"" + default(object) + ""A"" + default(object)); Console.WriteLine(default(string) + ""B""); Console.WriteLine(default(object) + ""B""); Console.WriteLine(default(string) + default(object)); Console.WriteLine(""#""); Console.WriteLine(default(object) + default(string)); Console.WriteLine(""#""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"AB A A AA B B # #"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 101 (0x65) .maxstack 1 IL_0000: ldstr ""AB"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ldstr ""A"" IL_000f: call ""void System.Console.WriteLine(string)"" IL_0014: ldstr ""A"" IL_0019: call ""void System.Console.WriteLine(string)"" IL_001e: ldstr ""AA"" IL_0023: call ""void System.Console.WriteLine(string)"" IL_0028: ldstr ""B"" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ldstr ""B"" IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ldstr """" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: ldstr ""#"" IL_004b: call ""void System.Console.WriteLine(string)"" IL_0050: ldstr """" IL_0055: call ""void System.Console.WriteLine(string)"" IL_005a: ldstr ""#"" IL_005f: call ""void System.Console.WriteLine(string)"" IL_0064: ret } "); } [Fact] public void ConcatFour() { var source = @" using System; public class Test { static void Main() { var s = ""qq""; var ss = s + s + s + s; Console.WriteLine(ss); } } "; var comp = CompileAndVerify(source, expectedOutput: @"qqqqqqqq" ); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 19 (0x13) .maxstack 4 IL_0000: ldstr ""qq"" IL_0005: dup IL_0006: dup IL_0007: dup IL_0008: call ""string string.Concat(string, string, string, string)"" IL_000d: call ""void System.Console.WriteLine(string)"" IL_0012: ret } "); } [Fact] public void ConcatMerge() { var source = @" using System; public class Test { private static string S = ""F""; private static object O = ""O""; static void Main() { Console.WriteLine( (S + ""A"") + (""B"" + S)); Console.WriteLine( (O + ""A"") + (""B"" + O)); Console.WriteLine( ((S + ""A"") + (""B"" + S)) + ((O + ""A"") + (""B"" + O))); Console.WriteLine( ((O + ""A"") + (S + ""A"")) + ((""B"" + O) + (S + ""A""))); } } "; var comp = CompileAndVerify(source, expectedOutput: @"FABF OABO FABFOABO OAFABOFA"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 259 (0x103) .maxstack 5 IL_0000: ldsfld ""string Test.S"" IL_0005: ldstr ""AB"" IL_000a: ldsfld ""string Test.S"" IL_000f: call ""string string.Concat(string, string, string)"" IL_0014: call ""void System.Console.WriteLine(string)"" IL_0019: ldsfld ""object Test.O"" IL_001e: dup IL_001f: brtrue.s IL_0025 IL_0021: pop IL_0022: ldnull IL_0023: br.s IL_002a IL_0025: callvirt ""string object.ToString()"" IL_002a: ldstr ""AB"" IL_002f: ldsfld ""object Test.O"" IL_0034: dup IL_0035: brtrue.s IL_003b IL_0037: pop IL_0038: ldnull IL_0039: br.s IL_0040 IL_003b: callvirt ""string object.ToString()"" IL_0040: call ""string string.Concat(string, string, string)"" IL_0045: call ""void System.Console.WriteLine(string)"" IL_004a: ldc.i4.6 IL_004b: newarr ""string"" IL_0050: dup IL_0051: ldc.i4.0 IL_0052: ldsfld ""string Test.S"" IL_0057: stelem.ref IL_0058: dup IL_0059: ldc.i4.1 IL_005a: ldstr ""AB"" IL_005f: stelem.ref IL_0060: dup IL_0061: ldc.i4.2 IL_0062: ldsfld ""string Test.S"" IL_0067: stelem.ref IL_0068: dup IL_0069: ldc.i4.3 IL_006a: ldsfld ""object Test.O"" IL_006f: dup IL_0070: brtrue.s IL_0076 IL_0072: pop IL_0073: ldnull IL_0074: br.s IL_007b IL_0076: callvirt ""string object.ToString()"" IL_007b: stelem.ref IL_007c: dup IL_007d: ldc.i4.4 IL_007e: ldstr ""AB"" IL_0083: stelem.ref IL_0084: dup IL_0085: ldc.i4.5 IL_0086: ldsfld ""object Test.O"" IL_008b: dup IL_008c: brtrue.s IL_0092 IL_008e: pop IL_008f: ldnull IL_0090: br.s IL_0097 IL_0092: callvirt ""string object.ToString()"" IL_0097: stelem.ref IL_0098: call ""string string.Concat(params string[])"" IL_009d: call ""void System.Console.WriteLine(string)"" IL_00a2: ldc.i4.7 IL_00a3: newarr ""string"" IL_00a8: dup IL_00a9: ldc.i4.0 IL_00aa: ldsfld ""object Test.O"" IL_00af: dup IL_00b0: brtrue.s IL_00b6 IL_00b2: pop IL_00b3: ldnull IL_00b4: br.s IL_00bb IL_00b6: callvirt ""string object.ToString()"" IL_00bb: stelem.ref IL_00bc: dup IL_00bd: ldc.i4.1 IL_00be: ldstr ""A"" IL_00c3: stelem.ref IL_00c4: dup IL_00c5: ldc.i4.2 IL_00c6: ldsfld ""string Test.S"" IL_00cb: stelem.ref IL_00cc: dup IL_00cd: ldc.i4.3 IL_00ce: ldstr ""AB"" IL_00d3: stelem.ref IL_00d4: dup IL_00d5: ldc.i4.4 IL_00d6: ldsfld ""object Test.O"" IL_00db: dup IL_00dc: brtrue.s IL_00e2 IL_00de: pop IL_00df: ldnull IL_00e0: br.s IL_00e7 IL_00e2: callvirt ""string object.ToString()"" IL_00e7: stelem.ref IL_00e8: dup IL_00e9: ldc.i4.5 IL_00ea: ldsfld ""string Test.S"" IL_00ef: stelem.ref IL_00f0: dup IL_00f1: ldc.i4.6 IL_00f2: ldstr ""A"" IL_00f7: stelem.ref IL_00f8: call ""string string.Concat(params string[])"" IL_00fd: call ""void System.Console.WriteLine(string)"" IL_0102: ret } "); } [Fact] public void ConcatMergeFromOne() { var source = @" using System; public class Test { private static string S = ""F""; static void Main() { Console.WriteLine( (S + null) + (S + ""A"") + (""B"" + S) + (S + null)); } } "; var comp = CompileAndVerify(source, expectedOutput: @"FFABFF"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 57 (0x39) .maxstack 4 IL_0000: ldc.i4.5 IL_0001: newarr ""string"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldsfld ""string Test.S"" IL_000d: stelem.ref IL_000e: dup IL_000f: ldc.i4.1 IL_0010: ldsfld ""string Test.S"" IL_0015: stelem.ref IL_0016: dup IL_0017: ldc.i4.2 IL_0018: ldstr ""AB"" IL_001d: stelem.ref IL_001e: dup IL_001f: ldc.i4.3 IL_0020: ldsfld ""string Test.S"" IL_0025: stelem.ref IL_0026: dup IL_0027: ldc.i4.4 IL_0028: ldsfld ""string Test.S"" IL_002d: stelem.ref IL_002e: call ""string string.Concat(params string[])"" IL_0033: call ""void System.Console.WriteLine(string)"" IL_0038: ret } "); } [Fact] public void ConcatOneArg() { var source = @" using System; public class Test { private static string S = ""F""; private static object O = ""O""; static void Main() { Console.WriteLine(O + null); Console.WriteLine(S + null); Console.WriteLine(O?.ToString() + null); } } "; var comp = CompileAndVerify(source, expectedOutput: @"O F O"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 82 (0x52) .maxstack 2 IL_0000: ldsfld ""object Test.O"" IL_0005: dup IL_0006: brtrue.s IL_000c IL_0008: pop IL_0009: ldnull IL_000a: br.s IL_0011 IL_000c: callvirt ""string object.ToString()"" IL_0011: dup IL_0012: brtrue.s IL_001a IL_0014: pop IL_0015: ldstr """" IL_001a: call ""void System.Console.WriteLine(string)"" IL_001f: ldsfld ""string Test.S"" IL_0024: dup IL_0025: brtrue.s IL_002d IL_0027: pop IL_0028: ldstr """" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ldsfld ""object Test.O"" IL_0037: dup IL_0038: brtrue.s IL_003e IL_003a: pop IL_003b: ldnull IL_003c: br.s IL_0043 IL_003e: callvirt ""string object.ToString()"" IL_0043: dup IL_0044: brtrue.s IL_004c IL_0046: pop IL_0047: ldstr """" IL_004c: call ""void System.Console.WriteLine(string)"" IL_0051: ret } "); } [Fact] public void ConcatOneArgWithNullToString() { var source = @" using System; public class Test { private static object C = new C(); static void Main() { Console.WriteLine((C + null) == """" ? ""Y"" : ""N""); Console.WriteLine((C + null + null) == """" ? ""Y"" : ""N""); } } public class C { public override string ToString() => null; } "; var comp = CompileAndVerify(source, expectedOutput: @"Y Y"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 111 (0x6f) .maxstack 2 IL_0000: ldsfld ""object Test.C"" IL_0005: dup IL_0006: brtrue.s IL_000c IL_0008: pop IL_0009: ldnull IL_000a: br.s IL_0011 IL_000c: callvirt ""string object.ToString()"" IL_0011: dup IL_0012: brtrue.s IL_001a IL_0014: pop IL_0015: ldstr """" IL_001a: ldstr """" IL_001f: call ""bool string.op_Equality(string, string)"" IL_0024: brtrue.s IL_002d IL_0026: ldstr ""N"" IL_002b: br.s IL_0032 IL_002d: ldstr ""Y"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ldsfld ""object Test.C"" IL_003c: dup IL_003d: brtrue.s IL_0043 IL_003f: pop IL_0040: ldnull IL_0041: br.s IL_0048 IL_0043: callvirt ""string object.ToString()"" IL_0048: dup IL_0049: brtrue.s IL_0051 IL_004b: pop IL_004c: ldstr """" IL_0051: ldstr """" IL_0056: call ""bool string.op_Equality(string, string)"" IL_005b: brtrue.s IL_0064 IL_005d: ldstr ""N"" IL_0062: br.s IL_0069 IL_0064: ldstr ""Y"" IL_0069: call ""void System.Console.WriteLine(string)"" IL_006e: ret } "); } [Fact] public void ConcatOneArgWithExplicitConcatCall() { var source = @" using System; public class Test { private static object O = ""O""; static void Main() { Console.WriteLine(string.Concat(O) + null); Console.WriteLine(string.Concat(O) + null + null); } } "; var comp = CompileAndVerify(source, expectedOutput: @"O O"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 49 (0x31) .maxstack 2 IL_0000: ldsfld ""object Test.O"" IL_0005: call ""string string.Concat(object)"" IL_000a: dup IL_000b: brtrue.s IL_0013 IL_000d: pop IL_000e: ldstr """" IL_0013: call ""void System.Console.WriteLine(string)"" IL_0018: ldsfld ""object Test.O"" IL_001d: call ""string string.Concat(object)"" IL_0022: dup IL_0023: brtrue.s IL_002b IL_0025: pop IL_0026: ldstr """" IL_002b: call ""void System.Console.WriteLine(string)"" IL_0030: ret } "); } [Fact] public void ConcatEmptyString() { var source = @" using System; public class Test { private static string S = ""F""; private static object O = ""O""; static void Main() { Console.WriteLine(O + """"); Console.WriteLine(S + """"); } } "; var comp = CompileAndVerify(source, expectedOutput: @"O F"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 51 (0x33) .maxstack 2 IL_0000: ldsfld ""object Test.O"" IL_0005: dup IL_0006: brtrue.s IL_000c IL_0008: pop IL_0009: ldnull IL_000a: br.s IL_0011 IL_000c: callvirt ""string object.ToString()"" IL_0011: dup IL_0012: brtrue.s IL_001a IL_0014: pop IL_0015: ldstr """" IL_001a: call ""void System.Console.WriteLine(string)"" IL_001f: ldsfld ""string Test.S"" IL_0024: dup IL_0025: brtrue.s IL_002d IL_0027: pop IL_0028: ldstr """" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ret } "); } [Fact] [WorkItem(679120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/679120")] public void ConcatEmptyArray() { var source = @" using System; public class Test { static void Main() { Console.WriteLine(""Start""); Console.WriteLine(string.Concat(new string[] {})); Console.WriteLine(string.Concat(new string[] {}) + string.Concat(new string[] {})); Console.WriteLine(""A"" + string.Concat(new string[] {})); Console.WriteLine(string.Concat(new string[] {}) + ""B""); Console.WriteLine(""End""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"Start A B End"); comp.VerifyDiagnostics(); // NOTE: Dev11 doesn't optimize away string.Concat(new string[0]) either. // We could add an optimization, but it's unlikely to occur in real code. comp.VerifyIL("Test.Main", @" { // Code size 67 (0x43) .maxstack 1 IL_0000: ldstr ""Start"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ldc.i4.0 IL_000b: newarr ""string"" IL_0010: call ""string string.Concat(params string[])"" IL_0015: call ""void System.Console.WriteLine(string)"" IL_001a: ldstr """" IL_001f: call ""void System.Console.WriteLine(string)"" IL_0024: ldstr ""A"" IL_0029: call ""void System.Console.WriteLine(string)"" IL_002e: ldstr ""B"" IL_0033: call ""void System.Console.WriteLine(string)"" IL_0038: ldstr ""End"" IL_003d: call ""void System.Console.WriteLine(string)"" IL_0042: ret } "); } [WorkItem(529064, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529064")] [Fact] public void TestStringConcatOnLiteralAndCompound() { var source = @" public class Test { static string field01 = ""A""; static string field02 = ""B""; static void Main() { field01 += field02 + ""C"" + ""D""; } } "; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 26 (0x1a) .maxstack 3 IL_0000: ldsfld ""string Test.field01"" IL_0005: ldsfld ""string Test.field02"" IL_000a: ldstr ""CD"" IL_000f: call ""string string.Concat(string, string, string)"" IL_0014: stsfld ""string Test.field01"" IL_0019: ret } "); } [Fact] public void ConcatGeneric() { var source = @" using System; public class Test { static void Main() { TestMethod<int>(); } private static void TestMethod<T>() { Console.WriteLine(""A"" + default(T)); Console.WriteLine(""A"" + default(T) + ""A"" + default(T)); Console.WriteLine(default(T) + ""B""); Console.WriteLine(default(string) + default(T)); Console.WriteLine(""#""); Console.WriteLine(default(T) + default(string)); Console.WriteLine(""#""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"A0 A0A0 0B 0 # 0 #"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.TestMethod<T>()", @" { // Code size 291 (0x123) .maxstack 4 .locals init (T V_0) IL_0000: ldstr ""A"" IL_0005: ldloca.s V_0 IL_0007: initobj ""T"" IL_000d: ldloc.0 IL_000e: box ""T"" IL_0013: brtrue.s IL_0018 IL_0015: ldnull IL_0016: br.s IL_0025 IL_0018: ldloca.s V_0 IL_001a: constrained. ""T"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""string string.Concat(string, string)"" IL_002a: call ""void System.Console.WriteLine(string)"" IL_002f: ldstr ""A"" IL_0034: ldloca.s V_0 IL_0036: initobj ""T"" IL_003c: ldloc.0 IL_003d: box ""T"" IL_0042: brtrue.s IL_0047 IL_0044: ldnull IL_0045: br.s IL_0054 IL_0047: ldloca.s V_0 IL_0049: constrained. ""T"" IL_004f: callvirt ""string object.ToString()"" IL_0054: ldstr ""A"" IL_0059: ldloca.s V_0 IL_005b: initobj ""T"" IL_0061: ldloc.0 IL_0062: box ""T"" IL_0067: brtrue.s IL_006c IL_0069: ldnull IL_006a: br.s IL_0079 IL_006c: ldloca.s V_0 IL_006e: constrained. ""T"" IL_0074: callvirt ""string object.ToString()"" IL_0079: call ""string string.Concat(string, string, string, string)"" IL_007e: call ""void System.Console.WriteLine(string)"" IL_0083: ldloca.s V_0 IL_0085: initobj ""T"" IL_008b: ldloc.0 IL_008c: box ""T"" IL_0091: brtrue.s IL_0096 IL_0093: ldnull IL_0094: br.s IL_00a3 IL_0096: ldloca.s V_0 IL_0098: constrained. ""T"" IL_009e: callvirt ""string object.ToString()"" IL_00a3: ldstr ""B"" IL_00a8: call ""string string.Concat(string, string)"" IL_00ad: call ""void System.Console.WriteLine(string)"" IL_00b2: ldloca.s V_0 IL_00b4: initobj ""T"" IL_00ba: ldloc.0 IL_00bb: box ""T"" IL_00c0: brtrue.s IL_00c5 IL_00c2: ldnull IL_00c3: br.s IL_00d2 IL_00c5: ldloca.s V_0 IL_00c7: constrained. ""T"" IL_00cd: callvirt ""string object.ToString()"" IL_00d2: dup IL_00d3: brtrue.s IL_00db IL_00d5: pop IL_00d6: ldstr """" IL_00db: call ""void System.Console.WriteLine(string)"" IL_00e0: ldstr ""#"" IL_00e5: call ""void System.Console.WriteLine(string)"" IL_00ea: ldloca.s V_0 IL_00ec: initobj ""T"" IL_00f2: ldloc.0 IL_00f3: box ""T"" IL_00f8: brtrue.s IL_00fd IL_00fa: ldnull IL_00fb: br.s IL_010a IL_00fd: ldloca.s V_0 IL_00ff: constrained. ""T"" IL_0105: callvirt ""string object.ToString()"" IL_010a: dup IL_010b: brtrue.s IL_0113 IL_010d: pop IL_010e: ldstr """" IL_0113: call ""void System.Console.WriteLine(string)"" IL_0118: ldstr ""#"" IL_011d: call ""void System.Console.WriteLine(string)"" IL_0122: ret } "); } [Fact] public void ConcatGenericConstrained() { var source = @" using System; public class Test { static void Main() { TestMethod<Exception, Exception>(); } private static void TestMethod<T, U>() where T:class where U: class { Console.WriteLine(""A"" + default(T)); Console.WriteLine(""A"" + default(T) + ""A"" + default(T)); Console.WriteLine(default(T) + ""B""); Console.WriteLine(default(string) + default(T)); Console.WriteLine(""#""); Console.WriteLine(default(T) + default(string)); Console.WriteLine(""#""); Console.WriteLine(""A"" + (U)null); Console.WriteLine(""A"" + (U)null + ""A"" + (U)null); Console.WriteLine((U)null + ""B""); Console.WriteLine(default(string) + (U)null); Console.WriteLine(""#""); Console.WriteLine((U)null + default(string)); Console.WriteLine(""#""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"A AA B # # A AA B # #"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.TestMethod<T, U>()", @" { // Code size 141 (0x8d) .maxstack 1 IL_0000: ldstr ""A"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ldstr ""AA"" IL_000f: call ""void System.Console.WriteLine(string)"" IL_0014: ldstr ""B"" IL_0019: call ""void System.Console.WriteLine(string)"" IL_001e: ldstr """" IL_0023: call ""void System.Console.WriteLine(string)"" IL_0028: ldstr ""#"" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ldstr """" IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ldstr ""#"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: ldstr ""A"" IL_004b: call ""void System.Console.WriteLine(string)"" IL_0050: ldstr ""AA"" IL_0055: call ""void System.Console.WriteLine(string)"" IL_005a: ldstr ""B"" IL_005f: call ""void System.Console.WriteLine(string)"" IL_0064: ldstr """" IL_0069: call ""void System.Console.WriteLine(string)"" IL_006e: ldstr ""#"" IL_0073: call ""void System.Console.WriteLine(string)"" IL_0078: ldstr """" IL_007d: call ""void System.Console.WriteLine(string)"" IL_0082: ldstr ""#"" IL_0087: call ""void System.Console.WriteLine(string)"" IL_008c: ret } "); } [Fact] public void ConcatGenericUnconstrained() { var source = @" using System; class Test { static void Main() { var p1 = new Printer<string>(""F""); p1.Print(""P""); p1.Print(null); var p2 = new Printer<string>(null); p2.Print(""P""); p2.Print(null); var p3 = new Printer<MutableStruct>(new MutableStruct()); MutableStruct m = new MutableStruct(); p3.Print(m); p3.Print(m); } } class Printer<T> { private T field; public Printer(T field) => this.field = field; public void Print(T p) { Console.WriteLine("""" + p + p + field + field); } } struct MutableStruct { private int i; public override string ToString() => (++i).ToString(); } "; var comp = CompileAndVerify(source, expectedOutput: @"PPFF FF PP 1111 1111"); comp.VerifyDiagnostics(); comp.VerifyIL("Printer<T>.Print", @" { // Code size 125 (0x7d) .maxstack 4 .locals init (T V_0) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: box ""T"" IL_0008: brtrue.s IL_000d IL_000a: ldnull IL_000b: br.s IL_001a IL_000d: ldloca.s V_0 IL_000f: constrained. ""T"" IL_0015: callvirt ""string object.ToString()"" IL_001a: ldarg.1 IL_001b: stloc.0 IL_001c: ldloc.0 IL_001d: box ""T"" IL_0022: brtrue.s IL_0027 IL_0024: ldnull IL_0025: br.s IL_0034 IL_0027: ldloca.s V_0 IL_0029: constrained. ""T"" IL_002f: callvirt ""string object.ToString()"" IL_0034: ldarg.0 IL_0035: ldfld ""T Printer<T>.field"" IL_003a: stloc.0 IL_003b: ldloc.0 IL_003c: box ""T"" IL_0041: brtrue.s IL_0046 IL_0043: ldnull IL_0044: br.s IL_0053 IL_0046: ldloca.s V_0 IL_0048: constrained. ""T"" IL_004e: callvirt ""string object.ToString()"" IL_0053: ldarg.0 IL_0054: ldfld ""T Printer<T>.field"" IL_0059: stloc.0 IL_005a: ldloc.0 IL_005b: box ""T"" IL_0060: brtrue.s IL_0065 IL_0062: ldnull IL_0063: br.s IL_0072 IL_0065: ldloca.s V_0 IL_0067: constrained. ""T"" IL_006d: callvirt ""string object.ToString()"" IL_0072: call ""string string.Concat(string, string, string, string)"" IL_0077: call ""void System.Console.WriteLine(string)"" IL_007c: ret } "); } [Fact] public void ConcatGenericConstrainedClass() { var source = @" using System; class Test { static void Main() { var p1 = new Printer<string>(""F""); p1.Print(""P""); p1.Print(null); var p2 = new Printer<string>(null); p2.Print(""P""); p2.Print(null); } } class Printer<T> where T : class { private T field; public Printer(T field) => this.field = field; public void Print(T p) { Console.WriteLine("""" + p + p + field + field); } }"; var comp = CompileAndVerify(source, expectedOutput: @"PPFF FF PP "); comp.VerifyDiagnostics(); comp.VerifyIL("Printer<T>.Print", @" { // Code size 93 (0x5d) .maxstack 5 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: dup IL_0007: brtrue.s IL_000d IL_0009: pop IL_000a: ldnull IL_000b: br.s IL_0012 IL_000d: callvirt ""string object.ToString()"" IL_0012: ldarg.1 IL_0013: box ""T"" IL_0018: dup IL_0019: brtrue.s IL_001f IL_001b: pop IL_001c: ldnull IL_001d: br.s IL_0024 IL_001f: callvirt ""string object.ToString()"" IL_0024: ldarg.0 IL_0025: ldfld ""T Printer<T>.field"" IL_002a: box ""T"" IL_002f: dup IL_0030: brtrue.s IL_0036 IL_0032: pop IL_0033: ldnull IL_0034: br.s IL_003b IL_0036: callvirt ""string object.ToString()"" IL_003b: ldarg.0 IL_003c: ldfld ""T Printer<T>.field"" IL_0041: box ""T"" IL_0046: dup IL_0047: brtrue.s IL_004d IL_0049: pop IL_004a: ldnull IL_004b: br.s IL_0052 IL_004d: callvirt ""string object.ToString()"" IL_0052: call ""string string.Concat(string, string, string, string)"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: ret } "); } [Fact] public void ConcatGenericConstrainedStruct() { var source = @" using System; class Test { static void Main() { MutableStruct m = new MutableStruct(); var p1 = new Printer<MutableStruct>(new MutableStruct()); p1.Print(m); p1.Print(m); } } class Printer<T> where T : struct { private T field; public Printer(T field) => this.field = field; public void Print(T p) { Console.WriteLine("""" + p + p + field + field); } } struct MutableStruct { private int i; public override string ToString() => (++i).ToString(); }"; var comp = CompileAndVerify(source, expectedOutput: @"1111 1111"); comp.VerifyDiagnostics(); comp.VerifyIL("Printer<T>.Print", @" { // Code size 81 (0x51) .maxstack 4 .locals init (T V_0) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: constrained. ""T"" IL_000a: callvirt ""string object.ToString()"" IL_000f: ldarg.1 IL_0010: stloc.0 IL_0011: ldloca.s V_0 IL_0013: constrained. ""T"" IL_0019: callvirt ""string object.ToString()"" IL_001e: ldarg.0 IL_001f: ldfld ""T Printer<T>.field"" IL_0024: stloc.0 IL_0025: ldloca.s V_0 IL_0027: constrained. ""T"" IL_002d: callvirt ""string object.ToString()"" IL_0032: ldarg.0 IL_0033: ldfld ""T Printer<T>.field"" IL_0038: stloc.0 IL_0039: ldloca.s V_0 IL_003b: constrained. ""T"" IL_0041: callvirt ""string object.ToString()"" IL_0046: call ""string string.Concat(string, string, string, string)"" IL_004b: call ""void System.Console.WriteLine(string)"" IL_0050: ret } "); } [Fact] public void ConcatWithOtherOptimizations() { var source = @" using System; public class Test { static void Main() { var expr1 = ""hi""; var expr2 = ""bye""; // expr1 is optimized away // only expr2 should be lifted!! Func<string> f = () => (""abc"" + ""def"" + null ?? expr1 + ""moo"" + ""baz"") + expr2; System.Console.WriteLine(f()); } } "; var comp = CompileAndVerify(source, expectedOutput: @"abcdefbye"); comp.VerifyDiagnostics(); // IMPORTANT!! only c__DisplayClass0.expr2 should be initialized, // there should not be such thing as c__DisplayClass0.expr1 comp.VerifyIL("Test.Main", @" { // Code size 38 (0x26) .maxstack 3 IL_0000: newobj ""Test.<>c__DisplayClass0_0..ctor()"" IL_0005: dup IL_0006: ldstr ""bye"" IL_000b: stfld ""string Test.<>c__DisplayClass0_0.expr2"" IL_0010: ldftn ""string Test.<>c__DisplayClass0_0.<Main>b__0()"" IL_0016: newobj ""System.Func<string>..ctor(object, System.IntPtr)"" IL_001b: callvirt ""string System.Func<string>.Invoke()"" IL_0020: call ""void System.Console.WriteLine(string)"" IL_0025: ret } "); } [Fact, WorkItem(1092853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1092853")] public void ConcatWithNullCoalescedNullLiteral() { const string source = @" class Repro { static string Bug(string s) { string x = """"; x += s ?? null; return x; } static void Main() { System.Console.Write(""\""{0}\"""", Bug(null)); } }"; var comp = CompileAndVerify(source, expectedOutput: "\"\""); comp.VerifyDiagnostics(); comp.VerifyIL("Repro.Bug", @" { // Code size 17 (0x11) .maxstack 3 IL_0000: ldstr """" IL_0005: ldarg.0 IL_0006: dup IL_0007: brtrue.s IL_000b IL_0009: pop IL_000a: ldnull IL_000b: call ""string string.Concat(string, string)"" IL_0010: ret } "); } [Fact, WorkItem(1092853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1092853")] public void ConcatWithNullCoalescedNullLiteral_2() { const string source = @" class Repro { static string Bug(string s) { string x = """"; x += s ?? ((string)null ?? null); return x; } static void Main() { System.Console.Write(""\""{0}\"""", Bug(null)); } }"; var comp = CompileAndVerify(source, expectedOutput: "\"\""); comp.VerifyIL("Repro.Bug", @" { // Code size 17 (0x11) .maxstack 3 IL_0000: ldstr """" IL_0005: ldarg.0 IL_0006: dup IL_0007: brtrue.s IL_000b IL_0009: pop IL_000a: ldnull IL_000b: call ""string string.Concat(string, string)"" IL_0010: ret } "); } [Fact] public void ConcatMutableStruct() { var source = @" using System; class Test { static MutableStruct f = new MutableStruct(); static void Main() { MutableStruct l = new MutableStruct(); Console.WriteLine("""" + l + l + f + f); } } struct MutableStruct { private int i; public override string ToString() => (++i).ToString(); } "; var comp = CompileAndVerify(source, expectedOutput: @"1111"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 87 (0x57) .maxstack 4 .locals init (MutableStruct V_0, //l MutableStruct V_1) IL_0000: ldloca.s V_0 IL_0002: initobj ""MutableStruct"" IL_0008: ldloc.0 IL_0009: stloc.1 IL_000a: ldloca.s V_1 IL_000c: constrained. ""MutableStruct"" IL_0012: callvirt ""string object.ToString()"" IL_0017: ldloc.0 IL_0018: stloc.1 IL_0019: ldloca.s V_1 IL_001b: constrained. ""MutableStruct"" IL_0021: callvirt ""string object.ToString()"" IL_0026: ldsfld ""MutableStruct Test.f"" IL_002b: stloc.1 IL_002c: ldloca.s V_1 IL_002e: constrained. ""MutableStruct"" IL_0034: callvirt ""string object.ToString()"" IL_0039: ldsfld ""MutableStruct Test.f"" IL_003e: stloc.1 IL_003f: ldloca.s V_1 IL_0041: constrained. ""MutableStruct"" IL_0047: callvirt ""string object.ToString()"" IL_004c: call ""string string.Concat(string, string, string, string)"" IL_0051: call ""void System.Console.WriteLine(string)"" IL_0056: ret }"); } [Fact] public void ConcatMutableStructsSideEffects() { const string source = @" using System; using static System.Console; struct Mutable { int x; public override string ToString() => (x++).ToString(); } class Test { static Mutable m = new Mutable(); static void Main() { Write(""("" + m + "")""); // (0) Write(""("" + m + "")""); // (0) Write(""("" + m.ToString() + "")""); // (0) Write(""("" + m.ToString() + "")""); // (1) Write(""("" + m.ToString() + "")""); // (2) Nullable<Mutable> n = new Mutable(); Write(""("" + n + "")""); // (0) Write(""("" + n + "")""); // (0) Write(""("" + n.ToString() + "")""); // (0) Write(""("" + n.ToString() + "")""); // (1) Write(""("" + n.ToString() + "")""); // (2) } }"; CompileAndVerify(source, expectedOutput: "(0)(0)(0)(1)(2)(0)(0)(0)(1)(2)"); } [Fact] public void ConcatReadonlyStruct() { var source = @" using System; class Test { static ReadonlyStruct f = new ReadonlyStruct(); static void Main() { ReadonlyStruct l = new ReadonlyStruct(); Console.WriteLine("""" + l + l + f + f); } } readonly struct ReadonlyStruct { public override string ToString() => ""R""; } "; var comp = CompileAndVerify(source, expectedOutput: @"RRRR"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 77 (0x4d) .maxstack 4 .locals init (ReadonlyStruct V_0) //l IL_0000: ldloca.s V_0 IL_0002: initobj ""ReadonlyStruct"" IL_0008: ldloca.s V_0 IL_000a: constrained. ""ReadonlyStruct"" IL_0010: callvirt ""string object.ToString()"" IL_0015: ldloca.s V_0 IL_0017: constrained. ""ReadonlyStruct"" IL_001d: callvirt ""string object.ToString()"" IL_0022: ldsflda ""ReadonlyStruct Test.f"" IL_0027: constrained. ""ReadonlyStruct"" IL_002d: callvirt ""string object.ToString()"" IL_0032: ldsflda ""ReadonlyStruct Test.f"" IL_0037: constrained. ""ReadonlyStruct"" IL_003d: callvirt ""string object.ToString()"" IL_0042: call ""string string.Concat(string, string, string, string)"" IL_0047: call ""void System.Console.WriteLine(string)"" IL_004c: ret } "); } [Fact] public void ConcatStructWithReadonlyToString() { var source = @" using System; class Test { static StructWithReadonlyToString f = new StructWithReadonlyToString(); static void Main() { StructWithReadonlyToString l = new StructWithReadonlyToString(); Console.WriteLine("""" + l + l + f + f); } } struct StructWithReadonlyToString { public readonly override string ToString() => ""R""; } "; var comp = CompileAndVerify(source, expectedOutput: @"RRRR"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 77 (0x4d) .maxstack 4 .locals init (StructWithReadonlyToString V_0) //l IL_0000: ldloca.s V_0 IL_0002: initobj ""StructWithReadonlyToString"" IL_0008: ldloca.s V_0 IL_000a: constrained. ""StructWithReadonlyToString"" IL_0010: callvirt ""string object.ToString()"" IL_0015: ldloca.s V_0 IL_0017: constrained. ""StructWithReadonlyToString"" IL_001d: callvirt ""string object.ToString()"" IL_0022: ldsflda ""StructWithReadonlyToString Test.f"" IL_0027: constrained. ""StructWithReadonlyToString"" IL_002d: callvirt ""string object.ToString()"" IL_0032: ldsflda ""StructWithReadonlyToString Test.f"" IL_0037: constrained. ""StructWithReadonlyToString"" IL_003d: callvirt ""string object.ToString()"" IL_0042: call ""string string.Concat(string, string, string, string)"" IL_0047: call ""void System.Console.WriteLine(string)"" IL_004c: ret } "); } [Fact] public void ConcatStructWithNoToString() { var source = @" using System; class Test { static S f = new S(); static void Main() { S l = new S(); Console.WriteLine("""" + l + l + f + f); } } struct S { } "; var comp = CompileAndVerify(source, expectedOutput: @"SSSS"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 77 (0x4d) .maxstack 4 .locals init (S V_0) //l IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: constrained. ""S"" IL_0010: callvirt ""string object.ToString()"" IL_0015: ldloca.s V_0 IL_0017: constrained. ""S"" IL_001d: callvirt ""string object.ToString()"" IL_0022: ldsflda ""S Test.f"" IL_0027: constrained. ""S"" IL_002d: callvirt ""string object.ToString()"" IL_0032: ldsflda ""S Test.f"" IL_0037: constrained. ""S"" IL_003d: callvirt ""string object.ToString()"" IL_0042: call ""string string.Concat(string, string, string, string)"" IL_0047: call ""void System.Console.WriteLine(string)"" IL_004c: ret } "); } [Fact] public void ConcatWithImplicitOperator() { var source = @" using System; public class Test { static void Main() { Console.WriteLine(""S"" + new Test()); } public static implicit operator string(Test test) => ""T""; } "; var comp = CompileAndVerify(source, expectedOutput: @"ST"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 26 (0x1a) .maxstack 2 IL_0000: ldstr ""S"" IL_0005: newobj ""Test..ctor()"" IL_000a: call ""string Test.op_Implicit(Test)"" IL_000f: call ""string string.Concat(string, string)"" IL_0014: call ""void System.Console.WriteLine(string)"" IL_0019: ret } "); } [Fact] public void ConcatWithNull() { var source = @" using System; public class Test { public static Test T = null; static void Main() { Console.WriteLine(""S"" + T); } } "; var comp = CompileAndVerify(source, expectedOutput: @"S"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 33 (0x21) .maxstack 3 IL_0000: ldstr ""S"" IL_0005: ldsfld ""Test Test.T"" IL_000a: dup IL_000b: brtrue.s IL_0011 IL_000d: pop IL_000e: ldnull IL_000f: br.s IL_0016 IL_0011: callvirt ""string object.ToString()"" IL_0016: call ""string string.Concat(string, string)"" IL_001b: call ""void System.Console.WriteLine(string)"" IL_0020: ret } "); } [Fact] public void ConcatWithSpecialValueTypes() { var source = @" using System; public class Test { static void Main() { const char a = 'a', b = 'b'; char c = 'c', d = 'd'; Console.WriteLine(a + ""1""); Console.WriteLine(""2"" + b); Console.WriteLine(c + ""3""); Console.WriteLine(""4"" + d); Console.WriteLine(true + ""5"" + c); Console.WriteLine(""6"" + d + (IntPtr)7); Console.WriteLine(""8"" + (UIntPtr)9 + false); Console.WriteLine(c + ""10"" + d + ""11""); Console.WriteLine(""12"" + c + ""13"" + d); Console.WriteLine(a + ""14"" + b + ""15"" + a + ""16""); Console.WriteLine(c + ""17"" + d + ""18"" + c + ""19""); Console.WriteLine(""20"" + 21 + c + d + c + d); Console.WriteLine(""22"" + c + ""23"" + d + c + d); } } "; var comp = CompileAndVerify(source, expectedOutput: @"a1 2b c3 4d True5c 6d7 89False c10d11 12c13d a14b15a16 c17d18c19 2021cdcd 22c23dcd"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 477 (0x1dd) .maxstack 4 .locals init (char V_0, //c char V_1, //d bool V_2, System.IntPtr V_3, System.UIntPtr V_4, int V_5) IL_0000: ldc.i4.s 99 IL_0002: stloc.0 IL_0003: ldc.i4.s 100 IL_0005: stloc.1 IL_0006: ldstr ""a1"" IL_000b: call ""void System.Console.WriteLine(string)"" IL_0010: ldstr ""2b"" IL_0015: call ""void System.Console.WriteLine(string)"" IL_001a: ldloca.s V_0 IL_001c: call ""string char.ToString()"" IL_0021: ldstr ""3"" IL_0026: call ""string string.Concat(string, string)"" IL_002b: call ""void System.Console.WriteLine(string)"" IL_0030: ldstr ""4"" IL_0035: ldloca.s V_1 IL_0037: call ""string char.ToString()"" IL_003c: call ""string string.Concat(string, string)"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: ldc.i4.1 IL_0047: stloc.2 IL_0048: ldloca.s V_2 IL_004a: call ""string bool.ToString()"" IL_004f: ldstr ""5"" IL_0054: ldloca.s V_0 IL_0056: call ""string char.ToString()"" IL_005b: call ""string string.Concat(string, string, string)"" IL_0060: call ""void System.Console.WriteLine(string)"" IL_0065: ldstr ""6"" IL_006a: ldloca.s V_1 IL_006c: call ""string char.ToString()"" IL_0071: ldc.i4.7 IL_0072: call ""System.IntPtr System.IntPtr.op_Explicit(int)"" IL_0077: stloc.3 IL_0078: ldloca.s V_3 IL_007a: call ""string System.IntPtr.ToString()"" IL_007f: call ""string string.Concat(string, string, string)"" IL_0084: call ""void System.Console.WriteLine(string)"" IL_0089: ldstr ""8"" IL_008e: ldc.i4.s 9 IL_0090: conv.i8 IL_0091: call ""System.UIntPtr System.UIntPtr.op_Explicit(ulong)"" IL_0096: stloc.s V_4 IL_0098: ldloca.s V_4 IL_009a: call ""string System.UIntPtr.ToString()"" IL_009f: ldc.i4.0 IL_00a0: stloc.2 IL_00a1: ldloca.s V_2 IL_00a3: call ""string bool.ToString()"" IL_00a8: call ""string string.Concat(string, string, string)"" IL_00ad: call ""void System.Console.WriteLine(string)"" IL_00b2: ldloca.s V_0 IL_00b4: call ""string char.ToString()"" IL_00b9: ldstr ""10"" IL_00be: ldloca.s V_1 IL_00c0: call ""string char.ToString()"" IL_00c5: ldstr ""11"" IL_00ca: call ""string string.Concat(string, string, string, string)"" IL_00cf: call ""void System.Console.WriteLine(string)"" IL_00d4: ldstr ""12"" IL_00d9: ldloca.s V_0 IL_00db: call ""string char.ToString()"" IL_00e0: ldstr ""13"" IL_00e5: ldloca.s V_1 IL_00e7: call ""string char.ToString()"" IL_00ec: call ""string string.Concat(string, string, string, string)"" IL_00f1: call ""void System.Console.WriteLine(string)"" IL_00f6: ldstr ""a14b15a16"" IL_00fb: call ""void System.Console.WriteLine(string)"" IL_0100: ldc.i4.6 IL_0101: newarr ""string"" IL_0106: dup IL_0107: ldc.i4.0 IL_0108: ldloca.s V_0 IL_010a: call ""string char.ToString()"" IL_010f: stelem.ref IL_0110: dup IL_0111: ldc.i4.1 IL_0112: ldstr ""17"" IL_0117: stelem.ref IL_0118: dup IL_0119: ldc.i4.2 IL_011a: ldloca.s V_1 IL_011c: call ""string char.ToString()"" IL_0121: stelem.ref IL_0122: dup IL_0123: ldc.i4.3 IL_0124: ldstr ""18"" IL_0129: stelem.ref IL_012a: dup IL_012b: ldc.i4.4 IL_012c: ldloca.s V_0 IL_012e: call ""string char.ToString()"" IL_0133: stelem.ref IL_0134: dup IL_0135: ldc.i4.5 IL_0136: ldstr ""19"" IL_013b: stelem.ref IL_013c: call ""string string.Concat(params string[])"" IL_0141: call ""void System.Console.WriteLine(string)"" IL_0146: ldc.i4.6 IL_0147: newarr ""string"" IL_014c: dup IL_014d: ldc.i4.0 IL_014e: ldstr ""20"" IL_0153: stelem.ref IL_0154: dup IL_0155: ldc.i4.1 IL_0156: ldc.i4.s 21 IL_0158: stloc.s V_5 IL_015a: ldloca.s V_5 IL_015c: call ""string int.ToString()"" IL_0161: stelem.ref IL_0162: dup IL_0163: ldc.i4.2 IL_0164: ldloca.s V_0 IL_0166: call ""string char.ToString()"" IL_016b: stelem.ref IL_016c: dup IL_016d: ldc.i4.3 IL_016e: ldloca.s V_1 IL_0170: call ""string char.ToString()"" IL_0175: stelem.ref IL_0176: dup IL_0177: ldc.i4.4 IL_0178: ldloca.s V_0 IL_017a: call ""string char.ToString()"" IL_017f: stelem.ref IL_0180: dup IL_0181: ldc.i4.5 IL_0182: ldloca.s V_1 IL_0184: call ""string char.ToString()"" IL_0189: stelem.ref IL_018a: call ""string string.Concat(params string[])"" IL_018f: call ""void System.Console.WriteLine(string)"" IL_0194: ldc.i4.6 IL_0195: newarr ""string"" IL_019a: dup IL_019b: ldc.i4.0 IL_019c: ldstr ""22"" IL_01a1: stelem.ref IL_01a2: dup IL_01a3: ldc.i4.1 IL_01a4: ldloca.s V_0 IL_01a6: call ""string char.ToString()"" IL_01ab: stelem.ref IL_01ac: dup IL_01ad: ldc.i4.2 IL_01ae: ldstr ""23"" IL_01b3: stelem.ref IL_01b4: dup IL_01b5: ldc.i4.3 IL_01b6: ldloca.s V_1 IL_01b8: call ""string char.ToString()"" IL_01bd: stelem.ref IL_01be: dup IL_01bf: ldc.i4.4 IL_01c0: ldloca.s V_0 IL_01c2: call ""string char.ToString()"" IL_01c7: stelem.ref IL_01c8: dup IL_01c9: ldc.i4.5 IL_01ca: ldloca.s V_1 IL_01cc: call ""string char.ToString()"" IL_01d1: stelem.ref IL_01d2: call ""string string.Concat(params string[])"" IL_01d7: call ""void System.Console.WriteLine(string)"" IL_01dc: ret } "); } [Fact] public void ConcatExpressions() { var source = @" using System; class Test { static int X = 3; static int Y = 4; static void Main() { Console.WriteLine(X + ""+"" + Y + ""="" + (X + Y)); } } "; var comp = CompileAndVerify(source, expectedOutput: "3+4=7"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 81 (0x51) .maxstack 5 .locals init (int V_0) IL_0000: ldc.i4.5 IL_0001: newarr ""string"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldsflda ""int Test.X"" IL_000d: call ""string int.ToString()"" IL_0012: stelem.ref IL_0013: dup IL_0014: ldc.i4.1 IL_0015: ldstr ""+"" IL_001a: stelem.ref IL_001b: dup IL_001c: ldc.i4.2 IL_001d: ldsflda ""int Test.Y"" IL_0022: call ""string int.ToString()"" IL_0027: stelem.ref IL_0028: dup IL_0029: ldc.i4.3 IL_002a: ldstr ""="" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.4 IL_0032: ldsfld ""int Test.X"" IL_0037: ldsfld ""int Test.Y"" IL_003c: add IL_003d: stloc.0 IL_003e: ldloca.s V_0 IL_0040: call ""string int.ToString()"" IL_0045: stelem.ref IL_0046: call ""string string.Concat(params string[])"" IL_004b: call ""void System.Console.WriteLine(string)"" IL_0050: ret }"); } [Fact] public void ConcatRefs() { var source = @" using System; class Test { static void Main() { string s1 = ""S1""; string s2 = ""S2""; int i1 = 3; int i2 = 4; object o1 = ""O1""; object o2 = ""O2""; Print(ref s1, ref i1, ref o1, ref s2, ref i2, ref o2); } static void Print<T1, T2, T3>(ref string s, ref int i, ref object o, ref T1 t1, ref T2 t2, ref T3 t3) where T1 : class where T2 : struct { Console.WriteLine(s + i + o + t1 + t2 + t3); } } "; var comp = CompileAndVerify(source, expectedOutput: "S13O1S24O2"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Print<T1, T2, T3>", @" { // Code size 133 (0x85) .maxstack 5 .locals init (T2 V_0, T3 V_1) IL_0000: ldc.i4.6 IL_0001: newarr ""string"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldarg.0 IL_0009: ldind.ref IL_000a: stelem.ref IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldarg.1 IL_000e: call ""string int.ToString()"" IL_0013: stelem.ref IL_0014: dup IL_0015: ldc.i4.2 IL_0016: ldarg.2 IL_0017: ldind.ref IL_0018: dup IL_0019: brtrue.s IL_001f IL_001b: pop IL_001c: ldnull IL_001d: br.s IL_0024 IL_001f: callvirt ""string object.ToString()"" IL_0024: stelem.ref IL_0025: dup IL_0026: ldc.i4.3 IL_0027: ldarg.3 IL_0028: ldobj ""T1"" IL_002d: box ""T1"" IL_0032: dup IL_0033: brtrue.s IL_0039 IL_0035: pop IL_0036: ldnull IL_0037: br.s IL_003e IL_0039: callvirt ""string object.ToString()"" IL_003e: stelem.ref IL_003f: dup IL_0040: ldc.i4.4 IL_0041: ldarg.s V_4 IL_0043: ldobj ""T2"" IL_0048: stloc.0 IL_0049: ldloca.s V_0 IL_004b: constrained. ""T2"" IL_0051: callvirt ""string object.ToString()"" IL_0056: stelem.ref IL_0057: dup IL_0058: ldc.i4.5 IL_0059: ldarg.s V_5 IL_005b: ldobj ""T3"" IL_0060: stloc.1 IL_0061: ldloc.1 IL_0062: box ""T3"" IL_0067: brtrue.s IL_006c IL_0069: ldnull IL_006a: br.s IL_0079 IL_006c: ldloca.s V_1 IL_006e: constrained. ""T3"" IL_0074: callvirt ""string object.ToString()"" IL_0079: stelem.ref IL_007a: call ""string string.Concat(params string[])"" IL_007f: call ""void System.Console.WriteLine(string)"" IL_0084: ret }"); } } }
aelij/roslyn
src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenStringConcat.cs
C#
apache-2.0
52,898
/*! * LESS - Leaner CSS v1.7.0 * http://lesscss.org * * Copyright (c) 2009-2014, Alexis Sellier <self@cloudhead.net> * Licensed under the Apache v2 License. * */ /** * @license Apache v2 */ (function (window, undefined) {// // Stub out `require` in the browser // function require(arg) { return window.less[arg.split('/')[1]]; }; if (typeof(window.less) === 'undefined' || typeof(window.less.nodeType) !== 'undefined') { window.less = {}; } less = window.less; tree = window.less.tree = {}; less.mode = 'browser'; var less, tree; // Node.js does not have a header file added which defines less if (less === undefined) { less = exports; tree = require('./tree'); less.mode = 'node'; } // // less.js - parser // // A relatively straight-forward predictive parser. // There is no tokenization/lexing stage, the input is parsed // in one sweep. // // To make the parser fast enough to run in the browser, several // optimization had to be made: // // - Matching and slicing on a huge input is often cause of slowdowns. // The solution is to chunkify the input into smaller strings. // The chunks are stored in the `chunks` var, // `j` holds the current chunk index, and `currentPos` holds // the index of the current chunk in relation to `input`. // This gives us an almost 4x speed-up. // // - In many cases, we don't need to match individual tokens; // for example, if a value doesn't hold any variables, operations // or dynamic references, the parser can effectively 'skip' it, // treating it as a literal. // An example would be '1px solid #000' - which evaluates to itself, // we don't need to know what the individual components are. // The drawback, of course is that you don't get the benefits of // syntax-checking on the CSS. This gives us a 50% speed-up in the parser, // and a smaller speed-up in the code-gen. // // // Token matching is done with the `$` function, which either takes // a terminal string or regexp, or a non-terminal function to call. // It also takes care of moving all the indices forwards. // // less.Parser = function Parser(env) { var input, // LeSS input string i, // current index in `input` j, // current chunk saveStack = [], // holds state for backtracking furthest, // furthest index the parser has gone to chunks, // chunkified input current, // current chunk currentPos, // index of current chunk, in `input` parser, parsers, rootFilename = env && env.filename; // Top parser on an import tree must be sure there is one "env" // which will then be passed around by reference. if (!(env instanceof tree.parseEnv)) { env = new tree.parseEnv(env); } var imports = this.imports = { paths: env.paths || [], // Search paths, when importing queue: [], // Files which haven't been imported yet files: env.files, // Holds the imported parse trees contents: env.contents, // Holds the imported file contents contentsIgnoredChars: env.contentsIgnoredChars, // lines inserted, not in the original less mime: env.mime, // MIME type of .less files error: null, // Error in parsing/evaluating an import push: function (path, currentFileInfo, importOptions, callback) { var parserImports = this; this.queue.push(path); var fileParsedFunc = function (e, root, fullPath) { parserImports.queue.splice(parserImports.queue.indexOf(path), 1); // Remove the path from the queue var importedPreviously = fullPath === rootFilename; parserImports.files[fullPath] = root; // Store the root if (e && !parserImports.error) { parserImports.error = e; } callback(e, root, importedPreviously, fullPath); }; if (less.Parser.importer) { less.Parser.importer(path, currentFileInfo, fileParsedFunc, env); } else { less.Parser.fileLoader(path, currentFileInfo, function(e, contents, fullPath, newFileInfo) { if (e) {fileParsedFunc(e); return;} var newEnv = new tree.parseEnv(env); newEnv.currentFileInfo = newFileInfo; newEnv.processImports = false; newEnv.contents[fullPath] = contents; if (currentFileInfo.reference || importOptions.reference) { newFileInfo.reference = true; } if (importOptions.inline) { fileParsedFunc(null, contents, fullPath); } else { new(less.Parser)(newEnv).parse(contents, function (e, root) { fileParsedFunc(e, root, fullPath); }); } }, env); } } }; function save() { currentPos = i; saveStack.push( { current: current, i: i, j: j }); } function restore() { var state = saveStack.pop(); current = state.current; currentPos = i = state.i; j = state.j; } function forget() { saveStack.pop(); } function sync() { if (i > currentPos) { current = current.slice(i - currentPos); currentPos = i; } } function isWhitespace(str, pos) { var code = str.charCodeAt(pos | 0); return (code <= 32) && (code === 32 || code === 10 || code === 9); } // // Parse from a token, regexp or string, and move forward if match // function $(tok) { var tokType = typeof tok, match, length; // Either match a single character in the input, // or match a regexp in the current chunk (`current`). // if (tokType === "string") { if (input.charAt(i) !== tok) { return null; } skipWhitespace(1); return tok; } // regexp sync (); if (! (match = tok.exec(current))) { return null; } length = match[0].length; // The match is confirmed, add the match length to `i`, // and consume any extra white-space characters (' ' || '\n') // which come after that. The reason for this is that LeSS's // grammar is mostly white-space insensitive. // skipWhitespace(length); if(typeof(match) === 'string') { return match; } else { return match.length === 1 ? match[0] : match; } } // Specialization of $(tok) function $re(tok) { if (i > currentPos) { current = current.slice(i - currentPos); currentPos = i; } var m = tok.exec(current); if (!m) { return null; } skipWhitespace(m[0].length); if(typeof m === "string") { return m; } return m.length === 1 ? m[0] : m; } var _$re = $re; // Specialization of $(tok) function $char(tok) { if (input.charAt(i) !== tok) { return null; } skipWhitespace(1); return tok; } function skipWhitespace(length) { var oldi = i, oldj = j, curr = i - currentPos, endIndex = i + current.length - curr, mem = (i += length), inp = input, c; for (; i < endIndex; i++) { c = inp.charCodeAt(i); if (c > 32) { break; } if ((c !== 32) && (c !== 10) && (c !== 9) && (c !== 13)) { break; } } current = current.slice(length + i - mem + curr); currentPos = i; if (!current.length && (j < chunks.length - 1)) { current = chunks[++j]; skipWhitespace(0); // skip space at the beginning of a chunk return true; // things changed } return oldi !== i || oldj !== j; } function expect(arg, msg) { // some older browsers return typeof 'function' for RegExp var result = (Object.prototype.toString.call(arg) === '[object Function]') ? arg.call(parsers) : $(arg); if (result) { return result; } error(msg || (typeof(arg) === 'string' ? "expected '" + arg + "' got '" + input.charAt(i) + "'" : "unexpected token")); } // Specialization of expect() function expectChar(arg, msg) { if (input.charAt(i) === arg) { skipWhitespace(1); return arg; } error(msg || "expected '" + arg + "' got '" + input.charAt(i) + "'"); } function error(msg, type) { var e = new Error(msg); e.index = i; e.type = type || 'Syntax'; throw e; } // Same as $(), but don't change the state of the parser, // just return the match. function peek(tok) { if (typeof(tok) === 'string') { return input.charAt(i) === tok; } else { return tok.test(current); } } // Specialization of peek() function peekChar(tok) { return input.charAt(i) === tok; } function getInput(e, env) { if (e.filename && env.currentFileInfo.filename && (e.filename !== env.currentFileInfo.filename)) { return parser.imports.contents[e.filename]; } else { return input; } } function getLocation(index, inputStream) { var n = index + 1, line = null, column = -1; while (--n >= 0 && inputStream.charAt(n) !== '\n') { column++; } if (typeof index === 'number') { line = (inputStream.slice(0, index).match(/\n/g) || "").length; } return { line: line, column: column }; } function getDebugInfo(index, inputStream, env) { var filename = env.currentFileInfo.filename; if(less.mode !== 'browser' && less.mode !== 'rhino') { filename = require('path').resolve(filename); } return { lineNumber: getLocation(index, inputStream).line + 1, fileName: filename }; } function LessError(e, env) { var input = getInput(e, env), loc = getLocation(e.index, input), line = loc.line, col = loc.column, callLine = e.call && getLocation(e.call, input).line, lines = input.split('\n'); this.type = e.type || 'Syntax'; this.message = e.message; this.filename = e.filename || env.currentFileInfo.filename; this.index = e.index; this.line = typeof(line) === 'number' ? line + 1 : null; this.callLine = callLine + 1; this.callExtract = lines[callLine]; this.stack = e.stack; this.column = col; this.extract = [ lines[line - 1], lines[line], lines[line + 1] ]; } LessError.prototype = new Error(); LessError.prototype.constructor = LessError; this.env = env = env || {}; // The optimization level dictates the thoroughness of the parser, // the lower the number, the less nodes it will create in the tree. // This could matter for debugging, or if you want to access // the individual nodes in the tree. this.optimization = ('optimization' in this.env) ? this.env.optimization : 1; // // The Parser // parser = { imports: imports, // // Parse an input string into an abstract syntax tree, // @param str A string containing 'less' markup // @param callback call `callback` when done. // @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply // parse: function (str, callback, additionalData) { var root, line, lines, error = null, globalVars, modifyVars, preText = ""; i = j = currentPos = furthest = 0; globalVars = (additionalData && additionalData.globalVars) ? less.Parser.serializeVars(additionalData.globalVars) + '\n' : ''; modifyVars = (additionalData && additionalData.modifyVars) ? '\n' + less.Parser.serializeVars(additionalData.modifyVars) : ''; if (globalVars || (additionalData && additionalData.banner)) { preText = ((additionalData && additionalData.banner) ? additionalData.banner : "") + globalVars; parser.imports.contentsIgnoredChars[env.currentFileInfo.filename] = preText.length; } str = str.replace(/\r\n/g, '\n'); // Remove potential UTF Byte Order Mark input = str = preText + str.replace(/^\uFEFF/, '') + modifyVars; parser.imports.contents[env.currentFileInfo.filename] = str; // Split the input into chunks. chunks = (function (input) { var len = input.length, level = 0, parenLevel = 0, lastOpening, lastOpeningParen, lastMultiComment, lastMultiCommentEndBrace, chunks = [], emitFrom = 0, parserCurrentIndex, currentChunkStartIndex, cc, cc2, matched; function fail(msg, index) { error = new(LessError)({ index: index || parserCurrentIndex, type: 'Parse', message: msg, filename: env.currentFileInfo.filename }, env); } function emitChunk(force) { var len = parserCurrentIndex - emitFrom; if (((len < 512) && !force) || !len) { return; } chunks.push(input.slice(emitFrom, parserCurrentIndex + 1)); emitFrom = parserCurrentIndex + 1; } for (parserCurrentIndex = 0; parserCurrentIndex < len; parserCurrentIndex++) { cc = input.charCodeAt(parserCurrentIndex); if (((cc >= 97) && (cc <= 122)) || (cc < 34)) { // a-z or whitespace continue; } switch (cc) { case 40: // ( parenLevel++; lastOpeningParen = parserCurrentIndex; continue; case 41: // ) if (--parenLevel < 0) { return fail("missing opening `(`"); } continue; case 59: // ; if (!parenLevel) { emitChunk(); } continue; case 123: // { level++; lastOpening = parserCurrentIndex; continue; case 125: // } if (--level < 0) { return fail("missing opening `{`"); } if (!level && !parenLevel) { emitChunk(); } continue; case 92: // \ if (parserCurrentIndex < len - 1) { parserCurrentIndex++; continue; } return fail("unescaped `\\`"); case 34: case 39: case 96: // ", ' and ` matched = 0; currentChunkStartIndex = parserCurrentIndex; for (parserCurrentIndex = parserCurrentIndex + 1; parserCurrentIndex < len; parserCurrentIndex++) { cc2 = input.charCodeAt(parserCurrentIndex); if (cc2 > 96) { continue; } if (cc2 == cc) { matched = 1; break; } if (cc2 == 92) { // \ if (parserCurrentIndex == len - 1) { return fail("unescaped `\\`"); } parserCurrentIndex++; } } if (matched) { continue; } return fail("unmatched `" + String.fromCharCode(cc) + "`", currentChunkStartIndex); case 47: // /, check for comment if (parenLevel || (parserCurrentIndex == len - 1)) { continue; } cc2 = input.charCodeAt(parserCurrentIndex + 1); if (cc2 == 47) { // //, find lnfeed for (parserCurrentIndex = parserCurrentIndex + 2; parserCurrentIndex < len; parserCurrentIndex++) { cc2 = input.charCodeAt(parserCurrentIndex); if ((cc2 <= 13) && ((cc2 == 10) || (cc2 == 13))) { break; } } } else if (cc2 == 42) { // /*, find */ lastMultiComment = currentChunkStartIndex = parserCurrentIndex; for (parserCurrentIndex = parserCurrentIndex + 2; parserCurrentIndex < len - 1; parserCurrentIndex++) { cc2 = input.charCodeAt(parserCurrentIndex); if (cc2 == 125) { lastMultiCommentEndBrace = parserCurrentIndex; } if (cc2 != 42) { continue; } if (input.charCodeAt(parserCurrentIndex + 1) == 47) { break; } } if (parserCurrentIndex == len - 1) { return fail("missing closing `*/`", currentChunkStartIndex); } parserCurrentIndex++; } continue; case 42: // *, check for unmatched */ if ((parserCurrentIndex < len - 1) && (input.charCodeAt(parserCurrentIndex + 1) == 47)) { return fail("unmatched `/*`"); } continue; } } if (level !== 0) { if ((lastMultiComment > lastOpening) && (lastMultiCommentEndBrace > lastMultiComment)) { return fail("missing closing `}` or `*/`", lastOpening); } else { return fail("missing closing `}`", lastOpening); } } else if (parenLevel !== 0) { return fail("missing closing `)`", lastOpeningParen); } emitChunk(true); return chunks; })(str); if (error) { return callback(new(LessError)(error, env)); } current = chunks[0]; // Start with the primary rule. // The whole syntax tree is held under a Ruleset node, // with the `root` property set to true, so no `{}` are // output. The callback is called when the input is parsed. try { root = new(tree.Ruleset)(null, this.parsers.primary()); root.root = true; root.firstRoot = true; } catch (e) { return callback(new(LessError)(e, env)); } root.toCSS = (function (evaluate) { return function (options, variables) { options = options || {}; var evaldRoot, css, evalEnv = new tree.evalEnv(options); // // Allows setting variables with a hash, so: // // `{ color: new(tree.Color)('#f01') }` will become: // // new(tree.Rule)('@color', // new(tree.Value)([ // new(tree.Expression)([ // new(tree.Color)('#f01') // ]) // ]) // ) // if (typeof(variables) === 'object' && !Array.isArray(variables)) { variables = Object.keys(variables).map(function (k) { var value = variables[k]; if (! (value instanceof tree.Value)) { if (! (value instanceof tree.Expression)) { value = new(tree.Expression)([value]); } value = new(tree.Value)([value]); } return new(tree.Rule)('@' + k, value, false, null, 0); }); evalEnv.frames = [new(tree.Ruleset)(null, variables)]; } try { var preEvalVisitors = [], visitors = [ new(tree.joinSelectorVisitor)(), new(tree.processExtendsVisitor)(), new(tree.toCSSVisitor)({compress: Boolean(options.compress)}) ], i, root = this; if (options.plugins) { for(i =0; i < options.plugins.length; i++) { if (options.plugins[i].isPreEvalVisitor) { preEvalVisitors.push(options.plugins[i]); } else { if (options.plugins[i].isPreVisitor) { visitors.splice(0, 0, options.plugins[i]); } else { visitors.push(options.plugins[i]); } } } } for(i = 0; i < preEvalVisitors.length; i++) { preEvalVisitors[i].run(root); } evaldRoot = evaluate.call(root, evalEnv); for(i = 0; i < visitors.length; i++) { visitors[i].run(evaldRoot); } if (options.sourceMap) { evaldRoot = new tree.sourceMapOutput( { contentsIgnoredCharsMap: parser.imports.contentsIgnoredChars, writeSourceMap: options.writeSourceMap, rootNode: evaldRoot, contentsMap: parser.imports.contents, sourceMapFilename: options.sourceMapFilename, sourceMapURL: options.sourceMapURL, outputFilename: options.sourceMapOutputFilename, sourceMapBasepath: options.sourceMapBasepath, sourceMapRootpath: options.sourceMapRootpath, outputSourceFiles: options.outputSourceFiles, sourceMapGenerator: options.sourceMapGenerator }); } css = evaldRoot.toCSS({ compress: Boolean(options.compress), dumpLineNumbers: env.dumpLineNumbers, strictUnits: Boolean(options.strictUnits), numPrecision: 8}); } catch (e) { throw new(LessError)(e, env); } if (options.cleancss && less.mode === 'node') { var CleanCSS = require('clean-css'), cleancssOptions = options.cleancssOptions || {}; if (cleancssOptions.keepSpecialComments === undefined) { cleancssOptions.keepSpecialComments = "*"; } cleancssOptions.processImport = false; cleancssOptions.noRebase = true; if (cleancssOptions.noAdvanced === undefined) { cleancssOptions.noAdvanced = true; } return new CleanCSS(cleancssOptions).minify(css); } else if (options.compress) { return css.replace(/(^(\s)+)|((\s)+$)/g, ""); } else { return css; } }; })(root.eval); // If `i` is smaller than the `input.length - 1`, // it means the parser wasn't able to parse the whole // string, so we've got a parsing error. // // We try to extract a \n delimited string, // showing the line where the parse error occured. // We split it up into two parts (the part which parsed, // and the part which didn't), so we can color them differently. if (i < input.length - 1) { i = furthest; var loc = getLocation(i, input); lines = input.split('\n'); line = loc.line + 1; error = { type: "Parse", message: "Unrecognised input", index: i, filename: env.currentFileInfo.filename, line: line, column: loc.column, extract: [ lines[line - 2], lines[line - 1], lines[line] ] }; } var finish = function (e) { e = error || e || parser.imports.error; if (e) { if (!(e instanceof LessError)) { e = new(LessError)(e, env); } return callback(e); } else { return callback(null, root); } }; if (env.processImports !== false) { new tree.importVisitor(this.imports, finish) .run(root); } else { return finish(); } }, // // Here in, the parsing rules/functions // // The basic structure of the syntax tree generated is as follows: // // Ruleset -> Rule -> Value -> Expression -> Entity // // Here's some LESS code: // // .class { // color: #fff; // border: 1px solid #000; // width: @w + 4px; // > .child {...} // } // // And here's what the parse tree might look like: // // Ruleset (Selector '.class', [ // Rule ("color", Value ([Expression [Color #fff]])) // Rule ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]])) // Rule ("width", Value ([Expression [Operation "+" [Variable "@w"][Dimension 4px]]])) // Ruleset (Selector [Element '>', '.child'], [...]) // ]) // // In general, most rules will try to parse a token with the `$()` function, and if the return // value is truly, will return a new node, of the relevant type. Sometimes, we need to check // first, before parsing, that's when we use `peek()`. // parsers: parsers = { // // The `primary` rule is the *entry* and *exit* point of the parser. // The rules here can appear at any level of the parse tree. // // The recursive nature of the grammar is an interplay between the `block` // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule, // as represented by this simplified grammar: // // primary → (ruleset | rule)+ // ruleset → selector+ block // block → '{' primary '}' // // Only at one point is the primary rule not called from the // block rule: at the root level. // primary: function () { var mixin = this.mixin, $re = _$re, root = [], node; while (current) { node = this.extendRule() || mixin.definition() || this.rule() || this.ruleset() || mixin.call() || this.comment() || this.rulesetCall() || this.directive(); if (node) { root.push(node); } else { if (!($re(/^[\s\n]+/) || $re(/^;+/))) { break; } } if (peekChar('}')) { break; } } return root; }, // We create a Comment node for CSS comments `/* */`, // but keep the LeSS comments `//` silent, by just skipping // over them. comment: function () { var comment; if (input.charAt(i) !== '/') { return; } if (input.charAt(i + 1) === '/') { return new(tree.Comment)($re(/^\/\/.*/), true, i, env.currentFileInfo); } comment = $re(/^\/\*(?:[^*]|\*+[^\/*])*\*+\/\n?/); if (comment) { return new(tree.Comment)(comment, false, i, env.currentFileInfo); } }, comments: function () { var comment, comments = []; while(true) { comment = this.comment(); if (!comment) { break; } comments.push(comment); } return comments; }, // // Entities are tokens which can be found inside an Expression // entities: { // // A string, which supports escaping " and ' // // "milky way" 'he\'s the one!' // quoted: function () { var str, j = i, e, index = i; if (input.charAt(j) === '~') { j++; e = true; } // Escaped strings if (input.charAt(j) !== '"' && input.charAt(j) !== "'") { return; } if (e) { $char('~'); } str = $re(/^"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'/); if (str) { return new(tree.Quoted)(str[0], str[1] || str[2], e, index, env.currentFileInfo); } }, // // A catch-all word, such as: // // black border-collapse // keyword: function () { var k; k = $re(/^%|^[_A-Za-z-][_A-Za-z0-9-]*/); if (k) { var color = tree.Color.fromKeyword(k); if (color) { return color; } return new(tree.Keyword)(k); } }, // // A function call // // rgb(255, 0, 255) // // We also try to catch IE's `alpha()`, but let the `alpha` parser // deal with the details. // // The arguments are parsed with the `entities.arguments` parser. // call: function () { var name, nameLC, args, alpha_ret, index = i; name = /^([\w-]+|%|progid:[\w\.]+)\(/.exec(current); if (!name) { return; } name = name[1]; nameLC = name.toLowerCase(); if (nameLC === 'url') { return null; } i += name.length; if (nameLC === 'alpha') { alpha_ret = parsers.alpha(); if(typeof alpha_ret !== 'undefined') { return alpha_ret; } } $char('('); // Parse the '(' and consume whitespace. args = this.arguments(); if (! $char(')')) { return; } if (name) { return new(tree.Call)(name, args, index, env.currentFileInfo); } }, arguments: function () { var args = [], arg; while (true) { arg = this.assignment() || parsers.expression(); if (!arg) { break; } args.push(arg); if (! $char(',')) { break; } } return args; }, literal: function () { return this.dimension() || this.color() || this.quoted() || this.unicodeDescriptor(); }, // Assignments are argument entities for calls. // They are present in ie filter properties as shown below. // // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* ) // assignment: function () { var key, value; key = $re(/^\w+(?=\s?=)/i); if (!key) { return; } if (!$char('=')) { return; } value = parsers.entity(); if (value) { return new(tree.Assignment)(key, value); } }, // // Parse url() tokens // // We use a specific rule for urls, because they don't really behave like // standard function calls. The difference is that the argument doesn't have // to be enclosed within a string, so it can't be parsed as an Expression. // url: function () { var value; if (input.charAt(i) !== 'u' || !$re(/^url\(/)) { return; } value = this.quoted() || this.variable() || $re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || ""; expectChar(')'); return new(tree.URL)((value.value != null || value instanceof tree.Variable) ? value : new(tree.Anonymous)(value), env.currentFileInfo); }, // // A Variable entity, such as `@fink`, in // // width: @fink + 2px // // We use a different parser for variable definitions, // see `parsers.variable`. // variable: function () { var name, index = i; if (input.charAt(i) === '@' && (name = $re(/^@@?[\w-]+/))) { return new(tree.Variable)(name, index, env.currentFileInfo); } }, // A variable entity useing the protective {} e.g. @{var} variableCurly: function () { var curly, index = i; if (input.charAt(i) === '@' && (curly = $re(/^@\{([\w-]+)\}/))) { return new(tree.Variable)("@" + curly[1], index, env.currentFileInfo); } }, // // A Hexadecimal color // // #4F3C2F // // `rgb` and `hsl` colors are parsed through the `entities.call` parser. // color: function () { var rgb; if (input.charAt(i) === '#' && (rgb = $re(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/))) { return new(tree.Color)(rgb[1]); } }, // // A Dimension, that is, a number and a unit // // 0.5em 95% // dimension: function () { var value, c = input.charCodeAt(i); //Is the first char of the dimension 0-9, '.', '+' or '-' if ((c > 57 || c < 43) || c === 47 || c == 44) { return; } value = $re(/^([+-]?\d*\.?\d+)(%|[a-z]+)?/); if (value) { return new(tree.Dimension)(value[1], value[2]); } }, // // A unicode descriptor, as is used in unicode-range // // U+0?? or U+00A1-00A9 // unicodeDescriptor: function () { var ud; ud = $re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/); if (ud) { return new(tree.UnicodeDescriptor)(ud[0]); } }, // // JavaScript code to be evaluated // // `window.location.href` // javascript: function () { var str, j = i, e; if (input.charAt(j) === '~') { j++; e = true; } // Escaped strings if (input.charAt(j) !== '`') { return; } if (env.javascriptEnabled !== undefined && !env.javascriptEnabled) { error("You are using JavaScript, which has been disabled."); } if (e) { $char('~'); } str = $re(/^`([^`]*)`/); if (str) { return new(tree.JavaScript)(str[1], i, e); } } }, // // The variable part of a variable definition. Used in the `rule` parser // // @fink: // variable: function () { var name; if (input.charAt(i) === '@' && (name = $re(/^(@[\w-]+)\s*:/))) { return name[1]; } }, // // The variable part of a variable definition. Used in the `rule` parser // // @fink(); // rulesetCall: function () { var name; if (input.charAt(i) === '@' && (name = $re(/^(@[\w-]+)\s*\(\s*\)\s*;/))) { return new tree.RulesetCall(name[1]); } }, // // extend syntax - used to extend selectors // extend: function(isRule) { var elements, e, index = i, option, extendList, extend; if (!(isRule ? $re(/^&:extend\(/) : $re(/^:extend\(/))) { return; } do { option = null; elements = null; while (! (option = $re(/^(all)(?=\s*(\)|,))/))) { e = this.element(); if (!e) { break; } if (elements) { elements.push(e); } else { elements = [ e ]; } } option = option && option[1]; extend = new(tree.Extend)(new(tree.Selector)(elements), option, index); if (extendList) { extendList.push(extend); } else { extendList = [ extend ]; } } while($char(",")); expect(/^\)/); if (isRule) { expect(/^;/); } return extendList; }, // // extendRule - used in a rule to extend all the parent selectors // extendRule: function() { return this.extend(true); }, // // Mixins // mixin: { // // A Mixin call, with an optional argument list // // #mixins > .square(#fff); // .rounded(4px, black); // .button; // // The `while` loop is there because mixins can be // namespaced, but we only support the child and descendant // selector for now. // call: function () { var s = input.charAt(i), important = false, index = i, elemIndex, elements, elem, e, c, args; if (s !== '.' && s !== '#') { return; } save(); // stop us absorbing part of an invalid selector while (true) { elemIndex = i; e = $re(/^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/); if (!e) { break; } elem = new(tree.Element)(c, e, elemIndex, env.currentFileInfo); if (elements) { elements.push(elem); } else { elements = [ elem ]; } c = $char('>'); } if (elements) { if ($char('(')) { args = this.args(true).args; expectChar(')'); } if (parsers.important()) { important = true; } if (parsers.end()) { forget(); return new(tree.mixin.Call)(elements, args, index, env.currentFileInfo, important); } } restore(); }, args: function (isCall) { var parsers = parser.parsers, entities = parsers.entities, returner = { args:null, variadic: false }, expressions = [], argsSemiColon = [], argsComma = [], isSemiColonSeperated, expressionContainsNamed, name, nameLoop, value, arg; save(); while (true) { if (isCall) { arg = parsers.detachedRuleset() || parsers.expression(); } else { parsers.comments(); if (input.charAt(i) === '.' && $re(/^\.{3}/)) { returner.variadic = true; if ($char(";") && !isSemiColonSeperated) { isSemiColonSeperated = true; } (isSemiColonSeperated ? argsSemiColon : argsComma) .push({ variadic: true }); break; } arg = entities.variable() || entities.literal() || entities.keyword(); } if (!arg) { break; } nameLoop = null; if (arg.throwAwayComments) { arg.throwAwayComments(); } value = arg; var val = null; if (isCall) { // Variable if (arg.value && arg.value.length == 1) { val = arg.value[0]; } } else { val = arg; } if (val && val instanceof tree.Variable) { if ($char(':')) { if (expressions.length > 0) { if (isSemiColonSeperated) { error("Cannot mix ; and , as delimiter types"); } expressionContainsNamed = true; } // we do not support setting a ruleset as a default variable - it doesn't make sense // However if we do want to add it, there is nothing blocking it, just don't error // and remove isCall dependency below value = (isCall && parsers.detachedRuleset()) || parsers.expression(); if (!value) { if (isCall) { error("could not understand value for named argument"); } else { restore(); returner.args = []; return returner; } } nameLoop = (name = val.name); } else if (!isCall && $re(/^\.{3}/)) { returner.variadic = true; if ($char(";") && !isSemiColonSeperated) { isSemiColonSeperated = true; } (isSemiColonSeperated ? argsSemiColon : argsComma) .push({ name: arg.name, variadic: true }); break; } else if (!isCall) { name = nameLoop = val.name; value = null; } } if (value) { expressions.push(value); } argsComma.push({ name:nameLoop, value:value }); if ($char(',')) { continue; } if ($char(';') || isSemiColonSeperated) { if (expressionContainsNamed) { error("Cannot mix ; and , as delimiter types"); } isSemiColonSeperated = true; if (expressions.length > 1) { value = new(tree.Value)(expressions); } argsSemiColon.push({ name:name, value:value }); name = null; expressions = []; expressionContainsNamed = false; } } forget(); returner.args = isSemiColonSeperated ? argsSemiColon : argsComma; return returner; }, // // A Mixin definition, with a list of parameters // // .rounded (@radius: 2px, @color) { // ... // } // // Until we have a finer grained state-machine, we have to // do a look-ahead, to make sure we don't have a mixin call. // See the `rule` function for more information. // // We start by matching `.rounded (`, and then proceed on to // the argument list, which has optional default values. // We store the parameters in `params`, with a `value` key, // if there is a value, such as in the case of `@radius`. // // Once we've got our params list, and a closing `)`, we parse // the `{...}` block. // definition: function () { var name, params = [], match, ruleset, cond, variadic = false; if ((input.charAt(i) !== '.' && input.charAt(i) !== '#') || peek(/^[^{]*\}/)) { return; } save(); match = $re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/); if (match) { name = match[1]; var argInfo = this.args(false); params = argInfo.args; variadic = argInfo.variadic; // .mixincall("@{a}"); // looks a bit like a mixin definition.. // also // .mixincall(@a: {rule: set;}); // so we have to be nice and restore if (!$char(')')) { furthest = i; restore(); return; } parsers.comments(); if ($re(/^when/)) { // Guard cond = expect(parsers.conditions, 'expected condition'); } ruleset = parsers.block(); if (ruleset) { forget(); return new(tree.mixin.Definition)(name, params, ruleset, cond, variadic); } else { restore(); } } else { forget(); } } }, // // Entities are the smallest recognized token, // and can be found inside a rule's value. // entity: function () { var entities = this.entities; return entities.literal() || entities.variable() || entities.url() || entities.call() || entities.keyword() || entities.javascript() || this.comment(); }, // // A Rule terminator. Note that we use `peek()` to check for '}', // because the `block` rule will be expecting it, but we still need to make sure // it's there, if ';' was ommitted. // end: function () { return $char(';') || peekChar('}'); }, // // IE's alpha function // // alpha(opacity=88) // alpha: function () { var value; if (! $re(/^\(opacity=/i)) { return; } value = $re(/^\d+/) || this.entities.variable(); if (value) { expectChar(')'); return new(tree.Alpha)(value); } }, // // A Selector Element // // div // + h1 // #socks // input[type="text"] // // Elements are the building blocks for Selectors, // they are made out of a `Combinator` (see combinator rule), // and an element name, such as a tag a class, or `*`. // element: function () { var e, c, v, index = i; c = this.combinator(); e = $re(/^(?:\d+\.\d+|\d+)%/) || $re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) || $char('*') || $char('&') || this.attribute() || $re(/^\([^()@]+\)/) || $re(/^[\.#](?=@)/) || this.entities.variableCurly(); if (! e) { save(); if ($char('(')) { if ((v = this.selector()) && $char(')')) { e = new(tree.Paren)(v); forget(); } else { restore(); } } else { forget(); } } if (e) { return new(tree.Element)(c, e, index, env.currentFileInfo); } }, // // Combinators combine elements together, in a Selector. // // Because our parser isn't white-space sensitive, special care // has to be taken, when parsing the descendant combinator, ` `, // as it's an empty space. We have to check the previous character // in the input, to see if it's a ` ` character. More info on how // we deal with this in *combinator.js*. // combinator: function () { var c = input.charAt(i); if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') { i++; if (input.charAt(i) === '^') { c = '^^'; i++; } while (isWhitespace(input, i)) { i++; } return new(tree.Combinator)(c); } else if (isWhitespace(input, i - 1)) { return new(tree.Combinator)(" "); } else { return new(tree.Combinator)(null); } }, // // A CSS selector (see selector below) // with less extensions e.g. the ability to extend and guard // lessSelector: function () { return this.selector(true); }, // // A CSS Selector // // .class > div + h1 // li a:hover // // Selectors are made out of one or more Elements, see above. // selector: function (isLess) { var index = i, $re = _$re, elements, extendList, c, e, extend, when, condition; while ((isLess && (extend = this.extend())) || (isLess && (when = $re(/^when/))) || (e = this.element())) { if (when) { condition = expect(this.conditions, 'expected condition'); } else if (condition) { error("CSS guard can only be used at the end of selector"); } else if (extend) { if (extendList) { extendList.push(extend); } else { extendList = [ extend ]; } } else { if (extendList) { error("Extend can only be used at the end of selector"); } c = input.charAt(i); if (elements) { elements.push(e); } else { elements = [ e ]; } e = null; } if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') { break; } } if (elements) { return new(tree.Selector)(elements, extendList, condition, index, env.currentFileInfo); } if (extendList) { error("Extend must be used to extend a selector, it cannot be used on its own"); } }, attribute: function () { if (! $char('[')) { return; } var entities = this.entities, key, val, op; if (!(key = entities.variableCurly())) { key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/); } op = $re(/^[|~*$^]?=/); if (op) { val = entities.quoted() || $re(/^[0-9]+%/) || $re(/^[\w-]+/) || entities.variableCurly(); } expectChar(']'); return new(tree.Attribute)(key, op, val); }, // // The `block` rule is used by `ruleset` and `mixin.definition`. // It's a wrapper around the `primary` rule, with added `{}`. // block: function () { var content; if ($char('{') && (content = this.primary()) && $char('}')) { return content; } }, blockRuleset: function() { var block = this.block(); if (block) { block = new tree.Ruleset(null, block); } return block; }, detachedRuleset: function() { var blockRuleset = this.blockRuleset(); if (blockRuleset) { return new tree.DetachedRuleset(blockRuleset); } }, // // div, .class, body > p {...} // ruleset: function () { var selectors, s, rules, debugInfo; save(); if (env.dumpLineNumbers) { debugInfo = getDebugInfo(i, input, env); } while (true) { s = this.lessSelector(); if (!s) { break; } if (selectors) { selectors.push(s); } else { selectors = [ s ]; } this.comments(); if (s.condition && selectors.length > 1) { error("Guards are only currently allowed on a single selector."); } if (! $char(',')) { break; } if (s.condition) { error("Guards are only currently allowed on a single selector."); } this.comments(); } if (selectors && (rules = this.block())) { forget(); var ruleset = new(tree.Ruleset)(selectors, rules, env.strictImports); if (env.dumpLineNumbers) { ruleset.debugInfo = debugInfo; } return ruleset; } else { // Backtrack furthest = i; restore(); } }, rule: function (tryAnonymous) { var name, value, startOfRule = i, c = input.charAt(startOfRule), important, merge, isVariable; if (c === '.' || c === '#' || c === '&') { return; } save(); name = this.variable() || this.ruleProperty(); if (name) { isVariable = typeof name === "string"; if (isVariable) { value = this.detachedRuleset(); } if (!value) { // prefer to try to parse first if its a variable or we are compressing // but always fallback on the other one value = !tryAnonymous && (env.compress || isVariable) ? (this.value() || this.anonymousValue()) : (this.anonymousValue() || this.value()); important = this.important(); // a name returned by this.ruleProperty() is always an array of the form: // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"] // where each item is a tree.Keyword or tree.Variable merge = !isVariable && name.pop().value; } if (value && this.end()) { forget(); return new (tree.Rule)(name, value, important, merge, startOfRule, env.currentFileInfo); } else { furthest = i; restore(); if (value && !tryAnonymous) { return this.rule(true); } } } else { forget(); } }, anonymousValue: function () { var match; match = /^([^@+\/'"*`(;{}-]*);/.exec(current); if (match) { i += match[0].length - 1; return new(tree.Anonymous)(match[1]); } }, // // An @import directive // // @import "lib"; // // Depending on our environemnt, importing is done differently: // In the browser, it's an XHR request, in Node, it would be a // file-system operation. The function used for importing is // stored in `import`, which we pass to the Import constructor. // "import": function () { var path, features, index = i; save(); var dir = $re(/^@import?\s+/); var options = (dir ? this.importOptions() : null) || {}; if (dir && (path = this.entities.quoted() || this.entities.url())) { features = this.mediaFeatures(); if ($char(';')) { forget(); features = features && new(tree.Value)(features); return new(tree.Import)(path, features, options, index, env.currentFileInfo); } } restore(); }, importOptions: function() { var o, options = {}, optionName, value; // list of options, surrounded by parens if (! $char('(')) { return null; } do { o = this.importOption(); if (o) { optionName = o; value = true; switch(optionName) { case "css": optionName = "less"; value = false; break; case "once": optionName = "multiple"; value = false; break; } options[optionName] = value; if (! $char(',')) { break; } } } while (o); expectChar(')'); return options; }, importOption: function() { var opt = $re(/^(less|css|multiple|once|inline|reference)/); if (opt) { return opt[1]; } }, mediaFeature: function () { var entities = this.entities, nodes = [], e, p; do { e = entities.keyword() || entities.variable(); if (e) { nodes.push(e); } else if ($char('(')) { p = this.property(); e = this.value(); if ($char(')')) { if (p && e) { nodes.push(new(tree.Paren)(new(tree.Rule)(p, e, null, null, i, env.currentFileInfo, true))); } else if (e) { nodes.push(new(tree.Paren)(e)); } else { return null; } } else { return null; } } } while (e); if (nodes.length > 0) { return new(tree.Expression)(nodes); } }, mediaFeatures: function () { var entities = this.entities, features = [], e; do { e = this.mediaFeature(); if (e) { features.push(e); if (! $char(',')) { break; } } else { e = entities.variable(); if (e) { features.push(e); if (! $char(',')) { break; } } } } while (e); return features.length > 0 ? features : null; }, media: function () { var features, rules, media, debugInfo; if (env.dumpLineNumbers) { debugInfo = getDebugInfo(i, input, env); } if ($re(/^@media/)) { features = this.mediaFeatures(); rules = this.block(); if (rules) { media = new(tree.Media)(rules, features, i, env.currentFileInfo); if (env.dumpLineNumbers) { media.debugInfo = debugInfo; } return media; } } }, // // A CSS Directive // // @charset "utf-8"; // directive: function () { var index = i, name, value, rules, nonVendorSpecificName, hasIdentifier, hasExpression, hasUnknown, hasBlock = true; if (input.charAt(i) !== '@') { return; } value = this['import']() || this.media(); if (value) { return value; } save(); name = $re(/^@[a-z-]+/); if (!name) { return; } nonVendorSpecificName = name; if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) { nonVendorSpecificName = "@" + name.slice(name.indexOf('-', 2) + 1); } switch(nonVendorSpecificName) { /* case "@font-face": case "@viewport": case "@top-left": case "@top-left-corner": case "@top-center": case "@top-right": case "@top-right-corner": case "@bottom-left": case "@bottom-left-corner": case "@bottom-center": case "@bottom-right": case "@bottom-right-corner": case "@left-top": case "@left-middle": case "@left-bottom": case "@right-top": case "@right-middle": case "@right-bottom": hasBlock = true; break; */ case "@charset": hasIdentifier = true; hasBlock = false; break; case "@namespace": hasExpression = true; hasBlock = false; break; case "@keyframes": hasIdentifier = true; break; case "@host": case "@page": case "@document": case "@supports": hasUnknown = true; break; } if (hasIdentifier) { value = this.entity(); if (!value) { error("expected " + name + " identifier"); } } else if (hasExpression) { value = this.expression(); if (!value) { error("expected " + name + " expression"); } } else if (hasUnknown) { value = ($re(/^[^{;]+/) || '').trim(); if (value) { value = new(tree.Anonymous)(value); } } if (hasBlock) { rules = this.blockRuleset(); } if (rules || (!hasBlock && value && $char(';'))) { forget(); return new(tree.Directive)(name, value, rules, index, env.currentFileInfo, env.dumpLineNumbers ? getDebugInfo(index, input, env) : null); } restore(); }, // // A Value is a comma-delimited list of Expressions // // font-family: Baskerville, Georgia, serif; // // In a Rule, a Value represents everything after the `:`, // and before the `;`. // value: function () { var e, expressions = []; do { e = this.expression(); if (e) { expressions.push(e); if (! $char(',')) { break; } } } while(e); if (expressions.length > 0) { return new(tree.Value)(expressions); } }, important: function () { if (input.charAt(i) === '!') { return $re(/^! *important/); } }, sub: function () { var a, e; if ($char('(')) { a = this.addition(); if (a) { e = new(tree.Expression)([a]); expectChar(')'); e.parens = true; return e; } } }, multiplication: function () { var m, a, op, operation, isSpaced; m = this.operand(); if (m) { isSpaced = isWhitespace(input, i - 1); while (true) { if (peek(/^\/[*\/]/)) { break; } op = $char('/') || $char('*'); if (!op) { break; } a = this.operand(); if (!a) { break; } m.parensInOp = true; a.parensInOp = true; operation = new(tree.Operation)(op, [operation || m, a], isSpaced); isSpaced = isWhitespace(input, i - 1); } return operation || m; } }, addition: function () { var m, a, op, operation, isSpaced; m = this.multiplication(); if (m) { isSpaced = isWhitespace(input, i - 1); while (true) { op = $re(/^[-+]\s+/) || (!isSpaced && ($char('+') || $char('-'))); if (!op) { break; } a = this.multiplication(); if (!a) { break; } m.parensInOp = true; a.parensInOp = true; operation = new(tree.Operation)(op, [operation || m, a], isSpaced); isSpaced = isWhitespace(input, i - 1); } return operation || m; } }, conditions: function () { var a, b, index = i, condition; a = this.condition(); if (a) { while (true) { if (!peek(/^,\s*(not\s*)?\(/) || !$char(',')) { break; } b = this.condition(); if (!b) { break; } condition = new(tree.Condition)('or', condition || a, b, index); } return condition || a; } }, condition: function () { var entities = this.entities, index = i, negate = false, a, b, c, op; if ($re(/^not/)) { negate = true; } expectChar('('); a = this.addition() || entities.keyword() || entities.quoted(); if (a) { op = $re(/^(?:>=|<=|=<|[<=>])/); if (op) { b = this.addition() || entities.keyword() || entities.quoted(); if (b) { c = new(tree.Condition)(op, a, b, index, negate); } else { error('expected expression'); } } else { c = new(tree.Condition)('=', a, new(tree.Keyword)('true'), index, negate); } expectChar(')'); return $re(/^and/) ? new(tree.Condition)('and', c, this.condition()) : c; } }, // // An operand is anything that can be part of an operation, // such as a Color, or a Variable // operand: function () { var entities = this.entities, p = input.charAt(i + 1), negate; if (input.charAt(i) === '-' && (p === '@' || p === '(')) { negate = $char('-'); } var o = this.sub() || entities.dimension() || entities.color() || entities.variable() || entities.call(); if (negate) { o.parensInOp = true; o = new(tree.Negative)(o); } return o; }, // // Expressions either represent mathematical operations, // or white-space delimited Entities. // // 1px solid black // @var * 2 // expression: function () { var entities = [], e, delim; do { e = this.addition() || this.entity(); if (e) { entities.push(e); // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here if (!peek(/^\/[\/*]/)) { delim = $char('/'); if (delim) { entities.push(new(tree.Anonymous)(delim)); } } } } while (e); if (entities.length > 0) { return new(tree.Expression)(entities); } }, property: function () { var name = $re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/); if (name) { return name[1]; } }, ruleProperty: function () { var c = current, name = [], index = [], length = 0, s, k; function match(re) { var a = re.exec(c); if (a) { index.push(i + length); length += a[0].length; c = c.slice(a[1].length); return name.push(a[1]); } } match(/^(\*?)/); while (match(/^((?:[\w-]+)|(?:@\{[\w-]+\}))/)); // ! if ((name.length > 1) && match(/^\s*((?:\+_|\+)?)\s*:/)) { // at last, we have the complete match now. move forward, // convert name particles to tree objects and return: skipWhitespace(length); if (name[0] === '') { name.shift(); index.shift(); } for (k = 0; k < name.length; k++) { s = name[k]; name[k] = (s.charAt(0) !== '@') ? new(tree.Keyword)(s) : new(tree.Variable)('@' + s.slice(2, -1), index[k], env.currentFileInfo); } return name; } } } }; return parser; }; less.Parser.serializeVars = function(vars) { var s = ''; for (var name in vars) { if (Object.hasOwnProperty.call(vars, name)) { var value = vars[name]; s += ((name[0] === '@') ? '' : '@') + name +': '+ value + ((('' + value).slice(-1) === ';') ? '' : ';'); } } return s; }; (function (tree) { tree.functions = { rgb: function (r, g, b) { return this.rgba(r, g, b, 1.0); }, rgba: function (r, g, b, a) { var rgb = [r, g, b].map(function (c) { return scaled(c, 255); }); a = number(a); return new(tree.Color)(rgb, a); }, hsl: function (h, s, l) { return this.hsla(h, s, l, 1.0); }, hsla: function (h, s, l, a) { function hue(h) { h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h); if (h * 6 < 1) { return m1 + (m2 - m1) * h * 6; } else if (h * 2 < 1) { return m2; } else if (h * 3 < 2) { return m1 + (m2 - m1) * (2/3 - h) * 6; } else { return m1; } } h = (number(h) % 360) / 360; s = clamp(number(s)); l = clamp(number(l)); a = clamp(number(a)); var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; var m1 = l * 2 - m2; return this.rgba(hue(h + 1/3) * 255, hue(h) * 255, hue(h - 1/3) * 255, a); }, hsv: function(h, s, v) { return this.hsva(h, s, v, 1.0); }, hsva: function(h, s, v, a) { h = ((number(h) % 360) / 360) * 360; s = number(s); v = number(v); a = number(a); var i, f; i = Math.floor((h / 60) % 6); f = (h / 60) - i; var vs = [v, v * (1 - s), v * (1 - f * s), v * (1 - (1 - f) * s)]; var perm = [[0, 3, 1], [2, 0, 1], [1, 0, 3], [1, 2, 0], [3, 1, 0], [0, 1, 2]]; return this.rgba(vs[perm[i][0]] * 255, vs[perm[i][1]] * 255, vs[perm[i][2]] * 255, a); }, hue: function (color) { return new(tree.Dimension)(Math.round(color.toHSL().h)); }, saturation: function (color) { return new(tree.Dimension)(Math.round(color.toHSL().s * 100), '%'); }, lightness: function (color) { return new(tree.Dimension)(Math.round(color.toHSL().l * 100), '%'); }, hsvhue: function(color) { return new(tree.Dimension)(Math.round(color.toHSV().h)); }, hsvsaturation: function (color) { return new(tree.Dimension)(Math.round(color.toHSV().s * 100), '%'); }, hsvvalue: function (color) { return new(tree.Dimension)(Math.round(color.toHSV().v * 100), '%'); }, red: function (color) { return new(tree.Dimension)(color.rgb[0]); }, green: function (color) { return new(tree.Dimension)(color.rgb[1]); }, blue: function (color) { return new(tree.Dimension)(color.rgb[2]); }, alpha: function (color) { return new(tree.Dimension)(color.toHSL().a); }, luma: function (color) { return new(tree.Dimension)(Math.round(color.luma() * color.alpha * 100), '%'); }, luminance: function (color) { var luminance = (0.2126 * color.rgb[0] / 255) + (0.7152 * color.rgb[1] / 255) + (0.0722 * color.rgb[2] / 255); return new(tree.Dimension)(Math.round(luminance * color.alpha * 100), '%'); }, saturate: function (color, amount) { // filter: saturate(3.2); // should be kept as is, so check for color if (!color.rgb) { return null; } var hsl = color.toHSL(); hsl.s += amount.value / 100; hsl.s = clamp(hsl.s); return hsla(hsl); }, desaturate: function (color, amount) { var hsl = color.toHSL(); hsl.s -= amount.value / 100; hsl.s = clamp(hsl.s); return hsla(hsl); }, lighten: function (color, amount) { var hsl = color.toHSL(); hsl.l += amount.value / 100; hsl.l = clamp(hsl.l); return hsla(hsl); }, darken: function (color, amount) { var hsl = color.toHSL(); hsl.l -= amount.value / 100; hsl.l = clamp(hsl.l); return hsla(hsl); }, fadein: function (color, amount) { var hsl = color.toHSL(); hsl.a += amount.value / 100; hsl.a = clamp(hsl.a); return hsla(hsl); }, fadeout: function (color, amount) { var hsl = color.toHSL(); hsl.a -= amount.value / 100; hsl.a = clamp(hsl.a); return hsla(hsl); }, fade: function (color, amount) { var hsl = color.toHSL(); hsl.a = amount.value / 100; hsl.a = clamp(hsl.a); return hsla(hsl); }, spin: function (color, amount) { var hsl = color.toHSL(); var hue = (hsl.h + amount.value) % 360; hsl.h = hue < 0 ? 360 + hue : hue; return hsla(hsl); }, // // Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein // http://sass-lang.com // mix: function (color1, color2, weight) { if (!weight) { weight = new(tree.Dimension)(50); } var p = weight.value / 100.0; var w = p * 2 - 1; var a = color1.toHSL().a - color2.toHSL().a; var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0; var w2 = 1 - w1; var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2, color1.rgb[1] * w1 + color2.rgb[1] * w2, color1.rgb[2] * w1 + color2.rgb[2] * w2]; var alpha = color1.alpha * p + color2.alpha * (1 - p); return new(tree.Color)(rgb, alpha); }, greyscale: function (color) { return this.desaturate(color, new(tree.Dimension)(100)); }, contrast: function (color, dark, light, threshold) { // filter: contrast(3.2); // should be kept as is, so check for color if (!color.rgb) { return null; } if (typeof light === 'undefined') { light = this.rgba(255, 255, 255, 1.0); } if (typeof dark === 'undefined') { dark = this.rgba(0, 0, 0, 1.0); } //Figure out which is actually light and dark! if (dark.luma() > light.luma()) { var t = light; light = dark; dark = t; } if (typeof threshold === 'undefined') { threshold = 0.43; } else { threshold = number(threshold); } if (color.luma() < threshold) { return light; } else { return dark; } }, e: function (str) { return new(tree.Anonymous)(str instanceof tree.JavaScript ? str.evaluated : str); }, escape: function (str) { return new(tree.Anonymous)(encodeURI(str.value).replace(/=/g, "%3D").replace(/:/g, "%3A").replace(/#/g, "%23").replace(/;/g, "%3B").replace(/\(/g, "%28").replace(/\)/g, "%29")); }, replace: function (string, pattern, replacement, flags) { var result = string.value; result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement.value); return new(tree.Quoted)(string.quote || '', result, string.escaped); }, '%': function (string /* arg, arg, ...*/) { var args = Array.prototype.slice.call(arguments, 1), result = string.value; for (var i = 0; i < args.length; i++) { /*jshint loopfunc:true */ result = result.replace(/%[sda]/i, function(token) { var value = token.match(/s/i) ? args[i].value : args[i].toCSS(); return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value; }); } result = result.replace(/%%/g, '%'); return new(tree.Quoted)(string.quote || '', result, string.escaped); }, unit: function (val, unit) { if(!(val instanceof tree.Dimension)) { throw { type: "Argument", message: "the first argument to unit must be a number" + (val instanceof tree.Operation ? ". Have you forgotten parenthesis?" : "") }; } if (unit) { if (unit instanceof tree.Keyword) { unit = unit.value; } else { unit = unit.toCSS(); } } else { unit = ""; } return new(tree.Dimension)(val.value, unit); }, convert: function (val, unit) { return val.convertTo(unit.value); }, round: function (n, f) { var fraction = typeof(f) === "undefined" ? 0 : f.value; return _math(function(num) { return num.toFixed(fraction); }, null, n); }, pi: function () { return new(tree.Dimension)(Math.PI); }, mod: function(a, b) { return new(tree.Dimension)(a.value % b.value, a.unit); }, pow: function(x, y) { if (typeof x === "number" && typeof y === "number") { x = new(tree.Dimension)(x); y = new(tree.Dimension)(y); } else if (!(x instanceof tree.Dimension) || !(y instanceof tree.Dimension)) { throw { type: "Argument", message: "arguments must be numbers" }; } return new(tree.Dimension)(Math.pow(x.value, y.value), x.unit); }, _minmax: function (isMin, args) { args = Array.prototype.slice.call(args); switch(args.length) { case 0: throw { type: "Argument", message: "one or more arguments required" }; } var i, j, current, currentUnified, referenceUnified, unit, unitStatic, unitClone, order = [], // elems only contains original argument values. values = {}; // key is the unit.toString() for unified tree.Dimension values, // value is the index into the order array. for (i = 0; i < args.length; i++) { current = args[i]; if (!(current instanceof tree.Dimension)) { if(Array.isArray(args[i].value)) { Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value)); } continue; } currentUnified = current.unit.toString() === "" && unitClone !== undefined ? new(tree.Dimension)(current.value, unitClone).unify() : current.unify(); unit = currentUnified.unit.toString() === "" && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString(); unitStatic = unit !== "" && unitStatic === undefined || unit !== "" && order[0].unify().unit.toString() === "" ? unit : unitStatic; unitClone = unit !== "" && unitClone === undefined ? current.unit.toString() : unitClone; j = values[""] !== undefined && unit !== "" && unit === unitStatic ? values[""] : values[unit]; if (j === undefined) { if(unitStatic !== undefined && unit !== unitStatic) { throw{ type: "Argument", message: "incompatible types" }; } values[unit] = order.length; order.push(current); continue; } referenceUnified = order[j].unit.toString() === "" && unitClone !== undefined ? new(tree.Dimension)(order[j].value, unitClone).unify() : order[j].unify(); if ( isMin && currentUnified.value < referenceUnified.value || !isMin && currentUnified.value > referenceUnified.value) { order[j] = current; } } if (order.length == 1) { return order[0]; } args = order.map(function (a) { return a.toCSS(this.env); }).join(this.env.compress ? "," : ", "); return new(tree.Anonymous)((isMin ? "min" : "max") + "(" + args + ")"); }, min: function () { return this._minmax(true, arguments); }, max: function () { return this._minmax(false, arguments); }, "get-unit": function (n) { return new(tree.Anonymous)(n.unit); }, argb: function (color) { return new(tree.Anonymous)(color.toARGB()); }, percentage: function (n) { return new(tree.Dimension)(n.value * 100, '%'); }, color: function (n) { if (n instanceof tree.Quoted) { var colorCandidate = n.value, returnColor; returnColor = tree.Color.fromKeyword(colorCandidate); if (returnColor) { return returnColor; } if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/.test(colorCandidate)) { return new(tree.Color)(colorCandidate.slice(1)); } throw { type: "Argument", message: "argument must be a color keyword or 3/6 digit hex e.g. #FFF" }; } else { throw { type: "Argument", message: "argument must be a string" }; } }, iscolor: function (n) { return this._isa(n, tree.Color); }, isnumber: function (n) { return this._isa(n, tree.Dimension); }, isstring: function (n) { return this._isa(n, tree.Quoted); }, iskeyword: function (n) { return this._isa(n, tree.Keyword); }, isurl: function (n) { return this._isa(n, tree.URL); }, ispixel: function (n) { return this.isunit(n, 'px'); }, ispercentage: function (n) { return this.isunit(n, '%'); }, isem: function (n) { return this.isunit(n, 'em'); }, isunit: function (n, unit) { return (n instanceof tree.Dimension) && n.unit.is(unit.value || unit) ? tree.True : tree.False; }, _isa: function (n, Type) { return (n instanceof Type) ? tree.True : tree.False; }, tint: function(color, amount) { return this.mix(this.rgb(255,255,255), color, amount); }, shade: function(color, amount) { return this.mix(this.rgb(0, 0, 0), color, amount); }, extract: function(values, index) { index = index.value - 1; // (1-based index) // handle non-array values as an array of length 1 // return 'undefined' if index is invalid return Array.isArray(values.value) ? values.value[index] : Array(values)[index]; }, length: function(values) { var n = Array.isArray(values.value) ? values.value.length : 1; return new tree.Dimension(n); }, "data-uri": function(mimetypeNode, filePathNode) { if (typeof window !== 'undefined') { return new tree.URL(filePathNode || mimetypeNode, this.currentFileInfo).eval(this.env); } var mimetype = mimetypeNode.value; var filePath = (filePathNode && filePathNode.value); var fs = require('fs'), path = require('path'), useBase64 = false; if (arguments.length < 2) { filePath = mimetype; } if (this.env.isPathRelative(filePath)) { if (this.currentFileInfo.relativeUrls) { filePath = path.join(this.currentFileInfo.currentDirectory, filePath); } else { filePath = path.join(this.currentFileInfo.entryPath, filePath); } } // detect the mimetype if not given if (arguments.length < 2) { var mime; try { mime = require('mime'); } catch (ex) { mime = tree._mime; } mimetype = mime.lookup(filePath); // use base 64 unless it's an ASCII or UTF-8 format var charset = mime.charsets.lookup(mimetype); useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0; if (useBase64) { mimetype += ';base64'; } } else { useBase64 = /;base64$/.test(mimetype); } var buf = fs.readFileSync(filePath); // IE8 cannot handle a data-uri larger than 32KB. If this is exceeded // and the --ieCompat flag is enabled, return a normal url() instead. var DATA_URI_MAX_KB = 32, fileSizeInKB = parseInt((buf.length / 1024), 10); if (fileSizeInKB >= DATA_URI_MAX_KB) { if (this.env.ieCompat !== false) { if (!this.env.silent) { console.warn("Skipped data-uri embedding of %s because its size (%dKB) exceeds IE8-safe %dKB!", filePath, fileSizeInKB, DATA_URI_MAX_KB); } return new tree.URL(filePathNode || mimetypeNode, this.currentFileInfo).eval(this.env); } } buf = useBase64 ? buf.toString('base64') : encodeURIComponent(buf); var uri = "\"data:" + mimetype + ',' + buf + "\""; return new(tree.URL)(new(tree.Anonymous)(uri)); }, "svg-gradient": function(direction) { function throwArgumentDescriptor() { throw { type: "Argument", message: "svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position]" }; } if (arguments.length < 3) { throwArgumentDescriptor(); } var stops = Array.prototype.slice.call(arguments, 1), gradientDirectionSvg, gradientType = "linear", rectangleDimension = 'x="0" y="0" width="1" height="1"', useBase64 = true, renderEnv = {compress: false}, returner, directionValue = direction.toCSS(renderEnv), i, color, position, positionValue, alpha; switch (directionValue) { case "to bottom": gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"'; break; case "to right": gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"'; break; case "to bottom right": gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"'; break; case "to top right": gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"'; break; case "ellipse": case "ellipse at center": gradientType = "radial"; gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"'; rectangleDimension = 'x="-50" y="-50" width="101" height="101"'; break; default: throw { type: "Argument", message: "svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'" }; } returner = '<?xml version="1.0" ?>' + '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">' + '<' + gradientType + 'Gradient id="gradient" gradientUnits="userSpaceOnUse" ' + gradientDirectionSvg + '>'; for (i = 0; i < stops.length; i+= 1) { if (stops[i].value) { color = stops[i].value[0]; position = stops[i].value[1]; } else { color = stops[i]; position = undefined; } if (!(color instanceof tree.Color) || (!((i === 0 || i+1 === stops.length) && position === undefined) && !(position instanceof tree.Dimension))) { throwArgumentDescriptor(); } positionValue = position ? position.toCSS(renderEnv) : i === 0 ? "0%" : "100%"; alpha = color.alpha; returner += '<stop offset="' + positionValue + '" stop-color="' + color.toRGB() + '"' + (alpha < 1 ? ' stop-opacity="' + alpha + '"' : '') + '/>'; } returner += '</' + gradientType + 'Gradient>' + '<rect ' + rectangleDimension + ' fill="url(#gradient)" /></svg>'; if (useBase64) { try { returner = require('./encoder').encodeBase64(returner); // TODO browser implementation } catch(e) { useBase64 = false; } } returner = "'data:image/svg+xml" + (useBase64 ? ";base64" : "") + "," + returner + "'"; return new(tree.URL)(new(tree.Anonymous)(returner)); } }; // these static methods are used as a fallback when the optional 'mime' dependency is missing tree._mime = { // this map is intentionally incomplete // if you want more, install 'mime' dep _types: { '.htm' : 'text/html', '.html': 'text/html', '.gif' : 'image/gif', '.jpg' : 'image/jpeg', '.jpeg': 'image/jpeg', '.png' : 'image/png' }, lookup: function (filepath) { var ext = require('path').extname(filepath), type = tree._mime._types[ext]; if (type === undefined) { throw new Error('Optional dependency "mime" is required for ' + ext); } return type; }, charsets: { lookup: function (type) { // assumes all text types are UTF-8 return type && (/^text\//).test(type) ? 'UTF-8' : ''; } } }; // Math var mathFunctions = { // name, unit ceil: null, floor: null, sqrt: null, abs: null, tan: "", sin: "", cos: "", atan: "rad", asin: "rad", acos: "rad" }; function _math(fn, unit, n) { if (!(n instanceof tree.Dimension)) { throw { type: "Argument", message: "argument must be a number" }; } if (unit == null) { unit = n.unit; } else { n = n.unify(); } return new(tree.Dimension)(fn(parseFloat(n.value)), unit); } // ~ End of Math // Color Blending // ref: http://www.w3.org/TR/compositing-1 function colorBlend(mode, color1, color2) { var ab = color1.alpha, cb, // backdrop as = color2.alpha, cs, // source ar, cr, r = []; // result ar = as + ab * (1 - as); for (var i = 0; i < 3; i++) { cb = color1.rgb[i] / 255; cs = color2.rgb[i] / 255; cr = mode(cb, cs); if (ar) { cr = (as * cs + ab * (cb - as * (cb + cs - cr))) / ar; } r[i] = cr * 255; } return new(tree.Color)(r, ar); } var colorBlendMode = { multiply: function(cb, cs) { return cb * cs; }, screen: function(cb, cs) { return cb + cs - cb * cs; }, overlay: function(cb, cs) { cb *= 2; return (cb <= 1) ? colorBlendMode.multiply(cb, cs) : colorBlendMode.screen(cb - 1, cs); }, softlight: function(cb, cs) { var d = 1, e = cb; if (cs > 0.5) { e = 1; d = (cb > 0.25) ? Math.sqrt(cb) : ((16 * cb - 12) * cb + 4) * cb; } return cb - (1 - 2 * cs) * e * (d - cb); }, hardlight: function(cb, cs) { return colorBlendMode.overlay(cs, cb); }, difference: function(cb, cs) { return Math.abs(cb - cs); }, exclusion: function(cb, cs) { return cb + cs - 2 * cb * cs; }, // non-w3c functions: average: function(cb, cs) { return (cb + cs) / 2; }, negation: function(cb, cs) { return 1 - Math.abs(cb + cs - 1); } }; // ~ End of Color Blending tree.defaultFunc = { eval: function () { var v = this.value_, e = this.error_; if (e) { throw e; } if (v != null) { return v ? tree.True : tree.False; } }, value: function (v) { this.value_ = v; }, error: function (e) { this.error_ = e; }, reset: function () { this.value_ = this.error_ = null; } }; function initFunctions() { var f, tf = tree.functions; // math for (f in mathFunctions) { if (mathFunctions.hasOwnProperty(f)) { tf[f] = _math.bind(null, Math[f], mathFunctions[f]); } } // color blending for (f in colorBlendMode) { if (colorBlendMode.hasOwnProperty(f)) { tf[f] = colorBlend.bind(null, colorBlendMode[f]); } } // default f = tree.defaultFunc; tf["default"] = f.eval.bind(f); } initFunctions(); function hsla(color) { return tree.functions.hsla(color.h, color.s, color.l, color.a); } function scaled(n, size) { if (n instanceof tree.Dimension && n.unit.is('%')) { return parseFloat(n.value * size / 100); } else { return number(n); } } function number(n) { if (n instanceof tree.Dimension) { return parseFloat(n.unit.is('%') ? n.value / 100 : n.value); } else if (typeof(n) === 'number') { return n; } else { throw { error: "RuntimeError", message: "color functions take numbers as parameters" }; } } function clamp(val) { return Math.min(1, Math.max(0, val)); } tree.fround = function(env, value) { var p; if (env && (env.numPrecision != null)) { p = Math.pow(10, env.numPrecision); return Math.round(value * p) / p; } else { return value; } }; tree.functionCall = function(env, currentFileInfo) { this.env = env; this.currentFileInfo = currentFileInfo; }; tree.functionCall.prototype = tree.functions; })(require('./tree')); (function (tree) { tree.colors = { 'aliceblue':'#f0f8ff', 'antiquewhite':'#faebd7', 'aqua':'#00ffff', 'aquamarine':'#7fffd4', 'azure':'#f0ffff', 'beige':'#f5f5dc', 'bisque':'#ffe4c4', 'black':'#000000', 'blanchedalmond':'#ffebcd', 'blue':'#0000ff', 'blueviolet':'#8a2be2', 'brown':'#a52a2a', 'burlywood':'#deb887', 'cadetblue':'#5f9ea0', 'chartreuse':'#7fff00', 'chocolate':'#d2691e', 'coral':'#ff7f50', 'cornflowerblue':'#6495ed', 'cornsilk':'#fff8dc', 'crimson':'#dc143c', 'cyan':'#00ffff', 'darkblue':'#00008b', 'darkcyan':'#008b8b', 'darkgoldenrod':'#b8860b', 'darkgray':'#a9a9a9', 'darkgrey':'#a9a9a9', 'darkgreen':'#006400', 'darkkhaki':'#bdb76b', 'darkmagenta':'#8b008b', 'darkolivegreen':'#556b2f', 'darkorange':'#ff8c00', 'darkorchid':'#9932cc', 'darkred':'#8b0000', 'darksalmon':'#e9967a', 'darkseagreen':'#8fbc8f', 'darkslateblue':'#483d8b', 'darkslategray':'#2f4f4f', 'darkslategrey':'#2f4f4f', 'darkturquoise':'#00ced1', 'darkviolet':'#9400d3', 'deeppink':'#ff1493', 'deepskyblue':'#00bfff', 'dimgray':'#696969', 'dimgrey':'#696969', 'dodgerblue':'#1e90ff', 'firebrick':'#b22222', 'floralwhite':'#fffaf0', 'forestgreen':'#228b22', 'fuchsia':'#ff00ff', 'gainsboro':'#dcdcdc', 'ghostwhite':'#f8f8ff', 'gold':'#ffd700', 'goldenrod':'#daa520', 'gray':'#808080', 'grey':'#808080', 'green':'#008000', 'greenyellow':'#adff2f', 'honeydew':'#f0fff0', 'hotpink':'#ff69b4', 'indianred':'#cd5c5c', 'indigo':'#4b0082', 'ivory':'#fffff0', 'khaki':'#f0e68c', 'lavender':'#e6e6fa', 'lavenderblush':'#fff0f5', 'lawngreen':'#7cfc00', 'lemonchiffon':'#fffacd', 'lightblue':'#add8e6', 'lightcoral':'#f08080', 'lightcyan':'#e0ffff', 'lightgoldenrodyellow':'#fafad2', 'lightgray':'#d3d3d3', 'lightgrey':'#d3d3d3', 'lightgreen':'#90ee90', 'lightpink':'#ffb6c1', 'lightsalmon':'#ffa07a', 'lightseagreen':'#20b2aa', 'lightskyblue':'#87cefa', 'lightslategray':'#778899', 'lightslategrey':'#778899', 'lightsteelblue':'#b0c4de', 'lightyellow':'#ffffe0', 'lime':'#00ff00', 'limegreen':'#32cd32', 'linen':'#faf0e6', 'magenta':'#ff00ff', 'maroon':'#800000', 'mediumaquamarine':'#66cdaa', 'mediumblue':'#0000cd', 'mediumorchid':'#ba55d3', 'mediumpurple':'#9370d8', 'mediumseagreen':'#3cb371', 'mediumslateblue':'#7b68ee', 'mediumspringgreen':'#00fa9a', 'mediumturquoise':'#48d1cc', 'mediumvioletred':'#c71585', 'midnightblue':'#191970', 'mintcream':'#f5fffa', 'mistyrose':'#ffe4e1', 'moccasin':'#ffe4b5', 'navajowhite':'#ffdead', 'navy':'#000080', 'oldlace':'#fdf5e6', 'olive':'#808000', 'olivedrab':'#6b8e23', 'orange':'#ffa500', 'orangered':'#ff4500', 'orchid':'#da70d6', 'palegoldenrod':'#eee8aa', 'palegreen':'#98fb98', 'paleturquoise':'#afeeee', 'palevioletred':'#d87093', 'papayawhip':'#ffefd5', 'peachpuff':'#ffdab9', 'peru':'#cd853f', 'pink':'#ffc0cb', 'plum':'#dda0dd', 'powderblue':'#b0e0e6', 'purple':'#800080', 'red':'#ff0000', 'rosybrown':'#bc8f8f', 'royalblue':'#4169e1', 'saddlebrown':'#8b4513', 'salmon':'#fa8072', 'sandybrown':'#f4a460', 'seagreen':'#2e8b57', 'seashell':'#fff5ee', 'sienna':'#a0522d', 'silver':'#c0c0c0', 'skyblue':'#87ceeb', 'slateblue':'#6a5acd', 'slategray':'#708090', 'slategrey':'#708090', 'snow':'#fffafa', 'springgreen':'#00ff7f', 'steelblue':'#4682b4', 'tan':'#d2b48c', 'teal':'#008080', 'thistle':'#d8bfd8', 'tomato':'#ff6347', 'turquoise':'#40e0d0', 'violet':'#ee82ee', 'wheat':'#f5deb3', 'white':'#ffffff', 'whitesmoke':'#f5f5f5', 'yellow':'#ffff00', 'yellowgreen':'#9acd32' }; })(require('./tree')); (function (tree) { tree.debugInfo = function(env, ctx, lineSeperator) { var result=""; if (env.dumpLineNumbers && !env.compress) { switch(env.dumpLineNumbers) { case 'comments': result = tree.debugInfo.asComment(ctx); break; case 'mediaquery': result = tree.debugInfo.asMediaQuery(ctx); break; case 'all': result = tree.debugInfo.asComment(ctx) + (lineSeperator || "") + tree.debugInfo.asMediaQuery(ctx); break; } } return result; }; tree.debugInfo.asComment = function(ctx) { return '/* line ' + ctx.debugInfo.lineNumber + ', ' + ctx.debugInfo.fileName + ' */\n'; }; tree.debugInfo.asMediaQuery = function(ctx) { return '@media -sass-debug-info{filename{font-family:' + ('file://' + ctx.debugInfo.fileName).replace(/([.:\/\\])/g, function (a) { if (a == '\\') { a = '\/'; } return '\\' + a; }) + '}line{font-family:\\00003' + ctx.debugInfo.lineNumber + '}}\n'; }; tree.find = function (obj, fun) { for (var i = 0, r; i < obj.length; i++) { r = fun.call(obj, obj[i]); if (r) { return r; } } return null; }; tree.jsify = function (obj) { if (Array.isArray(obj.value) && (obj.value.length > 1)) { return '[' + obj.value.map(function (v) { return v.toCSS(false); }).join(', ') + ']'; } else { return obj.toCSS(false); } }; tree.toCSS = function (env) { var strs = []; this.genCSS(env, { add: function(chunk, fileInfo, index) { strs.push(chunk); }, isEmpty: function () { return strs.length === 0; } }); return strs.join(''); }; tree.outputRuleset = function (env, output, rules) { var ruleCnt = rules.length, i; env.tabLevel = (env.tabLevel | 0) + 1; // Compressed if (env.compress) { output.add('{'); for (i = 0; i < ruleCnt; i++) { rules[i].genCSS(env, output); } output.add('}'); env.tabLevel--; return; } // Non-compressed var tabSetStr = '\n' + Array(env.tabLevel).join(" "), tabRuleStr = tabSetStr + " "; if (!ruleCnt) { output.add(" {" + tabSetStr + '}'); } else { output.add(" {" + tabRuleStr); rules[0].genCSS(env, output); for (i = 1; i < ruleCnt; i++) { output.add(tabRuleStr); rules[i].genCSS(env, output); } output.add(tabSetStr + '}'); } env.tabLevel--; }; })(require('./tree')); (function (tree) { tree.Alpha = function (val) { this.value = val; }; tree.Alpha.prototype = { type: "Alpha", accept: function (visitor) { this.value = visitor.visit(this.value); }, eval: function (env) { if (this.value.eval) { return new tree.Alpha(this.value.eval(env)); } return this; }, genCSS: function (env, output) { output.add("alpha(opacity="); if (this.value.genCSS) { this.value.genCSS(env, output); } else { output.add(this.value); } output.add(")"); }, toCSS: tree.toCSS }; })(require('../tree')); (function (tree) { tree.Anonymous = function (string, index, currentFileInfo, mapLines) { this.value = string.value || string; this.index = index; this.mapLines = mapLines; this.currentFileInfo = currentFileInfo; }; tree.Anonymous.prototype = { type: "Anonymous", eval: function () { return new tree.Anonymous(this.value, this.index, this.currentFileInfo, this.mapLines); }, compare: function (x) { if (!x.toCSS) { return -1; } var left = this.toCSS(), right = x.toCSS(); if (left === right) { return 0; } return left < right ? -1 : 1; }, genCSS: function (env, output) { output.add(this.value, this.currentFileInfo, this.index, this.mapLines); }, toCSS: tree.toCSS }; })(require('../tree')); (function (tree) { tree.Assignment = function (key, val) { this.key = key; this.value = val; }; tree.Assignment.prototype = { type: "Assignment", accept: function (visitor) { this.value = visitor.visit(this.value); }, eval: function (env) { if (this.value.eval) { return new(tree.Assignment)(this.key, this.value.eval(env)); } return this; }, genCSS: function (env, output) { output.add(this.key + '='); if (this.value.genCSS) { this.value.genCSS(env, output); } else { output.add(this.value); } }, toCSS: tree.toCSS }; })(require('../tree')); (function (tree) { // // A function call node. // tree.Call = function (name, args, index, currentFileInfo) { this.name = name; this.args = args; this.index = index; this.currentFileInfo = currentFileInfo; }; tree.Call.prototype = { type: "Call", accept: function (visitor) { if (this.args) { this.args = visitor.visitArray(this.args); } }, // // When evaluating a function call, // we either find the function in `tree.functions` [1], // in which case we call it, passing the evaluated arguments, // if this returns null or we cannot find the function, we // simply print it out as it appeared originally [2]. // // The *functions.js* file contains the built-in functions. // // The reason why we evaluate the arguments, is in the case where // we try to pass a variable to a function, like: `saturate(@color)`. // The function should receive the value, not the variable. // eval: function (env) { var args = this.args.map(function (a) { return a.eval(env); }), nameLC = this.name.toLowerCase(), result, func; if (nameLC in tree.functions) { // 1. try { func = new tree.functionCall(env, this.currentFileInfo); result = func[nameLC].apply(func, args); if (result != null) { return result; } } catch (e) { throw { type: e.type || "Runtime", message: "error evaluating function `" + this.name + "`" + (e.message ? ': ' + e.message : ''), index: this.index, filename: this.currentFileInfo.filename }; } } return new tree.Call(this.name, args, this.index, this.currentFileInfo); }, genCSS: function (env, output) { output.add(this.name + "(", this.currentFileInfo, this.index); for(var i = 0; i < this.args.length; i++) { this.args[i].genCSS(env, output); if (i + 1 < this.args.length) { output.add(", "); } } output.add(")"); }, toCSS: tree.toCSS }; })(require('../tree')); (function (tree) { // // RGB Colors - #ff0014, #eee // tree.Color = function (rgb, a) { // // The end goal here, is to parse the arguments // into an integer triplet, such as `128, 255, 0` // // This facilitates operations and conversions. // if (Array.isArray(rgb)) { this.rgb = rgb; } else if (rgb.length == 6) { this.rgb = rgb.match(/.{2}/g).map(function (c) { return parseInt(c, 16); }); } else { this.rgb = rgb.split('').map(function (c) { return parseInt(c + c, 16); }); } this.alpha = typeof(a) === 'number' ? a : 1; }; var transparentKeyword = "transparent"; tree.Color.prototype = { type: "Color", eval: function () { return this; }, luma: function () { var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255; r = (r <= 0.03928) ? r / 12.92 : Math.pow(((r + 0.055) / 1.055), 2.4); g = (g <= 0.03928) ? g / 12.92 : Math.pow(((g + 0.055) / 1.055), 2.4); b = (b <= 0.03928) ? b / 12.92 : Math.pow(((b + 0.055) / 1.055), 2.4); return 0.2126 * r + 0.7152 * g + 0.0722 * b; }, genCSS: function (env, output) { output.add(this.toCSS(env)); }, toCSS: function (env, doNotCompress) { var compress = env && env.compress && !doNotCompress, alpha = tree.fround(env, this.alpha); // If we have some transparency, the only way to represent it // is via `rgba`. Otherwise, we use the hex representation, // which has better compatibility with older browsers. // Values are capped between `0` and `255`, rounded and zero-padded. if (alpha < 1) { if (alpha === 0 && this.isTransparentKeyword) { return transparentKeyword; } return "rgba(" + this.rgb.map(function (c) { return clamp(Math.round(c), 255); }).concat(clamp(alpha, 1)) .join(',' + (compress ? '' : ' ')) + ")"; } else { var color = this.toRGB(); if (compress) { var splitcolor = color.split(''); // Convert color to short format if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) { color = '#' + splitcolor[1] + splitcolor[3] + splitcolor[5]; } } return color; } }, // // Operations have to be done per-channel, if not, // channels will spill onto each other. Once we have // our result, in the form of an integer triplet, // we create a new Color node to hold the result. // operate: function (env, op, other) { var rgb = []; var alpha = this.alpha * (1 - other.alpha) + other.alpha; for (var c = 0; c < 3; c++) { rgb[c] = tree.operate(env, op, this.rgb[c], other.rgb[c]); } return new(tree.Color)(rgb, alpha); }, toRGB: function () { return toHex(this.rgb); }, toHSL: function () { var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2, d = max - min; if (max === min) { h = s = 0; } else { s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h * 360, s: s, l: l, a: a }; }, //Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript toHSV: function () { var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, v = max; var d = max - min; if (max === 0) { s = 0; } else { s = d / max; } if (max === min) { h = 0; } else { switch(max){ case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h * 360, s: s, v: v, a: a }; }, toARGB: function () { return toHex([this.alpha * 255].concat(this.rgb)); }, compare: function (x) { if (!x.rgb) { return -1; } return (x.rgb[0] === this.rgb[0] && x.rgb[1] === this.rgb[1] && x.rgb[2] === this.rgb[2] && x.alpha === this.alpha) ? 0 : -1; } }; tree.Color.fromKeyword = function(keyword) { keyword = keyword.toLowerCase(); if (tree.colors.hasOwnProperty(keyword)) { // detect named color return new(tree.Color)(tree.colors[keyword].slice(1)); } if (keyword === transparentKeyword) { var transparent = new(tree.Color)([0, 0, 0], 0); transparent.isTransparentKeyword = true; return transparent; } }; function toHex(v) { return '#' + v.map(function (c) { c = clamp(Math.round(c), 255); return (c < 16 ? '0' : '') + c.toString(16); }).join(''); } function clamp(v, max) { return Math.min(Math.max(v, 0), max); } })(require('../tree')); (function (tree) { tree.Comment = function (value, silent, index, currentFileInfo) { this.value = value; this.silent = !!silent; this.currentFileInfo = currentFileInfo; }; tree.Comment.prototype = { type: "Comment", genCSS: function (env, output) { if (this.debugInfo) { output.add(tree.debugInfo(env, this), this.currentFileInfo, this.index); } output.add(this.value.trim()); //TODO shouldn't need to trim, we shouldn't grab the \n }, toCSS: tree.toCSS, isSilent: function(env) { var isReference = (this.currentFileInfo && this.currentFileInfo.reference && !this.isReferenced), isCompressed = env.compress && !this.value.match(/^\/\*!/); return this.silent || isReference || isCompressed; }, eval: function () { return this; }, markReferenced: function () { this.isReferenced = true; } }; })(require('../tree')); (function (tree) { tree.Condition = function (op, l, r, i, negate) { this.op = op.trim(); this.lvalue = l; this.rvalue = r; this.index = i; this.negate = negate; }; tree.Condition.prototype = { type: "Condition", accept: function (visitor) { this.lvalue = visitor.visit(this.lvalue); this.rvalue = visitor.visit(this.rvalue); }, eval: function (env) { var a = this.lvalue.eval(env), b = this.rvalue.eval(env); var i = this.index, result; result = (function (op) { switch (op) { case 'and': return a && b; case 'or': return a || b; default: if (a.compare) { result = a.compare(b); } else if (b.compare) { result = b.compare(a); } else { throw { type: "Type", message: "Unable to perform comparison", index: i }; } switch (result) { case -1: return op === '<' || op === '=<' || op === '<='; case 0: return op === '=' || op === '>=' || op === '=<' || op === '<='; case 1: return op === '>' || op === '>='; } } })(this.op); return this.negate ? !result : result; } }; })(require('../tree')); (function (tree) { tree.DetachedRuleset = function (ruleset, frames) { this.ruleset = ruleset; this.frames = frames; }; tree.DetachedRuleset.prototype = { type: "DetachedRuleset", accept: function (visitor) { this.ruleset = visitor.visit(this.ruleset); }, eval: function (env) { var frames = this.frames || env.frames.slice(0); return new tree.DetachedRuleset(this.ruleset, frames); }, callEval: function (env) { return this.ruleset.eval(this.frames ? new(tree.evalEnv)(env, this.frames.concat(env.frames)) : env); } }; })(require('../tree')); (function (tree) { // // A number with a unit // tree.Dimension = function (value, unit) { this.value = parseFloat(value); this.unit = (unit && unit instanceof tree.Unit) ? unit : new(tree.Unit)(unit ? [unit] : undefined); }; tree.Dimension.prototype = { type: "Dimension", accept: function (visitor) { this.unit = visitor.visit(this.unit); }, eval: function (env) { return this; }, toColor: function () { return new(tree.Color)([this.value, this.value, this.value]); }, genCSS: function (env, output) { if ((env && env.strictUnits) && !this.unit.isSingular()) { throw new Error("Multiple units in dimension. Correct the units or use the unit function. Bad unit: "+this.unit.toString()); } var value = tree.fround(env, this.value), strValue = String(value); if (value !== 0 && value < 0.000001 && value > -0.000001) { // would be output 1e-6 etc. strValue = value.toFixed(20).replace(/0+$/, ""); } if (env && env.compress) { // Zero values doesn't need a unit if (value === 0 && this.unit.isLength()) { output.add(strValue); return; } // Float values doesn't need a leading zero if (value > 0 && value < 1) { strValue = (strValue).substr(1); } } output.add(strValue); this.unit.genCSS(env, output); }, toCSS: tree.toCSS, // In an operation between two Dimensions, // we default to the first Dimension's unit, // so `1px + 2` will yield `3px`. operate: function (env, op, other) { /*jshint noempty:false */ var value = tree.operate(env, op, this.value, other.value), unit = this.unit.clone(); if (op === '+' || op === '-') { if (unit.numerator.length === 0 && unit.denominator.length === 0) { unit.numerator = other.unit.numerator.slice(0); unit.denominator = other.unit.denominator.slice(0); } else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) { // do nothing } else { other = other.convertTo(this.unit.usedUnits()); if(env.strictUnits && other.unit.toString() !== unit.toString()) { throw new Error("Incompatible units. Change the units or use the unit function. Bad units: '" + unit.toString() + "' and '" + other.unit.toString() + "'."); } value = tree.operate(env, op, this.value, other.value); } } else if (op === '*') { unit.numerator = unit.numerator.concat(other.unit.numerator).sort(); unit.denominator = unit.denominator.concat(other.unit.denominator).sort(); unit.cancel(); } else if (op === '/') { unit.numerator = unit.numerator.concat(other.unit.denominator).sort(); unit.denominator = unit.denominator.concat(other.unit.numerator).sort(); unit.cancel(); } return new(tree.Dimension)(value, unit); }, compare: function (other) { if (other instanceof tree.Dimension) { var a, b, aValue, bValue; if (this.unit.isEmpty() || other.unit.isEmpty()) { a = this; b = other; } else { a = this.unify(); b = other.unify(); if (a.unit.compare(b.unit) !== 0) { return -1; } } aValue = a.value; bValue = b.value; if (bValue > aValue) { return -1; } else if (bValue < aValue) { return 1; } else { return 0; } } else { return -1; } }, unify: function () { return this.convertTo({ length: 'px', duration: 's', angle: 'rad' }); }, convertTo: function (conversions) { var value = this.value, unit = this.unit.clone(), i, groupName, group, targetUnit, derivedConversions = {}, applyUnit; if (typeof conversions === 'string') { for(i in tree.UnitConversions) { if (tree.UnitConversions[i].hasOwnProperty(conversions)) { derivedConversions = {}; derivedConversions[i] = conversions; } } conversions = derivedConversions; } applyUnit = function (atomicUnit, denominator) { /*jshint loopfunc:true */ if (group.hasOwnProperty(atomicUnit)) { if (denominator) { value = value / (group[atomicUnit] / group[targetUnit]); } else { value = value * (group[atomicUnit] / group[targetUnit]); } return targetUnit; } return atomicUnit; }; for (groupName in conversions) { if (conversions.hasOwnProperty(groupName)) { targetUnit = conversions[groupName]; group = tree.UnitConversions[groupName]; unit.map(applyUnit); } } unit.cancel(); return new(tree.Dimension)(value, unit); } }; // http://www.w3.org/TR/css3-values/#absolute-lengths tree.UnitConversions = { length: { 'm': 1, 'cm': 0.01, 'mm': 0.001, 'in': 0.0254, 'px': 0.0254 / 96, 'pt': 0.0254 / 72, 'pc': 0.0254 / 72 * 12 }, duration: { 's': 1, 'ms': 0.001 }, angle: { 'rad': 1/(2*Math.PI), 'deg': 1/360, 'grad': 1/400, 'turn': 1 } }; tree.Unit = function (numerator, denominator, backupUnit) { this.numerator = numerator ? numerator.slice(0).sort() : []; this.denominator = denominator ? denominator.slice(0).sort() : []; this.backupUnit = backupUnit; }; tree.Unit.prototype = { type: "Unit", clone: function () { return new tree.Unit(this.numerator.slice(0), this.denominator.slice(0), this.backupUnit); }, genCSS: function (env, output) { if (this.numerator.length >= 1) { output.add(this.numerator[0]); } else if (this.denominator.length >= 1) { output.add(this.denominator[0]); } else if ((!env || !env.strictUnits) && this.backupUnit) { output.add(this.backupUnit); } }, toCSS: tree.toCSS, toString: function () { var i, returnStr = this.numerator.join("*"); for (i = 0; i < this.denominator.length; i++) { returnStr += "/" + this.denominator[i]; } return returnStr; }, compare: function (other) { return this.is(other.toString()) ? 0 : -1; }, is: function (unitString) { return this.toString() === unitString; }, isLength: function () { return Boolean(this.toCSS().match(/px|em|%|in|cm|mm|pc|pt|ex/)); }, isEmpty: function () { return this.numerator.length === 0 && this.denominator.length === 0; }, isSingular: function() { return this.numerator.length <= 1 && this.denominator.length === 0; }, map: function(callback) { var i; for (i = 0; i < this.numerator.length; i++) { this.numerator[i] = callback(this.numerator[i], false); } for (i = 0; i < this.denominator.length; i++) { this.denominator[i] = callback(this.denominator[i], true); } }, usedUnits: function() { var group, result = {}, mapUnit; mapUnit = function (atomicUnit) { /*jshint loopfunc:true */ if (group.hasOwnProperty(atomicUnit) && !result[groupName]) { result[groupName] = atomicUnit; } return atomicUnit; }; for (var groupName in tree.UnitConversions) { if (tree.UnitConversions.hasOwnProperty(groupName)) { group = tree.UnitConversions[groupName]; this.map(mapUnit); } } return result; }, cancel: function () { var counter = {}, atomicUnit, i, backup; for (i = 0; i < this.numerator.length; i++) { atomicUnit = this.numerator[i]; if (!backup) { backup = atomicUnit; } counter[atomicUnit] = (counter[atomicUnit] || 0) + 1; } for (i = 0; i < this.denominator.length; i++) { atomicUnit = this.denominator[i]; if (!backup) { backup = atomicUnit; } counter[atomicUnit] = (counter[atomicUnit] || 0) - 1; } this.numerator = []; this.denominator = []; for (atomicUnit in counter) { if (counter.hasOwnProperty(atomicUnit)) { var count = counter[atomicUnit]; if (count > 0) { for (i = 0; i < count; i++) { this.numerator.push(atomicUnit); } } else if (count < 0) { for (i = 0; i < -count; i++) { this.denominator.push(atomicUnit); } } } } if (this.numerator.length === 0 && this.denominator.length === 0 && backup) { this.backupUnit = backup; } this.numerator.sort(); this.denominator.sort(); } }; })(require('../tree')); (function (tree) { tree.Directive = function (name, value, rules, index, currentFileInfo, debugInfo) { this.name = name; this.value = value; if (rules) { this.rules = rules; this.rules.allowImports = true; } this.index = index; this.currentFileInfo = currentFileInfo; this.debugInfo = debugInfo; }; tree.Directive.prototype = { type: "Directive", accept: function (visitor) { var value = this.value, rules = this.rules; if (rules) { rules = visitor.visit(rules); } if (value) { value = visitor.visit(value); } }, genCSS: function (env, output) { var value = this.value, rules = this.rules; output.add(this.name, this.currentFileInfo, this.index); if (value) { output.add(' '); value.genCSS(env, output); } if (rules) { tree.outputRuleset(env, output, [rules]); } else { output.add(';'); } }, toCSS: tree.toCSS, eval: function (env) { var value = this.value, rules = this.rules; if (value) { value = value.eval(env); } if (rules) { rules = rules.eval(env); rules.root = true; } return new(tree.Directive)(this.name, value, rules, this.index, this.currentFileInfo, this.debugInfo); }, variable: function (name) { if (this.rules) return tree.Ruleset.prototype.variable.call(this.rules, name); }, find: function () { if (this.rules) return tree.Ruleset.prototype.find.apply(this.rules, arguments); }, rulesets: function () { if (this.rules) return tree.Ruleset.prototype.rulesets.apply(this.rules); }, markReferenced: function () { var i, rules; this.isReferenced = true; if (this.rules) { rules = this.rules.rules; for (i = 0; i < rules.length; i++) { if (rules[i].markReferenced) { rules[i].markReferenced(); } } } } }; })(require('../tree')); (function (tree) { tree.Element = function (combinator, value, index, currentFileInfo) { this.combinator = combinator instanceof tree.Combinator ? combinator : new(tree.Combinator)(combinator); if (typeof(value) === 'string') { this.value = value.trim(); } else if (value) { this.value = value; } else { this.value = ""; } this.index = index; this.currentFileInfo = currentFileInfo; }; tree.Element.prototype = { type: "Element", accept: function (visitor) { var value = this.value; this.combinator = visitor.visit(this.combinator); if (typeof value === "object") { this.value = visitor.visit(value); } }, eval: function (env) { return new(tree.Element)(this.combinator, this.value.eval ? this.value.eval(env) : this.value, this.index, this.currentFileInfo); }, genCSS: function (env, output) { output.add(this.toCSS(env), this.currentFileInfo, this.index); }, toCSS: function (env) { var value = (this.value.toCSS ? this.value.toCSS(env) : this.value); if (value === '' && this.combinator.value.charAt(0) === '&') { return ''; } else { return this.combinator.toCSS(env || {}) + value; } } }; tree.Attribute = function (key, op, value) { this.key = key; this.op = op; this.value = value; }; tree.Attribute.prototype = { type: "Attribute", eval: function (env) { return new(tree.Attribute)(this.key.eval ? this.key.eval(env) : this.key, this.op, (this.value && this.value.eval) ? this.value.eval(env) : this.value); }, genCSS: function (env, output) { output.add(this.toCSS(env)); }, toCSS: function (env) { var value = this.key.toCSS ? this.key.toCSS(env) : this.key; if (this.op) { value += this.op; value += (this.value.toCSS ? this.value.toCSS(env) : this.value); } return '[' + value + ']'; } }; tree.Combinator = function (value) { if (value === ' ') { this.value = ' '; } else { this.value = value ? value.trim() : ""; } }; tree.Combinator.prototype = { type: "Combinator", _outputMap: { '' : '', ' ' : ' ', ':' : ' :', '+' : ' + ', '~' : ' ~ ', '>' : ' > ', '|' : '|', '^' : ' ^ ', '^^' : ' ^^ ' }, _outputMapCompressed: { '' : '', ' ' : ' ', ':' : ' :', '+' : '+', '~' : '~', '>' : '>', '|' : '|', '^' : '^', '^^' : '^^' }, genCSS: function (env, output) { output.add((env.compress ? this._outputMapCompressed : this._outputMap)[this.value]); }, toCSS: tree.toCSS }; })(require('../tree')); (function (tree) { tree.Expression = function (value) { this.value = value; }; tree.Expression.prototype = { type: "Expression", accept: function (visitor) { if (this.value) { this.value = visitor.visitArray(this.value); } }, eval: function (env) { var returnValue, inParenthesis = this.parens && !this.parensInOp, doubleParen = false; if (inParenthesis) { env.inParenthesis(); } if (this.value.length > 1) { returnValue = new(tree.Expression)(this.value.map(function (e) { return e.eval(env); })); } else if (this.value.length === 1) { if (this.value[0].parens && !this.value[0].parensInOp) { doubleParen = true; } returnValue = this.value[0].eval(env); } else { returnValue = this; } if (inParenthesis) { env.outOfParenthesis(); } if (this.parens && this.parensInOp && !(env.isMathOn()) && !doubleParen) { returnValue = new(tree.Paren)(returnValue); } return returnValue; }, genCSS: function (env, output) { for(var i = 0; i < this.value.length; i++) { this.value[i].genCSS(env, output); if (i + 1 < this.value.length) { output.add(" "); } } }, toCSS: tree.toCSS, throwAwayComments: function () { this.value = this.value.filter(function(v) { return !(v instanceof tree.Comment); }); } }; })(require('../tree')); (function (tree) { tree.Extend = function Extend(selector, option, index) { this.selector = selector; this.option = option; this.index = index; this.object_id = tree.Extend.next_id++; this.parent_ids = [this.object_id]; switch(option) { case "all": this.allowBefore = true; this.allowAfter = true; break; default: this.allowBefore = false; this.allowAfter = false; break; } }; tree.Extend.next_id = 0; tree.Extend.prototype = { type: "Extend", accept: function (visitor) { this.selector = visitor.visit(this.selector); }, eval: function (env) { return new(tree.Extend)(this.selector.eval(env), this.option, this.index); }, clone: function (env) { return new(tree.Extend)(this.selector, this.option, this.index); }, findSelfSelectors: function (selectors) { var selfElements = [], i, selectorElements; for(i = 0; i < selectors.length; i++) { selectorElements = selectors[i].elements; // duplicate the logic in genCSS function inside the selector node. // future TODO - move both logics into the selector joiner visitor if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === "") { selectorElements[0].combinator.value = ' '; } selfElements = selfElements.concat(selectors[i].elements); } this.selfSelectors = [{ elements: selfElements }]; } }; })(require('../tree')); (function (tree) { // // CSS @import node // // The general strategy here is that we don't want to wait // for the parsing to be completed, before we start importing // the file. That's because in the context of a browser, // most of the time will be spent waiting for the server to respond. // // On creation, we push the import path to our import queue, though // `import,push`, we also pass it a callback, which it'll call once // the file has been fetched, and parsed. // tree.Import = function (path, features, options, index, currentFileInfo) { this.options = options; this.index = index; this.path = path; this.features = features; this.currentFileInfo = currentFileInfo; if (this.options.less !== undefined || this.options.inline) { this.css = !this.options.less || this.options.inline; } else { var pathValue = this.getPath(); if (pathValue && /css([\?;].*)?$/.test(pathValue)) { this.css = true; } } }; // // The actual import node doesn't return anything, when converted to CSS. // The reason is that it's used at the evaluation stage, so that the rules // it imports can be treated like any other rules. // // In `eval`, we make sure all Import nodes get evaluated, recursively, so // we end up with a flat structure, which can easily be imported in the parent // ruleset. // tree.Import.prototype = { type: "Import", accept: function (visitor) { if (this.features) { this.features = visitor.visit(this.features); } this.path = visitor.visit(this.path); if (!this.options.inline && this.root) { this.root = visitor.visit(this.root); } }, genCSS: function (env, output) { if (this.css) { output.add("@import ", this.currentFileInfo, this.index); this.path.genCSS(env, output); if (this.features) { output.add(" "); this.features.genCSS(env, output); } output.add(';'); } }, toCSS: tree.toCSS, getPath: function () { if (this.path instanceof tree.Quoted) { var path = this.path.value; return (this.css !== undefined || /(\.[a-z]*$)|([\?;].*)$/.test(path)) ? path : path + '.less'; } else if (this.path instanceof tree.URL) { return this.path.value.value; } return null; }, evalForImport: function (env) { return new(tree.Import)(this.path.eval(env), this.features, this.options, this.index, this.currentFileInfo); }, evalPath: function (env) { var path = this.path.eval(env); var rootpath = this.currentFileInfo && this.currentFileInfo.rootpath; if (!(path instanceof tree.URL)) { if (rootpath) { var pathValue = path.value; // Add the base path if the import is relative if (pathValue && env.isPathRelative(pathValue)) { path.value = rootpath +pathValue; } } path.value = env.normalizePath(path.value); } return path; }, eval: function (env) { var ruleset, features = this.features && this.features.eval(env); if (this.skip) { if (typeof this.skip === "function") { this.skip = this.skip(); } if (this.skip) { return []; } } if (this.options.inline) { //todo needs to reference css file not import var contents = new(tree.Anonymous)(this.root, 0, {filename: this.importedFilename}, true); return this.features ? new(tree.Media)([contents], this.features.value) : [contents]; } else if (this.css) { var newImport = new(tree.Import)(this.evalPath(env), features, this.options, this.index); if (!newImport.css && this.error) { throw this.error; } return newImport; } else { ruleset = new(tree.Ruleset)(null, this.root.rules.slice(0)); ruleset.evalImports(env); return this.features ? new(tree.Media)(ruleset.rules, this.features.value) : ruleset.rules; } } }; })(require('../tree')); (function (tree) { tree.JavaScript = function (string, index, escaped) { this.escaped = escaped; this.expression = string; this.index = index; }; tree.JavaScript.prototype = { type: "JavaScript", eval: function (env) { var result, that = this, context = {}; var expression = this.expression.replace(/@\{([\w-]+)\}/g, function (_, name) { return tree.jsify(new(tree.Variable)('@' + name, that.index).eval(env)); }); try { expression = new(Function)('return (' + expression + ')'); } catch (e) { throw { message: "JavaScript evaluation error: " + e.message + " from `" + expression + "`" , index: this.index }; } var variables = env.frames[0].variables(); for (var k in variables) { if (variables.hasOwnProperty(k)) { /*jshint loopfunc:true */ context[k.slice(1)] = { value: variables[k].value, toJS: function () { return this.value.eval(env).toCSS(); } }; } } try { result = expression.call(context); } catch (e) { throw { message: "JavaScript evaluation error: '" + e.name + ': ' + e.message.replace(/["]/g, "'") + "'" , index: this.index }; } if (typeof(result) === 'number') { return new(tree.Dimension)(result); } else if (typeof(result) === 'string') { return new(tree.Quoted)('"' + result + '"', result, this.escaped, this.index); } else if (Array.isArray(result)) { return new(tree.Anonymous)(result.join(', ')); } else { return new(tree.Anonymous)(result); } } }; })(require('../tree')); (function (tree) { tree.Keyword = function (value) { this.value = value; }; tree.Keyword.prototype = { type: "Keyword", eval: function () { return this; }, genCSS: function (env, output) { if (this.value === '%') { throw { type: "Syntax", message: "Invalid % without number" }; } output.add(this.value); }, toCSS: tree.toCSS, compare: function (other) { if (other instanceof tree.Keyword) { return other.value === this.value ? 0 : 1; } else { return -1; } } }; tree.True = new(tree.Keyword)('true'); tree.False = new(tree.Keyword)('false'); })(require('../tree')); (function (tree) { tree.Media = function (value, features, index, currentFileInfo) { this.index = index; this.currentFileInfo = currentFileInfo; var selectors = this.emptySelectors(); this.features = new(tree.Value)(features); this.rules = [new(tree.Ruleset)(selectors, value)]; this.rules[0].allowImports = true; }; tree.Media.prototype = { type: "Media", accept: function (visitor) { if (this.features) { this.features = visitor.visit(this.features); } if (this.rules) { this.rules = visitor.visitArray(this.rules); } }, genCSS: function (env, output) { output.add('@media ', this.currentFileInfo, this.index); this.features.genCSS(env, output); tree.outputRuleset(env, output, this.rules); }, toCSS: tree.toCSS, eval: function (env) { if (!env.mediaBlocks) { env.mediaBlocks = []; env.mediaPath = []; } var media = new(tree.Media)(null, [], this.index, this.currentFileInfo); if(this.debugInfo) { this.rules[0].debugInfo = this.debugInfo; media.debugInfo = this.debugInfo; } var strictMathBypass = false; if (!env.strictMath) { strictMathBypass = true; env.strictMath = true; } try { media.features = this.features.eval(env); } finally { if (strictMathBypass) { env.strictMath = false; } } env.mediaPath.push(media); env.mediaBlocks.push(media); env.frames.unshift(this.rules[0]); media.rules = [this.rules[0].eval(env)]; env.frames.shift(); env.mediaPath.pop(); return env.mediaPath.length === 0 ? media.evalTop(env) : media.evalNested(env); }, variable: function (name) { return tree.Ruleset.prototype.variable.call(this.rules[0], name); }, find: function () { return tree.Ruleset.prototype.find.apply(this.rules[0], arguments); }, rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.rules[0]); }, emptySelectors: function() { var el = new(tree.Element)('', '&', this.index, this.currentFileInfo), sels = [new(tree.Selector)([el], null, null, this.index, this.currentFileInfo)]; sels[0].mediaEmpty = true; return sels; }, markReferenced: function () { var i, rules = this.rules[0].rules; this.rules[0].markReferenced(); this.isReferenced = true; for (i = 0; i < rules.length; i++) { if (rules[i].markReferenced) { rules[i].markReferenced(); } } }, evalTop: function (env) { var result = this; // Render all dependent Media blocks. if (env.mediaBlocks.length > 1) { var selectors = this.emptySelectors(); result = new(tree.Ruleset)(selectors, env.mediaBlocks); result.multiMedia = true; } delete env.mediaBlocks; delete env.mediaPath; return result; }, evalNested: function (env) { var i, value, path = env.mediaPath.concat([this]); // Extract the media-query conditions separated with `,` (OR). for (i = 0; i < path.length; i++) { value = path[i].features instanceof tree.Value ? path[i].features.value : path[i].features; path[i] = Array.isArray(value) ? value : [value]; } // Trace all permutations to generate the resulting media-query. // // (a, b and c) with nested (d, e) -> // a and d // a and e // b and c and d // b and c and e this.features = new(tree.Value)(this.permute(path).map(function (path) { path = path.map(function (fragment) { return fragment.toCSS ? fragment : new(tree.Anonymous)(fragment); }); for(i = path.length - 1; i > 0; i--) { path.splice(i, 0, new(tree.Anonymous)("and")); } return new(tree.Expression)(path); })); // Fake a tree-node that doesn't output anything. return new(tree.Ruleset)([], []); }, permute: function (arr) { if (arr.length === 0) { return []; } else if (arr.length === 1) { return arr[0]; } else { var result = []; var rest = this.permute(arr.slice(1)); for (var i = 0; i < rest.length; i++) { for (var j = 0; j < arr[0].length; j++) { result.push([arr[0][j]].concat(rest[i])); } } return result; } }, bubbleSelectors: function (selectors) { if (!selectors) return; this.rules = [new(tree.Ruleset)(selectors.slice(0), [this.rules[0]])]; } }; })(require('../tree')); (function (tree) { tree.mixin = {}; tree.mixin.Call = function (elements, args, index, currentFileInfo, important) { this.selector = new(tree.Selector)(elements); this.arguments = (args && args.length) ? args : null; this.index = index; this.currentFileInfo = currentFileInfo; this.important = important; }; tree.mixin.Call.prototype = { type: "MixinCall", accept: function (visitor) { if (this.selector) { this.selector = visitor.visit(this.selector); } if (this.arguments) { this.arguments = visitor.visitArray(this.arguments); } }, eval: function (env) { var mixins, mixin, args, rules = [], match = false, i, m, f, isRecursive, isOneFound, rule, candidates = [], candidate, conditionResult = [], defaultFunc = tree.defaultFunc, defaultResult, defNone = 0, defTrue = 1, defFalse = 2, count; args = this.arguments && this.arguments.map(function (a) { return { name: a.name, value: a.value.eval(env) }; }); for (i = 0; i < env.frames.length; i++) { if ((mixins = env.frames[i].find(this.selector)).length > 0) { isOneFound = true; // To make `default()` function independent of definition order we have two "subpasses" here. // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`), // and build candidate list with corresponding flags. Then, when we know all possible matches, // we make a final decision. for (m = 0; m < mixins.length; m++) { mixin = mixins[m]; isRecursive = false; for(f = 0; f < env.frames.length; f++) { if ((!(mixin instanceof tree.mixin.Definition)) && mixin === (env.frames[f].originalRuleset || env.frames[f])) { isRecursive = true; break; } } if (isRecursive) { continue; } if (mixin.matchArgs(args, env)) { candidate = {mixin: mixin, group: defNone}; if (mixin.matchCondition) { for (f = 0; f < 2; f++) { defaultFunc.value(f); conditionResult[f] = mixin.matchCondition(args, env); } if (conditionResult[0] || conditionResult[1]) { if (conditionResult[0] != conditionResult[1]) { candidate.group = conditionResult[1] ? defTrue : defFalse; } candidates.push(candidate); } } else { candidates.push(candidate); } match = true; } } defaultFunc.reset(); count = [0, 0, 0]; for (m = 0; m < candidates.length; m++) { count[candidates[m].group]++; } if (count[defNone] > 0) { defaultResult = defFalse; } else { defaultResult = defTrue; if ((count[defTrue] + count[defFalse]) > 1) { throw { type: 'Runtime', message: 'Ambiguous use of `default()` found when matching for `' + this.format(args) + '`', index: this.index, filename: this.currentFileInfo.filename }; } } for (m = 0; m < candidates.length; m++) { candidate = candidates[m].group; if ((candidate === defNone) || (candidate === defaultResult)) { try { mixin = candidates[m].mixin; if (!(mixin instanceof tree.mixin.Definition)) { mixin = new tree.mixin.Definition("", [], mixin.rules, null, false); mixin.originalRuleset = mixins[m].originalRuleset || mixins[m]; } Array.prototype.push.apply( rules, mixin.evalCall(env, args, this.important).rules); } catch (e) { throw { message: e.message, index: this.index, filename: this.currentFileInfo.filename, stack: e.stack }; } } } if (match) { if (!this.currentFileInfo || !this.currentFileInfo.reference) { for (i = 0; i < rules.length; i++) { rule = rules[i]; if (rule.markReferenced) { rule.markReferenced(); } } } return rules; } } } if (isOneFound) { throw { type: 'Runtime', message: 'No matching definition was found for `' + this.format(args) + '`', index: this.index, filename: this.currentFileInfo.filename }; } else { throw { type: 'Name', message: this.selector.toCSS().trim() + " is undefined", index: this.index, filename: this.currentFileInfo.filename }; } }, format: function (args) { return this.selector.toCSS().trim() + '(' + (args ? args.map(function (a) { var argValue = ""; if (a.name) { argValue += a.name + ":"; } if (a.value.toCSS) { argValue += a.value.toCSS(); } else { argValue += "???"; } return argValue; }).join(', ') : "") + ")"; } }; tree.mixin.Definition = function (name, params, rules, condition, variadic, frames) { this.name = name; this.selectors = [new(tree.Selector)([new(tree.Element)(null, name, this.index, this.currentFileInfo)])]; this.params = params; this.condition = condition; this.variadic = variadic; this.arity = params.length; this.rules = rules; this._lookups = {}; this.required = params.reduce(function (count, p) { if (!p.name || (p.name && !p.value)) { return count + 1; } else { return count; } }, 0); this.parent = tree.Ruleset.prototype; this.frames = frames; }; tree.mixin.Definition.prototype = { type: "MixinDefinition", accept: function (visitor) { if (this.params && this.params.length) { this.params = visitor.visitArray(this.params); } this.rules = visitor.visitArray(this.rules); if (this.condition) { this.condition = visitor.visit(this.condition); } }, variable: function (name) { return this.parent.variable.call(this, name); }, variables: function () { return this.parent.variables.call(this); }, find: function () { return this.parent.find.apply(this, arguments); }, rulesets: function () { return this.parent.rulesets.apply(this); }, evalParams: function (env, mixinEnv, args, evaldArguments) { /*jshint boss:true */ var frame = new(tree.Ruleset)(null, null), varargs, arg, params = this.params.slice(0), i, j, val, name, isNamedFound, argIndex, argsLength = 0; mixinEnv = new tree.evalEnv(mixinEnv, [frame].concat(mixinEnv.frames)); if (args) { args = args.slice(0); argsLength = args.length; for(i = 0; i < argsLength; i++) { arg = args[i]; if (name = (arg && arg.name)) { isNamedFound = false; for(j = 0; j < params.length; j++) { if (!evaldArguments[j] && name === params[j].name) { evaldArguments[j] = arg.value.eval(env); frame.prependRule(new(tree.Rule)(name, arg.value.eval(env))); isNamedFound = true; break; } } if (isNamedFound) { args.splice(i, 1); i--; continue; } else { throw { type: 'Runtime', message: "Named argument for " + this.name + ' ' + args[i].name + ' not found' }; } } } } argIndex = 0; for (i = 0; i < params.length; i++) { if (evaldArguments[i]) { continue; } arg = args && args[argIndex]; if (name = params[i].name) { if (params[i].variadic) { varargs = []; for (j = argIndex; j < argsLength; j++) { varargs.push(args[j].value.eval(env)); } frame.prependRule(new(tree.Rule)(name, new(tree.Expression)(varargs).eval(env))); } else { val = arg && arg.value; if (val) { val = val.eval(env); } else if (params[i].value) { val = params[i].value.eval(mixinEnv); frame.resetCache(); } else { throw { type: 'Runtime', message: "wrong number of arguments for " + this.name + ' (' + argsLength + ' for ' + this.arity + ')' }; } frame.prependRule(new(tree.Rule)(name, val)); evaldArguments[i] = val; } } if (params[i].variadic && args) { for (j = argIndex; j < argsLength; j++) { evaldArguments[j] = args[j].value.eval(env); } } argIndex++; } return frame; }, eval: function (env) { return new tree.mixin.Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || env.frames.slice(0)); }, evalCall: function (env, args, important) { var _arguments = [], mixinFrames = this.frames ? this.frames.concat(env.frames) : env.frames, frame = this.evalParams(env, new(tree.evalEnv)(env, mixinFrames), args, _arguments), rules, ruleset; frame.prependRule(new(tree.Rule)('@arguments', new(tree.Expression)(_arguments).eval(env))); rules = this.rules.slice(0); ruleset = new(tree.Ruleset)(null, rules); ruleset.originalRuleset = this; ruleset = ruleset.eval(new(tree.evalEnv)(env, [this, frame].concat(mixinFrames))); if (important) { ruleset = this.parent.makeImportant.apply(ruleset); } return ruleset; }, matchCondition: function (args, env) { if (this.condition && !this.condition.eval( new(tree.evalEnv)(env, [this.evalParams(env, new(tree.evalEnv)(env, this.frames.concat(env.frames)), args, [])] // the parameter variables .concat(this.frames) // the parent namespace/mixin frames .concat(env.frames)))) { // the current environment frames return false; } return true; }, matchArgs: function (args, env) { var argsLength = (args && args.length) || 0, len; if (! this.variadic) { if (argsLength < this.required) { return false; } if (argsLength > this.params.length) { return false; } } else { if (argsLength < (this.required - 1)) { return false; } } len = Math.min(argsLength, this.arity); for (var i = 0; i < len; i++) { if (!this.params[i].name && !this.params[i].variadic) { if (args[i].value.eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) { return false; } } } return true; } }; })(require('../tree')); (function (tree) { tree.Negative = function (node) { this.value = node; }; tree.Negative.prototype = { type: "Negative", accept: function (visitor) { this.value = visitor.visit(this.value); }, genCSS: function (env, output) { output.add('-'); this.value.genCSS(env, output); }, toCSS: tree.toCSS, eval: function (env) { if (env.isMathOn()) { return (new(tree.Operation)('*', [new(tree.Dimension)(-1), this.value])).eval(env); } return new(tree.Negative)(this.value.eval(env)); } }; })(require('../tree')); (function (tree) { tree.Operation = function (op, operands, isSpaced) { this.op = op.trim(); this.operands = operands; this.isSpaced = isSpaced; }; tree.Operation.prototype = { type: "Operation", accept: function (visitor) { this.operands = visitor.visit(this.operands); }, eval: function (env) { var a = this.operands[0].eval(env), b = this.operands[1].eval(env); if (env.isMathOn()) { if (a instanceof tree.Dimension && b instanceof tree.Color) { a = a.toColor(); } if (b instanceof tree.Dimension && a instanceof tree.Color) { b = b.toColor(); } if (!a.operate) { throw { type: "Operation", message: "Operation on an invalid type" }; } return a.operate(env, this.op, b); } else { return new(tree.Operation)(this.op, [a, b], this.isSpaced); } }, genCSS: function (env, output) { this.operands[0].genCSS(env, output); if (this.isSpaced) { output.add(" "); } output.add(this.op); if (this.isSpaced) { output.add(" "); } this.operands[1].genCSS(env, output); }, toCSS: tree.toCSS }; tree.operate = function (env, op, a, b) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; } }; })(require('../tree')); (function (tree) { tree.Paren = function (node) { this.value = node; }; tree.Paren.prototype = { type: "Paren", accept: function (visitor) { this.value = visitor.visit(this.value); }, genCSS: function (env, output) { output.add('('); this.value.genCSS(env, output); output.add(')'); }, toCSS: tree.toCSS, eval: function (env) { return new(tree.Paren)(this.value.eval(env)); } }; })(require('../tree')); (function (tree) { tree.Quoted = function (str, content, escaped, index, currentFileInfo) { this.escaped = escaped; this.value = content || ''; this.quote = str.charAt(0); this.index = index; this.currentFileInfo = currentFileInfo; }; tree.Quoted.prototype = { type: "Quoted", genCSS: function (env, output) { if (!this.escaped) { output.add(this.quote, this.currentFileInfo, this.index); } output.add(this.value); if (!this.escaped) { output.add(this.quote); } }, toCSS: tree.toCSS, eval: function (env) { var that = this; var value = this.value.replace(/`([^`]+)`/g, function (_, exp) { return new(tree.JavaScript)(exp, that.index, true).eval(env).value; }).replace(/@\{([\w-]+)\}/g, function (_, name) { var v = new(tree.Variable)('@' + name, that.index, that.currentFileInfo).eval(env, true); return (v instanceof tree.Quoted) ? v.value : v.toCSS(); }); return new(tree.Quoted)(this.quote + value + this.quote, value, this.escaped, this.index, this.currentFileInfo); }, compare: function (x) { if (!x.toCSS) { return -1; } var left = this.toCSS(), right = x.toCSS(); if (left === right) { return 0; } return left < right ? -1 : 1; } }; })(require('../tree')); (function (tree) { tree.Rule = function (name, value, important, merge, index, currentFileInfo, inline) { this.name = name; this.value = (value instanceof tree.Value || value instanceof tree.Ruleset) ? value : new(tree.Value)([value]); this.important = important ? ' ' + important.trim() : ''; this.merge = merge; this.index = index; this.currentFileInfo = currentFileInfo; this.inline = inline || false; this.variable = name.charAt && (name.charAt(0) === '@'); }; tree.Rule.prototype = { type: "Rule", accept: function (visitor) { this.value = visitor.visit(this.value); }, genCSS: function (env, output) { output.add(this.name + (env.compress ? ':' : ': '), this.currentFileInfo, this.index); try { this.value.genCSS(env, output); } catch(e) { e.index = this.index; e.filename = this.currentFileInfo.filename; throw e; } output.add(this.important + ((this.inline || (env.lastRule && env.compress)) ? "" : ";"), this.currentFileInfo, this.index); }, toCSS: tree.toCSS, eval: function (env) { var strictMathBypass = false, name = this.name, evaldValue; if (typeof name !== "string") { // expand 'primitive' name directly to get // things faster (~10% for benchmark.less): name = (name.length === 1) && (name[0] instanceof tree.Keyword) ? name[0].value : evalName(env, name); } if (name === "font" && !env.strictMath) { strictMathBypass = true; env.strictMath = true; } try { evaldValue = this.value.eval(env); if (!this.variable && evaldValue.type === "DetachedRuleset") { throw { message: "Rulesets cannot be evaluated on a property.", index: this.index, filename: this.currentFileInfo.filename }; } return new(tree.Rule)(name, evaldValue, this.important, this.merge, this.index, this.currentFileInfo, this.inline); } catch(e) { if (typeof e.index !== 'number') { e.index = this.index; e.filename = this.currentFileInfo.filename; } throw e; } finally { if (strictMathBypass) { env.strictMath = false; } } }, makeImportant: function () { return new(tree.Rule)(this.name, this.value, "!important", this.merge, this.index, this.currentFileInfo, this.inline); } }; function evalName(env, name) { var value = "", i, n = name.length, output = {add: function (s) {value += s;}}; for (i = 0; i < n; i++) { name[i].eval(env).genCSS(env, output); } return value; } })(require('../tree')); (function (tree) { tree.RulesetCall = function (variable) { this.variable = variable; }; tree.RulesetCall.prototype = { type: "RulesetCall", accept: function (visitor) { }, eval: function (env) { var detachedRuleset = new(tree.Variable)(this.variable).eval(env); return detachedRuleset.callEval(env); } }; })(require('../tree')); (function (tree) { tree.Ruleset = function (selectors, rules, strictImports) { this.selectors = selectors; this.rules = rules; this._lookups = {}; this.strictImports = strictImports; }; tree.Ruleset.prototype = { type: "Ruleset", accept: function (visitor) { if (this.paths) { visitor.visitArray(this.paths, true); } else if (this.selectors) { this.selectors = visitor.visitArray(this.selectors); } if (this.rules && this.rules.length) { this.rules = visitor.visitArray(this.rules); } }, eval: function (env) { var thisSelectors = this.selectors, selectors, selCnt, selector, i, defaultFunc = tree.defaultFunc, hasOnePassingSelector = false; if (thisSelectors && (selCnt = thisSelectors.length)) { selectors = []; defaultFunc.error({ type: "Syntax", message: "it is currently only allowed in parametric mixin guards," }); for (i = 0; i < selCnt; i++) { selector = thisSelectors[i].eval(env); selectors.push(selector); if (selector.evaldCondition) { hasOnePassingSelector = true; } } defaultFunc.reset(); } else { hasOnePassingSelector = true; } var rules = this.rules ? this.rules.slice(0) : null, ruleset = new(tree.Ruleset)(selectors, rules, this.strictImports), rule, subRule; ruleset.originalRuleset = this; ruleset.root = this.root; ruleset.firstRoot = this.firstRoot; ruleset.allowImports = this.allowImports; if(this.debugInfo) { ruleset.debugInfo = this.debugInfo; } if (!hasOnePassingSelector) { rules.length = 0; } // push the current ruleset to the frames stack var envFrames = env.frames; envFrames.unshift(ruleset); // currrent selectors var envSelectors = env.selectors; if (!envSelectors) { env.selectors = envSelectors = []; } envSelectors.unshift(this.selectors); // Evaluate imports if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) { ruleset.evalImports(env); } // Store the frames around mixin definitions, // so they can be evaluated like closures when the time comes. var rsRules = ruleset.rules, rsRuleCnt = rsRules ? rsRules.length : 0; for (i = 0; i < rsRuleCnt; i++) { if (rsRules[i] instanceof tree.mixin.Definition || rsRules[i] instanceof tree.DetachedRuleset) { rsRules[i] = rsRules[i].eval(env); } } var mediaBlockCount = (env.mediaBlocks && env.mediaBlocks.length) || 0; // Evaluate mixin calls. for (i = 0; i < rsRuleCnt; i++) { if (rsRules[i] instanceof tree.mixin.Call) { /*jshint loopfunc:true */ rules = rsRules[i].eval(env).filter(function(r) { if ((r instanceof tree.Rule) && r.variable) { // do not pollute the scope if the variable is // already there. consider returning false here // but we need a way to "return" variable from mixins return !(ruleset.variable(r.name)); } return true; }); rsRules.splice.apply(rsRules, [i, 1].concat(rules)); rsRuleCnt += rules.length - 1; i += rules.length-1; ruleset.resetCache(); } else if (rsRules[i] instanceof tree.RulesetCall) { /*jshint loopfunc:true */ rules = rsRules[i].eval(env).rules.filter(function(r) { if ((r instanceof tree.Rule) && r.variable) { // do not pollute the scope at all return false; } return true; }); rsRules.splice.apply(rsRules, [i, 1].concat(rules)); rsRuleCnt += rules.length - 1; i += rules.length-1; ruleset.resetCache(); } } // Evaluate everything else for (i = 0; i < rsRules.length; i++) { rule = rsRules[i]; if (! (rule instanceof tree.mixin.Definition || rule instanceof tree.DetachedRuleset)) { rsRules[i] = rule = rule.eval ? rule.eval(env) : rule; } } // Evaluate everything else for (i = 0; i < rsRules.length; i++) { rule = rsRules[i]; // for rulesets, check if it is a css guard and can be removed if (rule instanceof tree.Ruleset && rule.selectors && rule.selectors.length === 1) { // check if it can be folded in (e.g. & where) if (rule.selectors[0].isJustParentSelector()) { rsRules.splice(i--, 1); for(var j = 0; j < rule.rules.length; j++) { subRule = rule.rules[j]; if (!(subRule instanceof tree.Rule) || !subRule.variable) { rsRules.splice(++i, 0, subRule); } } } } } // Pop the stack envFrames.shift(); envSelectors.shift(); if (env.mediaBlocks) { for (i = mediaBlockCount; i < env.mediaBlocks.length; i++) { env.mediaBlocks[i].bubbleSelectors(selectors); } } return ruleset; }, evalImports: function(env) { var rules = this.rules, i, importRules; if (!rules) { return; } for (i = 0; i < rules.length; i++) { if (rules[i] instanceof tree.Import) { importRules = rules[i].eval(env); if (importRules && importRules.length) { rules.splice.apply(rules, [i, 1].concat(importRules)); i+= importRules.length-1; } else { rules.splice(i, 1, importRules); } this.resetCache(); } } }, makeImportant: function() { return new tree.Ruleset(this.selectors, this.rules.map(function (r) { if (r.makeImportant) { return r.makeImportant(); } else { return r; } }), this.strictImports); }, matchArgs: function (args) { return !args || args.length === 0; }, // lets you call a css selector with a guard matchCondition: function (args, env) { var lastSelector = this.selectors[this.selectors.length-1]; if (!lastSelector.evaldCondition) { return false; } if (lastSelector.condition && !lastSelector.condition.eval( new(tree.evalEnv)(env, env.frames))) { return false; } return true; }, resetCache: function () { this._rulesets = null; this._variables = null; this._lookups = {}; }, variables: function () { if (!this._variables) { this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) { if (r instanceof tree.Rule && r.variable === true) { hash[r.name] = r; } return hash; }, {}); } return this._variables; }, variable: function (name) { return this.variables()[name]; }, rulesets: function () { if (!this.rules) { return null; } var _Ruleset = tree.Ruleset, _MixinDefinition = tree.mixin.Definition, filtRules = [], rules = this.rules, cnt = rules.length, i, rule; for (i = 0; i < cnt; i++) { rule = rules[i]; if ((rule instanceof _Ruleset) || (rule instanceof _MixinDefinition)) { filtRules.push(rule); } } return filtRules; }, prependRule: function (rule) { var rules = this.rules; if (rules) { rules.unshift(rule); } else { this.rules = [ rule ]; } }, find: function (selector, self) { self = self || this; var rules = [], match, key = selector.toCSS(); if (key in this._lookups) { return this._lookups[key]; } this.rulesets().forEach(function (rule) { if (rule !== self) { for (var j = 0; j < rule.selectors.length; j++) { match = selector.match(rule.selectors[j]); if (match) { if (selector.elements.length > match) { Array.prototype.push.apply(rules, rule.find( new(tree.Selector)(selector.elements.slice(match)), self)); } else { rules.push(rule); } break; } } } }); this._lookups[key] = rules; return rules; }, genCSS: function (env, output) { var i, j, ruleNodes = [], rulesetNodes = [], rulesetNodeCnt, debugInfo, // Line number debugging rule, path; env.tabLevel = (env.tabLevel || 0); if (!this.root) { env.tabLevel++; } var tabRuleStr = env.compress ? '' : Array(env.tabLevel + 1).join(" "), tabSetStr = env.compress ? '' : Array(env.tabLevel).join(" "), sep; for (i = 0; i < this.rules.length; i++) { rule = this.rules[i]; if (rule.rules || (rule instanceof tree.Media) || rule instanceof tree.Directive || (this.root && rule instanceof tree.Comment)) { rulesetNodes.push(rule); } else { ruleNodes.push(rule); } } // If this is the root node, we don't render // a selector, or {}. if (!this.root) { debugInfo = tree.debugInfo(env, this, tabSetStr); if (debugInfo) { output.add(debugInfo); output.add(tabSetStr); } var paths = this.paths, pathCnt = paths.length, pathSubCnt; sep = env.compress ? ',' : (',\n' + tabSetStr); for (i = 0; i < pathCnt; i++) { path = paths[i]; if (!(pathSubCnt = path.length)) { continue; } if (i > 0) { output.add(sep); } env.firstSelector = true; path[0].genCSS(env, output); env.firstSelector = false; for (j = 1; j < pathSubCnt; j++) { path[j].genCSS(env, output); } } output.add((env.compress ? '{' : ' {\n') + tabRuleStr); } // Compile rules and rulesets for (i = 0; i < ruleNodes.length; i++) { rule = ruleNodes[i]; // @page{ directive ends up with root elements inside it, a mix of rules and rulesets // In this instance we do not know whether it is the last property if (i + 1 === ruleNodes.length && (!this.root || rulesetNodes.length === 0 || this.firstRoot)) { env.lastRule = true; } if (rule.genCSS) { rule.genCSS(env, output); } else if (rule.value) { output.add(rule.value.toString()); } if (!env.lastRule) { output.add(env.compress ? '' : ('\n' + tabRuleStr)); } else { env.lastRule = false; } } if (!this.root) { output.add((env.compress ? '}' : '\n' + tabSetStr + '}')); env.tabLevel--; } sep = (env.compress ? "" : "\n") + (this.root ? tabRuleStr : tabSetStr); rulesetNodeCnt = rulesetNodes.length; if (rulesetNodeCnt) { if (ruleNodes.length && sep) { output.add(sep); } rulesetNodes[0].genCSS(env, output); for (i = 1; i < rulesetNodeCnt; i++) { if (sep) { output.add(sep); } rulesetNodes[i].genCSS(env, output); } } if (!output.isEmpty() && !env.compress && this.firstRoot) { output.add('\n'); } }, toCSS: tree.toCSS, markReferenced: function () { if (!this.selectors) { return; } for (var s = 0; s < this.selectors.length; s++) { this.selectors[s].markReferenced(); } }, joinSelectors: function (paths, context, selectors) { for (var s = 0; s < selectors.length; s++) { this.joinSelector(paths, context, selectors[s]); } }, joinSelector: function (paths, context, selector) { var i, j, k, hasParentSelector, newSelectors, el, sel, parentSel, newSelectorPath, afterParentJoin, newJoinedSelector, newJoinedSelectorEmpty, lastSelector, currentElements, selectorsMultiplied; for (i = 0; i < selector.elements.length; i++) { el = selector.elements[i]; if (el.value === '&') { hasParentSelector = true; } } if (!hasParentSelector) { if (context.length > 0) { for (i = 0; i < context.length; i++) { paths.push(context[i].concat(selector)); } } else { paths.push([selector]); } return; } // The paths are [[Selector]] // The first list is a list of comma seperated selectors // The inner list is a list of inheritance seperated selectors // e.g. // .a, .b { // .c { // } // } // == [[.a] [.c]] [[.b] [.c]] // // the elements from the current selector so far currentElements = []; // the current list of new selectors to add to the path. // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors // by the parents newSelectors = [[]]; for (i = 0; i < selector.elements.length; i++) { el = selector.elements[i]; // non parent reference elements just get added if (el.value !== "&") { currentElements.push(el); } else { // the new list of selectors to add selectorsMultiplied = []; // merge the current list of non parent selector elements // on to the current list of selectors to add if (currentElements.length > 0) { this.mergeElementsOnToSelectors(currentElements, newSelectors); } // loop through our current selectors for (j = 0; j < newSelectors.length; j++) { sel = newSelectors[j]; // if we don't have any parent paths, the & might be in a mixin so that it can be used // whether there are parents or not if (context.length === 0) { // the combinator used on el should now be applied to the next element instead so that // it is not lost if (sel.length > 0) { sel[0].elements = sel[0].elements.slice(0); sel[0].elements.push(new(tree.Element)(el.combinator, '', el.index, el.currentFileInfo)); } selectorsMultiplied.push(sel); } else { // and the parent selectors for (k = 0; k < context.length; k++) { parentSel = context[k]; // We need to put the current selectors // then join the last selector's elements on to the parents selectors // our new selector path newSelectorPath = []; // selectors from the parent after the join afterParentJoin = []; newJoinedSelectorEmpty = true; //construct the joined selector - if & is the first thing this will be empty, // if not newJoinedSelector will be the last set of elements in the selector if (sel.length > 0) { newSelectorPath = sel.slice(0); lastSelector = newSelectorPath.pop(); newJoinedSelector = selector.createDerived(lastSelector.elements.slice(0)); newJoinedSelectorEmpty = false; } else { newJoinedSelector = selector.createDerived([]); } //put together the parent selectors after the join if (parentSel.length > 1) { afterParentJoin = afterParentJoin.concat(parentSel.slice(1)); } if (parentSel.length > 0) { newJoinedSelectorEmpty = false; // join the elements so far with the first part of the parent newJoinedSelector.elements.push(new(tree.Element)(el.combinator, parentSel[0].elements[0].value, el.index, el.currentFileInfo)); newJoinedSelector.elements = newJoinedSelector.elements.concat(parentSel[0].elements.slice(1)); } if (!newJoinedSelectorEmpty) { // now add the joined selector newSelectorPath.push(newJoinedSelector); } // and the rest of the parent newSelectorPath = newSelectorPath.concat(afterParentJoin); // add that to our new set of selectors selectorsMultiplied.push(newSelectorPath); } } } // our new selectors has been multiplied, so reset the state newSelectors = selectorsMultiplied; currentElements = []; } } // if we have any elements left over (e.g. .a& .b == .b) // add them on to all the current selectors if (currentElements.length > 0) { this.mergeElementsOnToSelectors(currentElements, newSelectors); } for (i = 0; i < newSelectors.length; i++) { if (newSelectors[i].length > 0) { paths.push(newSelectors[i]); } } }, mergeElementsOnToSelectors: function(elements, selectors) { var i, sel; if (selectors.length === 0) { selectors.push([ new(tree.Selector)(elements) ]); return; } for (i = 0; i < selectors.length; i++) { sel = selectors[i]; // if the previous thing in sel is a parent this needs to join on to it if (sel.length > 0) { sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements)); } else { sel.push(new(tree.Selector)(elements)); } } } }; })(require('../tree')); (function (tree) { tree.Selector = function (elements, extendList, condition, index, currentFileInfo, isReferenced) { this.elements = elements; this.extendList = extendList; this.condition = condition; this.currentFileInfo = currentFileInfo || {}; this.isReferenced = isReferenced; if (!condition) { this.evaldCondition = true; } }; tree.Selector.prototype = { type: "Selector", accept: function (visitor) { if (this.elements) { this.elements = visitor.visitArray(this.elements); } if (this.extendList) { this.extendList = visitor.visitArray(this.extendList); } if (this.condition) { this.condition = visitor.visit(this.condition); } }, createDerived: function(elements, extendList, evaldCondition) { evaldCondition = (evaldCondition != null) ? evaldCondition : this.evaldCondition; var newSelector = new(tree.Selector)(elements, extendList || this.extendList, null, this.index, this.currentFileInfo, this.isReferenced); newSelector.evaldCondition = evaldCondition; newSelector.mediaEmpty = this.mediaEmpty; return newSelector; }, match: function (other) { var elements = this.elements, len = elements.length, olen, i; other.CacheElements(); olen = other._elements.length; if (olen === 0 || len < olen) { return 0; } else { for (i = 0; i < olen; i++) { if (elements[i].value !== other._elements[i]) { return 0; } } } return olen; // return number of matched elements }, CacheElements: function(){ var css = '', len, v, i; if( !this._elements ){ len = this.elements.length; for(i = 0; i < len; i++){ v = this.elements[i]; css += v.combinator.value; if( !v.value.value ){ css += v.value; continue; } if( typeof v.value.value !== "string" ){ css = ''; break; } css += v.value.value; } this._elements = css.match(/[,&#\.\w-]([\w-]|(\\.))*/g); if (this._elements) { if (this._elements[0] === "&") { this._elements.shift(); } } else { this._elements = []; } } }, isJustParentSelector: function() { return !this.mediaEmpty && this.elements.length === 1 && this.elements[0].value === '&' && (this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === ''); }, eval: function (env) { var evaldCondition = this.condition && this.condition.eval(env), elements = this.elements, extendList = this.extendList; elements = elements && elements.map(function (e) { return e.eval(env); }); extendList = extendList && extendList.map(function(extend) { return extend.eval(env); }); return this.createDerived(elements, extendList, evaldCondition); }, genCSS: function (env, output) { var i, element; if ((!env || !env.firstSelector) && this.elements[0].combinator.value === "") { output.add(' ', this.currentFileInfo, this.index); } if (!this._css) { //TODO caching? speed comparison? for(i = 0; i < this.elements.length; i++) { element = this.elements[i]; element.genCSS(env, output); } } }, toCSS: tree.toCSS, markReferenced: function () { this.isReferenced = true; }, getIsReferenced: function() { return !this.currentFileInfo.reference || this.isReferenced; }, getIsOutput: function() { return this.evaldCondition; } }; })(require('../tree')); (function (tree) { tree.UnicodeDescriptor = function (value) { this.value = value; }; tree.UnicodeDescriptor.prototype = { type: "UnicodeDescriptor", genCSS: function (env, output) { output.add(this.value); }, toCSS: tree.toCSS, eval: function () { return this; } }; })(require('../tree')); (function (tree) { tree.URL = function (val, currentFileInfo, isEvald) { this.value = val; this.currentFileInfo = currentFileInfo; this.isEvald = isEvald; }; tree.URL.prototype = { type: "Url", accept: function (visitor) { this.value = visitor.visit(this.value); }, genCSS: function (env, output) { output.add("url("); this.value.genCSS(env, output); output.add(")"); }, toCSS: tree.toCSS, eval: function (ctx) { var val = this.value.eval(ctx), rootpath; if (!this.isEvald) { // Add the base path if the URL is relative rootpath = this.currentFileInfo && this.currentFileInfo.rootpath; if (rootpath && typeof val.value === "string" && ctx.isPathRelative(val.value)) { if (!val.quote) { rootpath = rootpath.replace(/[\(\)'"\s]/g, function(match) { return "\\"+match; }); } val.value = rootpath + val.value; } val.value = ctx.normalizePath(val.value); // Add url args if enabled if (ctx.urlArgs) { if (!val.value.match(/^\s*data:/)) { var delimiter = val.value.indexOf('?') === -1 ? '?' : '&'; var urlArgs = delimiter + ctx.urlArgs; if (val.value.indexOf('#') !== -1) { val.value = val.value.replace('#', urlArgs + '#'); } else { val.value += urlArgs; } } } } return new(tree.URL)(val, this.currentFileInfo, true); } }; })(require('../tree')); (function (tree) { tree.Value = function (value) { this.value = value; }; tree.Value.prototype = { type: "Value", accept: function (visitor) { if (this.value) { this.value = visitor.visitArray(this.value); } }, eval: function (env) { if (this.value.length === 1) { return this.value[0].eval(env); } else { return new(tree.Value)(this.value.map(function (v) { return v.eval(env); })); } }, genCSS: function (env, output) { var i; for(i = 0; i < this.value.length; i++) { this.value[i].genCSS(env, output); if (i+1 < this.value.length) { output.add((env && env.compress) ? ',' : ', '); } } }, toCSS: tree.toCSS }; })(require('../tree')); (function (tree) { tree.Variable = function (name, index, currentFileInfo) { this.name = name; this.index = index; this.currentFileInfo = currentFileInfo || {}; }; tree.Variable.prototype = { type: "Variable", eval: function (env) { var variable, name = this.name; if (name.indexOf('@@') === 0) { name = '@' + new(tree.Variable)(name.slice(1)).eval(env).value; } if (this.evaluating) { throw { type: 'Name', message: "Recursive variable definition for " + name, filename: this.currentFileInfo.file, index: this.index }; } this.evaluating = true; variable = tree.find(env.frames, function (frame) { var v = frame.variable(name); if (v) { return v.value.eval(env); } }); if (variable) { this.evaluating = false; return variable; } else { throw { type: 'Name', message: "variable " + name + " is undefined", filename: this.currentFileInfo.filename, index: this.index }; } } }; })(require('../tree')); (function (tree) { var parseCopyProperties = [ 'paths', // option - unmodified - paths to search for imports on 'optimization', // option - optimization level (for the chunker) 'files', // list of files that have been imported, used for import-once 'contents', // map - filename to contents of all the files 'contentsIgnoredChars', // map - filename to lines at the begining of each file to ignore 'relativeUrls', // option - whether to adjust URL's to be relative 'rootpath', // option - rootpath to append to URL's 'strictImports', // option - 'insecure', // option - whether to allow imports from insecure ssl hosts 'dumpLineNumbers', // option - whether to dump line numbers 'compress', // option - whether to compress 'processImports', // option - whether to process imports. if false then imports will not be imported 'syncImport', // option - whether to import synchronously 'javascriptEnabled',// option - whether JavaScript is enabled. if undefined, defaults to true 'mime', // browser only - mime type for sheet import 'useFileCache', // browser only - whether to use the per file session cache 'currentFileInfo' // information about the current file - for error reporting and importing and making urls relative etc. ]; //currentFileInfo = { // 'relativeUrls' - option - whether to adjust URL's to be relative // 'filename' - full resolved filename of current file // 'rootpath' - path to append to normal URLs for this node // 'currentDirectory' - path to the current file, absolute // 'rootFilename' - filename of the base file // 'entryPath' - absolute path to the entry file // 'reference' - whether the file should not be output and only output parts that are referenced tree.parseEnv = function(options) { copyFromOriginal(options, this, parseCopyProperties); if (!this.contents) { this.contents = {}; } if (!this.contentsIgnoredChars) { this.contentsIgnoredChars = {}; } if (!this.files) { this.files = {}; } if (!this.currentFileInfo) { var filename = (options && options.filename) || "input"; var entryPath = filename.replace(/[^\/\\]*$/, ""); if (options) { options.filename = null; } this.currentFileInfo = { filename: filename, relativeUrls: this.relativeUrls, rootpath: (options && options.rootpath) || "", currentDirectory: entryPath, entryPath: entryPath, rootFilename: filename }; } }; var evalCopyProperties = [ 'silent', // whether to swallow errors and warnings 'verbose', // whether to log more activity 'compress', // whether to compress 'yuicompress', // whether to compress with the outside tool yui compressor 'ieCompat', // whether to enforce IE compatibility (IE8 data-uri) 'strictMath', // whether math has to be within parenthesis 'strictUnits', // whether units need to evaluate correctly 'cleancss', // whether to compress with clean-css 'sourceMap', // whether to output a source map 'importMultiple', // whether we are currently importing multiple copies 'urlArgs' // whether to add args into url tokens ]; tree.evalEnv = function(options, frames) { copyFromOriginal(options, this, evalCopyProperties); this.frames = frames || []; }; tree.evalEnv.prototype.inParenthesis = function () { if (!this.parensStack) { this.parensStack = []; } this.parensStack.push(true); }; tree.evalEnv.prototype.outOfParenthesis = function () { this.parensStack.pop(); }; tree.evalEnv.prototype.isMathOn = function () { return this.strictMath ? (this.parensStack && this.parensStack.length) : true; }; tree.evalEnv.prototype.isPathRelative = function (path) { return !/^(?:[a-z-]+:|\/)/.test(path); }; tree.evalEnv.prototype.normalizePath = function( path ) { var segments = path.split("/").reverse(), segment; path = []; while (segments.length !== 0 ) { segment = segments.pop(); switch( segment ) { case ".": break; case "..": if ((path.length === 0) || (path[path.length - 1] === "..")) { path.push( segment ); } else { path.pop(); } break; default: path.push( segment ); break; } } return path.join("/"); }; //todo - do the same for the toCSS env //tree.toCSSEnv = function (options) { //}; var copyFromOriginal = function(original, destination, propertiesToCopy) { if (!original) { return; } for(var i = 0; i < propertiesToCopy.length; i++) { if (original.hasOwnProperty(propertiesToCopy[i])) { destination[propertiesToCopy[i]] = original[propertiesToCopy[i]]; } } }; })(require('./tree')); (function (tree) { var _visitArgs = { visitDeeper: true }, _hasIndexed = false; function _noop(node) { return node; } function indexNodeTypes(parent, ticker) { // add .typeIndex to tree node types for lookup table var key, child; for (key in parent) { if (parent.hasOwnProperty(key)) { child = parent[key]; switch (typeof child) { case "function": // ignore bound functions directly on tree which do not have a prototype // or aren't nodes if (child.prototype && child.prototype.type) { child.prototype.typeIndex = ticker++; } break; case "object": ticker = indexNodeTypes(child, ticker); break; } } } return ticker; } tree.visitor = function(implementation) { this._implementation = implementation; this._visitFnCache = []; if (!_hasIndexed) { indexNodeTypes(tree, 1); _hasIndexed = true; } }; tree.visitor.prototype = { visit: function(node) { if (!node) { return node; } var nodeTypeIndex = node.typeIndex; if (!nodeTypeIndex) { return node; } var visitFnCache = this._visitFnCache, impl = this._implementation, aryIndx = nodeTypeIndex << 1, outAryIndex = aryIndx | 1, func = visitFnCache[aryIndx], funcOut = visitFnCache[outAryIndex], visitArgs = _visitArgs, fnName; visitArgs.visitDeeper = true; if (!func) { fnName = "visit" + node.type; func = impl[fnName] || _noop; funcOut = impl[fnName + "Out"] || _noop; visitFnCache[aryIndx] = func; visitFnCache[outAryIndex] = funcOut; } if (func !== _noop) { var newNode = func.call(impl, node, visitArgs); if (impl.isReplacing) { node = newNode; } } if (visitArgs.visitDeeper && node && node.accept) { node.accept(this); } if (funcOut != _noop) { funcOut.call(impl, node); } return node; }, visitArray: function(nodes, nonReplacing) { if (!nodes) { return nodes; } var cnt = nodes.length, i; // Non-replacing if (nonReplacing || !this._implementation.isReplacing) { for (i = 0; i < cnt; i++) { this.visit(nodes[i]); } return nodes; } // Replacing var out = []; for (i = 0; i < cnt; i++) { var evald = this.visit(nodes[i]); if (!evald.splice) { out.push(evald); } else if (evald.length) { this.flatten(evald, out); } } return out; }, flatten: function(arr, out) { if (!out) { out = []; } var cnt, i, item, nestedCnt, j, nestedItem; for (i = 0, cnt = arr.length; i < cnt; i++) { item = arr[i]; if (!item.splice) { out.push(item); continue; } for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) { nestedItem = item[j]; if (!nestedItem.splice) { out.push(nestedItem); } else if (nestedItem.length) { this.flatten(nestedItem, out); } } } return out; } }; })(require('./tree')); (function (tree) { tree.importVisitor = function(importer, finish, evalEnv, onceFileDetectionMap, recursionDetector) { this._visitor = new tree.visitor(this); this._importer = importer; this._finish = finish; this.env = evalEnv || new tree.evalEnv(); this.importCount = 0; this.onceFileDetectionMap = onceFileDetectionMap || {}; this.recursionDetector = {}; if (recursionDetector) { for(var fullFilename in recursionDetector) { if (recursionDetector.hasOwnProperty(fullFilename)) { this.recursionDetector[fullFilename] = true; } } } }; tree.importVisitor.prototype = { isReplacing: true, run: function (root) { var error; try { // process the contents this._visitor.visit(root); } catch(e) { error = e; } this.isFinished = true; if (this.importCount === 0) { this._finish(error); } }, visitImport: function (importNode, visitArgs) { var importVisitor = this, evaldImportNode, inlineCSS = importNode.options.inline; if (!importNode.css || inlineCSS) { try { evaldImportNode = importNode.evalForImport(this.env); } catch(e){ if (!e.filename) { e.index = importNode.index; e.filename = importNode.currentFileInfo.filename; } // attempt to eval properly and treat as css importNode.css = true; // if that fails, this error will be thrown importNode.error = e; } if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) { importNode = evaldImportNode; this.importCount++; var env = new tree.evalEnv(this.env, this.env.frames.slice(0)); if (importNode.options.multiple) { env.importMultiple = true; } this._importer.push(importNode.getPath(), importNode.currentFileInfo, importNode.options, function (e, root, importedAtRoot, fullPath) { if (e && !e.filename) { e.index = importNode.index; e.filename = importNode.currentFileInfo.filename; } if (!env.importMultiple) { if (importedAtRoot) { importNode.skip = true; } else { importNode.skip = function() { if (fullPath in importVisitor.onceFileDetectionMap) { return true; } importVisitor.onceFileDetectionMap[fullPath] = true; return false; }; } } var subFinish = function(e) { importVisitor.importCount--; if (importVisitor.importCount === 0 && importVisitor.isFinished) { importVisitor._finish(e); } }; if (root) { importNode.root = root; importNode.importedFilename = fullPath; var duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector; if (!inlineCSS && (env.importMultiple || !duplicateImport)) { importVisitor.recursionDetector[fullPath] = true; new(tree.importVisitor)(importVisitor._importer, subFinish, env, importVisitor.onceFileDetectionMap, importVisitor.recursionDetector) .run(root); return; } } subFinish(); }); } } visitArgs.visitDeeper = false; return importNode; }, visitRule: function (ruleNode, visitArgs) { visitArgs.visitDeeper = false; return ruleNode; }, visitDirective: function (directiveNode, visitArgs) { this.env.frames.unshift(directiveNode); return directiveNode; }, visitDirectiveOut: function (directiveNode) { this.env.frames.shift(); }, visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { this.env.frames.unshift(mixinDefinitionNode); return mixinDefinitionNode; }, visitMixinDefinitionOut: function (mixinDefinitionNode) { this.env.frames.shift(); }, visitRuleset: function (rulesetNode, visitArgs) { this.env.frames.unshift(rulesetNode); return rulesetNode; }, visitRulesetOut: function (rulesetNode) { this.env.frames.shift(); }, visitMedia: function (mediaNode, visitArgs) { this.env.frames.unshift(mediaNode.ruleset); return mediaNode; }, visitMediaOut: function (mediaNode) { this.env.frames.shift(); } }; })(require('./tree')); (function (tree) { tree.joinSelectorVisitor = function() { this.contexts = [[]]; this._visitor = new tree.visitor(this); }; tree.joinSelectorVisitor.prototype = { run: function (root) { return this._visitor.visit(root); }, visitRule: function (ruleNode, visitArgs) { visitArgs.visitDeeper = false; }, visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { visitArgs.visitDeeper = false; }, visitRuleset: function (rulesetNode, visitArgs) { var context = this.contexts[this.contexts.length - 1], paths = [], selectors; this.contexts.push(paths); if (! rulesetNode.root) { selectors = rulesetNode.selectors; if (selectors) { selectors = selectors.filter(function(selector) { return selector.getIsOutput(); }); rulesetNode.selectors = selectors.length ? selectors : (selectors = null); if (selectors) { rulesetNode.joinSelectors(paths, context, selectors); } } if (!selectors) { rulesetNode.rules = null; } rulesetNode.paths = paths; } }, visitRulesetOut: function (rulesetNode) { this.contexts.length = this.contexts.length - 1; }, visitMedia: function (mediaNode, visitArgs) { var context = this.contexts[this.contexts.length - 1]; mediaNode.rules[0].root = (context.length === 0 || context[0].multiMedia); } }; })(require('./tree')); (function (tree) { tree.toCSSVisitor = function(env) { this._visitor = new tree.visitor(this); this._env = env; }; tree.toCSSVisitor.prototype = { isReplacing: true, run: function (root) { return this._visitor.visit(root); }, visitRule: function (ruleNode, visitArgs) { if (ruleNode.variable) { return []; } return ruleNode; }, visitMixinDefinition: function (mixinNode, visitArgs) { // mixin definitions do not get eval'd - this means they keep state // so we have to clear that state here so it isn't used if toCSS is called twice mixinNode.frames = []; return []; }, visitExtend: function (extendNode, visitArgs) { return []; }, visitComment: function (commentNode, visitArgs) { if (commentNode.isSilent(this._env)) { return []; } return commentNode; }, visitMedia: function(mediaNode, visitArgs) { mediaNode.accept(this._visitor); visitArgs.visitDeeper = false; if (!mediaNode.rules.length) { return []; } return mediaNode; }, visitDirective: function(directiveNode, visitArgs) { if (directiveNode.currentFileInfo.reference && !directiveNode.isReferenced) { return []; } if (directiveNode.name === "@charset") { // Only output the debug info together with subsequent @charset definitions // a comment (or @media statement) before the actual @charset directive would // be considered illegal css as it has to be on the first line if (this.charset) { if (directiveNode.debugInfo) { var comment = new tree.Comment("/* " + directiveNode.toCSS(this._env).replace(/\n/g, "")+" */\n"); comment.debugInfo = directiveNode.debugInfo; return this._visitor.visit(comment); } return []; } this.charset = true; } return directiveNode; }, checkPropertiesInRoot: function(rules) { var ruleNode; for(var i = 0; i < rules.length; i++) { ruleNode = rules[i]; if (ruleNode instanceof tree.Rule && !ruleNode.variable) { throw { message: "properties must be inside selector blocks, they cannot be in the root.", index: ruleNode.index, filename: ruleNode.currentFileInfo ? ruleNode.currentFileInfo.filename : null}; } } }, visitRuleset: function (rulesetNode, visitArgs) { var rule, rulesets = []; if (rulesetNode.firstRoot) { this.checkPropertiesInRoot(rulesetNode.rules); } if (! rulesetNode.root) { if (rulesetNode.paths) { rulesetNode.paths = rulesetNode.paths .filter(function(p) { var i; if (p[0].elements[0].combinator.value === ' ') { p[0].elements[0].combinator = new(tree.Combinator)(''); } for(i = 0; i < p.length; i++) { if (p[i].getIsReferenced() && p[i].getIsOutput()) { return true; } } return false; }); } // Compile rules and rulesets var nodeRules = rulesetNode.rules, nodeRuleCnt = nodeRules ? nodeRules.length : 0; for (var i = 0; i < nodeRuleCnt; ) { rule = nodeRules[i]; if (rule && rule.rules) { // visit because we are moving them out from being a child rulesets.push(this._visitor.visit(rule)); nodeRules.splice(i, 1); nodeRuleCnt--; continue; } i++; } // accept the visitor to remove rules and refactor itself // then we can decide now whether we want it or not if (nodeRuleCnt > 0) { rulesetNode.accept(this._visitor); } else { rulesetNode.rules = null; } visitArgs.visitDeeper = false; nodeRules = rulesetNode.rules; if (nodeRules) { this._mergeRules(nodeRules); nodeRules = rulesetNode.rules; } if (nodeRules) { this._removeDuplicateRules(nodeRules); nodeRules = rulesetNode.rules; } // now decide whether we keep the ruleset if (nodeRules && nodeRules.length > 0 && rulesetNode.paths.length > 0) { rulesets.splice(0, 0, rulesetNode); } } else { rulesetNode.accept(this._visitor); visitArgs.visitDeeper = false; if (rulesetNode.firstRoot || (rulesetNode.rules && rulesetNode.rules.length > 0)) { rulesets.splice(0, 0, rulesetNode); } } if (rulesets.length === 1) { return rulesets[0]; } return rulesets; }, _removeDuplicateRules: function(rules) { if (!rules) { return; } // remove duplicates var ruleCache = {}, ruleList, rule, i; for(i = rules.length - 1; i >= 0 ; i--) { rule = rules[i]; if (rule instanceof tree.Rule) { if (!ruleCache[rule.name]) { ruleCache[rule.name] = rule; } else { ruleList = ruleCache[rule.name]; if (ruleList instanceof tree.Rule) { ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._env)]; } var ruleCSS = rule.toCSS(this._env); if (ruleList.indexOf(ruleCSS) !== -1) { rules.splice(i, 1); } else { ruleList.push(ruleCSS); } } } } }, _mergeRules: function (rules) { if (!rules) { return; } var groups = {}, parts, rule, key; for (var i = 0; i < rules.length; i++) { rule = rules[i]; if ((rule instanceof tree.Rule) && rule.merge) { key = [rule.name, rule.important ? "!" : ""].join(","); if (!groups[key]) { groups[key] = []; } else { rules.splice(i--, 1); } groups[key].push(rule); } } Object.keys(groups).map(function (k) { function toExpression(values) { return new (tree.Expression)(values.map(function (p) { return p.value; })); } function toValue(values) { return new (tree.Value)(values.map(function (p) { return p; })); } parts = groups[k]; if (parts.length > 1) { rule = parts[0]; var spacedGroups = []; var lastSpacedGroup = []; parts.map(function (p) { if (p.merge==="+") { if (lastSpacedGroup.length > 0) { spacedGroups.push(toExpression(lastSpacedGroup)); } lastSpacedGroup = []; } lastSpacedGroup.push(p); }); spacedGroups.push(toExpression(lastSpacedGroup)); rule.value = toValue(spacedGroups); } }); } }; })(require('./tree')); (function (tree) { /*jshint loopfunc:true */ tree.extendFinderVisitor = function() { this._visitor = new tree.visitor(this); this.contexts = []; this.allExtendsStack = [[]]; }; tree.extendFinderVisitor.prototype = { run: function (root) { root = this._visitor.visit(root); root.allExtends = this.allExtendsStack[0]; return root; }, visitRule: function (ruleNode, visitArgs) { visitArgs.visitDeeper = false; }, visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { visitArgs.visitDeeper = false; }, visitRuleset: function (rulesetNode, visitArgs) { if (rulesetNode.root) { return; } var i, j, extend, allSelectorsExtendList = [], extendList; // get &:extend(.a); rules which apply to all selectors in this ruleset var rules = rulesetNode.rules, ruleCnt = rules ? rules.length : 0; for(i = 0; i < ruleCnt; i++) { if (rulesetNode.rules[i] instanceof tree.Extend) { allSelectorsExtendList.push(rules[i]); rulesetNode.extendOnEveryPath = true; } } // now find every selector and apply the extends that apply to all extends // and the ones which apply to an individual extend var paths = rulesetNode.paths; for(i = 0; i < paths.length; i++) { var selectorPath = paths[i], selector = selectorPath[selectorPath.length - 1], selExtendList = selector.extendList; extendList = selExtendList ? selExtendList.slice(0).concat(allSelectorsExtendList) : allSelectorsExtendList; if (extendList) { extendList = extendList.map(function(allSelectorsExtend) { return allSelectorsExtend.clone(); }); } for(j = 0; j < extendList.length; j++) { this.foundExtends = true; extend = extendList[j]; extend.findSelfSelectors(selectorPath); extend.ruleset = rulesetNode; if (j === 0) { extend.firstExtendOnThisSelectorPath = true; } this.allExtendsStack[this.allExtendsStack.length-1].push(extend); } } this.contexts.push(rulesetNode.selectors); }, visitRulesetOut: function (rulesetNode) { if (!rulesetNode.root) { this.contexts.length = this.contexts.length - 1; } }, visitMedia: function (mediaNode, visitArgs) { mediaNode.allExtends = []; this.allExtendsStack.push(mediaNode.allExtends); }, visitMediaOut: function (mediaNode) { this.allExtendsStack.length = this.allExtendsStack.length - 1; }, visitDirective: function (directiveNode, visitArgs) { directiveNode.allExtends = []; this.allExtendsStack.push(directiveNode.allExtends); }, visitDirectiveOut: function (directiveNode) { this.allExtendsStack.length = this.allExtendsStack.length - 1; } }; tree.processExtendsVisitor = function() { this._visitor = new tree.visitor(this); }; tree.processExtendsVisitor.prototype = { run: function(root) { var extendFinder = new tree.extendFinderVisitor(); extendFinder.run(root); if (!extendFinder.foundExtends) { return root; } root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends)); this.allExtendsStack = [root.allExtends]; return this._visitor.visit(root); }, doExtendChaining: function (extendsList, extendsListTarget, iterationCount) { // // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering and pasting // the selector we would do normally, but we are also adding an extend with the same target selector // this means this new extend can then go and alter other extends // // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already processed if // we look at each selector at a time, as is done in visitRuleset var extendIndex, targetExtendIndex, matches, extendsToAdd = [], newSelector, extendVisitor = this, selectorPath, extend, targetExtend, newExtend; iterationCount = iterationCount || 0; //loop through comparing every extend with every target extend. // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one // and the second is the target. // the seperation into two lists allows us to process a subset of chains with a bigger set, as is the // case when processing media queries for(extendIndex = 0; extendIndex < extendsList.length; extendIndex++){ for(targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++){ extend = extendsList[extendIndex]; targetExtend = extendsListTarget[targetExtendIndex]; // look for circular references if( extend.parent_ids.indexOf( targetExtend.object_id ) >= 0 ){ continue; } // find a match in the target extends self selector (the bit before :extend) selectorPath = [targetExtend.selfSelectors[0]]; matches = extendVisitor.findMatch(extend, selectorPath); if (matches.length) { // we found a match, so for each self selector.. extend.selfSelectors.forEach(function(selfSelector) { // process the extend as usual newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector); // but now we create a new extend from it newExtend = new(tree.Extend)(targetExtend.selector, targetExtend.option, 0); newExtend.selfSelectors = newSelector; // add the extend onto the list of extends for that selector newSelector[newSelector.length-1].extendList = [newExtend]; // record that we need to add it. extendsToAdd.push(newExtend); newExtend.ruleset = targetExtend.ruleset; //remember its parents for circular references newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids); // only process the selector once.. if we have :extend(.a,.b) then multiple // extends will look at the same selector path, so when extending // we know that any others will be duplicates in terms of what is added to the css if (targetExtend.firstExtendOnThisSelectorPath) { newExtend.firstExtendOnThisSelectorPath = true; targetExtend.ruleset.paths.push(newSelector); } }); } } } if (extendsToAdd.length) { // try to detect circular references to stop a stack overflow. // may no longer be needed. this.extendChainCount++; if (iterationCount > 100) { var selectorOne = "{unable to calculate}"; var selectorTwo = "{unable to calculate}"; try { selectorOne = extendsToAdd[0].selfSelectors[0].toCSS(); selectorTwo = extendsToAdd[0].selector.toCSS(); } catch(e) {} throw {message: "extend circular reference detected. One of the circular extends is currently:"+selectorOne+":extend(" + selectorTwo+")"}; } // now process the new extends on the existing rules so that we can handle a extending b extending c ectending d extending e... return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount+1)); } else { return extendsToAdd; } }, visitRule: function (ruleNode, visitArgs) { visitArgs.visitDeeper = false; }, visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { visitArgs.visitDeeper = false; }, visitSelector: function (selectorNode, visitArgs) { visitArgs.visitDeeper = false; }, visitRuleset: function (rulesetNode, visitArgs) { if (rulesetNode.root) { return; } var matches, pathIndex, extendIndex, allExtends = this.allExtendsStack[this.allExtendsStack.length-1], selectorsToAdd = [], extendVisitor = this, selectorPath; // look at each selector path in the ruleset, find any extend matches and then copy, find and replace for(extendIndex = 0; extendIndex < allExtends.length; extendIndex++) { for(pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) { selectorPath = rulesetNode.paths[pathIndex]; // extending extends happens initially, before the main pass if (rulesetNode.extendOnEveryPath) { continue; } var extendList = selectorPath[selectorPath.length-1].extendList; if (extendList && extendList.length) { continue; } matches = this.findMatch(allExtends[extendIndex], selectorPath); if (matches.length) { allExtends[extendIndex].selfSelectors.forEach(function(selfSelector) { selectorsToAdd.push(extendVisitor.extendSelector(matches, selectorPath, selfSelector)); }); } } } rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd); }, findMatch: function (extend, haystackSelectorPath) { // // look through the haystack selector path to try and find the needle - extend.selector // returns an array of selector matches that can then be replaced // var haystackSelectorIndex, hackstackSelector, hackstackElementIndex, haystackElement, targetCombinator, i, extendVisitor = this, needleElements = extend.selector.elements, potentialMatches = [], potentialMatch, matches = []; // loop through the haystack elements for(haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) { hackstackSelector = haystackSelectorPath[haystackSelectorIndex]; for(hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) { haystackElement = hackstackSelector.elements[hackstackElementIndex]; // if we allow elements before our match we can add a potential match every time. otherwise only at the first element. if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) { potentialMatches.push({pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0, initialCombinator: haystackElement.combinator}); } for(i = 0; i < potentialMatches.length; i++) { potentialMatch = potentialMatches[i]; // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to work out // what the resulting combinator will be targetCombinator = haystackElement.combinator.value; if (targetCombinator === '' && hackstackElementIndex === 0) { targetCombinator = ' '; } // if we don't match, null our match to indicate failure if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) || (potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator)) { potentialMatch = null; } else { potentialMatch.matched++; } // if we are still valid and have finished, test whether we have elements after and whether these are allowed if (potentialMatch) { potentialMatch.finished = potentialMatch.matched === needleElements.length; if (potentialMatch.finished && (!extend.allowAfter && (hackstackElementIndex+1 < hackstackSelector.elements.length || haystackSelectorIndex+1 < haystackSelectorPath.length))) { potentialMatch = null; } } // if null we remove, if not, we are still valid, so either push as a valid match or continue if (potentialMatch) { if (potentialMatch.finished) { potentialMatch.length = needleElements.length; potentialMatch.endPathIndex = haystackSelectorIndex; potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again matches.push(potentialMatch); } } else { potentialMatches.splice(i, 1); i--; } } } } return matches; }, isElementValuesEqual: function(elementValue1, elementValue2) { if (typeof elementValue1 === "string" || typeof elementValue2 === "string") { return elementValue1 === elementValue2; } if (elementValue1 instanceof tree.Attribute) { if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) { return false; } if (!elementValue1.value || !elementValue2.value) { if (elementValue1.value || elementValue2.value) { return false; } return true; } elementValue1 = elementValue1.value.value || elementValue1.value; elementValue2 = elementValue2.value.value || elementValue2.value; return elementValue1 === elementValue2; } elementValue1 = elementValue1.value; elementValue2 = elementValue2.value; if (elementValue1 instanceof tree.Selector) { if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) { return false; } for(var i = 0; i <elementValue1.elements.length; i++) { if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) { if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) { return false; } } if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) { return false; } } return true; } return false; }, extendSelector:function (matches, selectorPath, replacementSelector) { //for a set of matches, replace each match with the replacement selector var currentSelectorPathIndex = 0, currentSelectorPathElementIndex = 0, path = [], matchIndex, selector, firstElement, match, newElements; for (matchIndex = 0; matchIndex < matches.length; matchIndex++) { match = matches[matchIndex]; selector = selectorPath[match.pathIndex]; firstElement = new tree.Element( match.initialCombinator, replacementSelector.elements[0].value, replacementSelector.elements[0].index, replacementSelector.elements[0].currentFileInfo ); if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) { path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex)); currentSelectorPathElementIndex = 0; currentSelectorPathIndex++; } newElements = selector.elements .slice(currentSelectorPathElementIndex, match.index) .concat([firstElement]) .concat(replacementSelector.elements.slice(1)); if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) { path[path.length - 1].elements = path[path.length - 1].elements.concat(newElements); } else { path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex)); path.push(new tree.Selector( newElements )); } currentSelectorPathIndex = match.endPathIndex; currentSelectorPathElementIndex = match.endPathElementIndex; if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) { currentSelectorPathElementIndex = 0; currentSelectorPathIndex++; } } if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) { path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex)); currentSelectorPathIndex++; } path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length)); return path; }, visitRulesetOut: function (rulesetNode) { }, visitMedia: function (mediaNode, visitArgs) { var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]); newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends)); this.allExtendsStack.push(newAllExtends); }, visitMediaOut: function (mediaNode) { this.allExtendsStack.length = this.allExtendsStack.length - 1; }, visitDirective: function (directiveNode, visitArgs) { var newAllExtends = directiveNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]); newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, directiveNode.allExtends)); this.allExtendsStack.push(newAllExtends); }, visitDirectiveOut: function (directiveNode) { this.allExtendsStack.length = this.allExtendsStack.length - 1; } }; })(require('./tree')); (function (tree) { tree.sourceMapOutput = function (options) { this._css = []; this._rootNode = options.rootNode; this._writeSourceMap = options.writeSourceMap; this._contentsMap = options.contentsMap; this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap; this._sourceMapFilename = options.sourceMapFilename; this._outputFilename = options.outputFilename; this._sourceMapURL = options.sourceMapURL; if (options.sourceMapBasepath) { this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/'); } this._sourceMapRootpath = options.sourceMapRootpath; this._outputSourceFiles = options.outputSourceFiles; this._sourceMapGeneratorConstructor = options.sourceMapGenerator || require("source-map").SourceMapGenerator; if (this._sourceMapRootpath && this._sourceMapRootpath.charAt(this._sourceMapRootpath.length-1) !== '/') { this._sourceMapRootpath += '/'; } this._lineNumber = 0; this._column = 0; }; tree.sourceMapOutput.prototype.normalizeFilename = function(filename) { filename = filename.replace(/\\/g, '/'); if (this._sourceMapBasepath && filename.indexOf(this._sourceMapBasepath) === 0) { filename = filename.substring(this._sourceMapBasepath.length); if (filename.charAt(0) === '\\' || filename.charAt(0) === '/') { filename = filename.substring(1); } } return (this._sourceMapRootpath || "") + filename; }; tree.sourceMapOutput.prototype.add = function(chunk, fileInfo, index, mapLines) { //ignore adding empty strings if (!chunk) { return; } var lines, sourceLines, columns, sourceColumns, i; if (fileInfo) { var inputSource = this._contentsMap[fileInfo.filename]; // remove vars/banner added to the top of the file if (this._contentsIgnoredCharsMap[fileInfo.filename]) { // adjust the index index -= this._contentsIgnoredCharsMap[fileInfo.filename]; if (index < 0) { index = 0; } // adjust the source inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]); } inputSource = inputSource.substring(0, index); sourceLines = inputSource.split("\n"); sourceColumns = sourceLines[sourceLines.length-1]; } lines = chunk.split("\n"); columns = lines[lines.length-1]; if (fileInfo) { if (!mapLines) { this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column}, original: { line: sourceLines.length, column: sourceColumns.length}, source: this.normalizeFilename(fileInfo.filename)}); } else { for(i = 0; i < lines.length; i++) { this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0}, original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0}, source: this.normalizeFilename(fileInfo.filename)}); } } } if (lines.length === 1) { this._column += columns.length; } else { this._lineNumber += lines.length - 1; this._column = columns.length; } this._css.push(chunk); }; tree.sourceMapOutput.prototype.isEmpty = function() { return this._css.length === 0; }; tree.sourceMapOutput.prototype.toCSS = function(env) { this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null }); if (this._outputSourceFiles) { for(var filename in this._contentsMap) { if (this._contentsMap.hasOwnProperty(filename)) { var source = this._contentsMap[filename]; if (this._contentsIgnoredCharsMap[filename]) { source = source.slice(this._contentsIgnoredCharsMap[filename]); } this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source); } } } this._rootNode.genCSS(env, this); if (this._css.length > 0) { var sourceMapURL, sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON()); if (this._sourceMapURL) { sourceMapURL = this._sourceMapURL; } else if (this._sourceMapFilename) { sourceMapURL = this.normalizeFilename(this._sourceMapFilename); } if (this._writeSourceMap) { this._writeSourceMap(sourceMapContent); } else { sourceMapURL = "data:application/json," + encodeURIComponent(sourceMapContent); } if (sourceMapURL) { this._css.push("/*# sourceMappingURL=" + sourceMapURL + " */"); } } return this._css.join(''); }; })(require('./tree')); // // browser.js - client-side engine // /*global less, window, document, XMLHttpRequest, location */ var isFileProtocol = /^(file|chrome(-extension)?|resource|qrc|app):/.test(location.protocol); less.env = less.env || (location.hostname == '127.0.0.1' || location.hostname == '0.0.0.0' || location.hostname == 'localhost' || (location.port && location.port.length > 0) || isFileProtocol ? 'development' : 'production'); var logLevel = { debug: 3, info: 2, errors: 1, none: 0 }; // The amount of logging in the javascript console. // 3 - Debug, information and errors // 2 - Information and errors // 1 - Errors // 0 - None // Defaults to 2 less.logLevel = typeof(less.logLevel) != 'undefined' ? less.logLevel : (less.env === 'development' ? logLevel.debug : logLevel.errors); // Load styles asynchronously (default: false) // // This is set to `false` by default, so that the body // doesn't start loading before the stylesheets are parsed. // Setting this to `true` can result in flickering. // less.async = less.async || false; less.fileAsync = less.fileAsync || false; // Interval between watch polls less.poll = less.poll || (isFileProtocol ? 1000 : 1500); //Setup user functions if (less.functions) { for(var func in less.functions) { if (less.functions.hasOwnProperty(func)) { less.tree.functions[func] = less.functions[func]; } } } var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(location.hash); if (dumpLineNumbers) { less.dumpLineNumbers = dumpLineNumbers[1]; } var typePattern = /^text\/(x-)?less$/; var cache = null; var fileCache = {}; function log(str, level) { if (typeof(console) !== 'undefined' && less.logLevel >= level) { console.log('less: ' + str); } } function extractId(href) { return href.replace(/^[a-z-]+:\/+?[^\/]+/, '' ) // Remove protocol & domain .replace(/^\//, '' ) // Remove root / .replace(/\.[a-zA-Z]+$/, '' ) // Remove simple extension .replace(/[^\.\w-]+/g, '-') // Replace illegal characters .replace(/\./g, ':'); // Replace dots with colons(for valid id) } function errorConsole(e, rootHref) { var template = '{line} {content}'; var filename = e.filename || rootHref; var errors = []; var content = (e.type || "Syntax") + "Error: " + (e.message || 'There is an error in your .less file') + " in " + filename + " "; var errorline = function (e, i, classname) { if (e.extract[i] !== undefined) { errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1)) .replace(/\{class\}/, classname) .replace(/\{content\}/, e.extract[i])); } }; if (e.extract) { errorline(e, 0, ''); errorline(e, 1, 'line'); errorline(e, 2, ''); content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':\n' + errors.join('\n'); } else if (e.stack) { content += e.stack; } log(content, logLevel.errors); } function createCSS(styles, sheet, lastModified) { // Strip the query-string var href = sheet.href || ''; // If there is no title set, use the filename, minus the extension var id = 'less:' + (sheet.title || extractId(href)); // If this has already been inserted into the DOM, we may need to replace it var oldCss = document.getElementById(id); var keepOldCss = false; // Create a new stylesheet node for insertion or (if necessary) replacement var css = document.createElement('style'); css.setAttribute('type', 'text/css'); if (sheet.media) { css.setAttribute('media', sheet.media); } css.id = id; if (css.styleSheet) { // IE try { css.styleSheet.cssText = styles; } catch (e) { throw new(Error)("Couldn't reassign styleSheet.cssText."); } } else { css.appendChild(document.createTextNode(styles)); // If new contents match contents of oldCss, don't replace oldCss keepOldCss = (oldCss !== null && oldCss.childNodes.length > 0 && css.childNodes.length > 0 && oldCss.firstChild.nodeValue === css.firstChild.nodeValue); } var head = document.getElementsByTagName('head')[0]; // If there is no oldCss, just append; otherwise, only append if we need // to replace oldCss with an updated stylesheet if (oldCss === null || keepOldCss === false) { var nextEl = sheet && sheet.nextSibling || null; if (nextEl) { nextEl.parentNode.insertBefore(css, nextEl); } else { head.appendChild(css); } } if (oldCss && keepOldCss === false) { oldCss.parentNode.removeChild(oldCss); } // Don't update the local store if the file wasn't modified if (lastModified && cache) { log('saving ' + href + ' to cache.', logLevel.info); try { cache.setItem(href, styles); cache.setItem(href + ':timestamp', lastModified); } catch(e) { //TODO - could do with adding more robust error handling log('failed to save', logLevel.errors); } } } function postProcessCSS(styles) { if (less.postProcessor && typeof less.postProcessor === 'function') { styles = less.postProcessor.call(styles, styles) || styles; } return styles; } function errorHTML(e, rootHref) { var id = 'less-error-message:' + extractId(rootHref || ""); var template = '<li><label>{line}</label><pre class="{class}">{content}</pre></li>'; var elem = document.createElement('div'), timer, content, errors = []; var filename = e.filename || rootHref; var filenameNoPath = filename.match(/([^\/]+(\?.*)?)$/)[1]; elem.id = id; elem.className = "less-error-message"; content = '<h3>' + (e.type || "Syntax") + "Error: " + (e.message || 'There is an error in your .less file') + '</h3>' + '<p>in <a href="' + filename + '">' + filenameNoPath + "</a> "; var errorline = function (e, i, classname) { if (e.extract[i] !== undefined) { errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1)) .replace(/\{class\}/, classname) .replace(/\{content\}/, e.extract[i])); } }; if (e.extract) { errorline(e, 0, ''); errorline(e, 1, 'line'); errorline(e, 2, ''); content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':</p>' + '<ul>' + errors.join('') + '</ul>'; } else if (e.stack) { content += '<br/>' + e.stack.split('\n').slice(1).join('<br/>'); } elem.innerHTML = content; // CSS for error messages createCSS([ '.less-error-message ul, .less-error-message li {', 'list-style-type: none;', 'margin-right: 15px;', 'padding: 4px 0;', 'margin: 0;', '}', '.less-error-message label {', 'font-size: 12px;', 'margin-right: 15px;', 'padding: 4px 0;', 'color: #cc7777;', '}', '.less-error-message pre {', 'color: #dd6666;', 'padding: 4px 0;', 'margin: 0;', 'display: inline-block;', '}', '.less-error-message pre.line {', 'color: #ff0000;', '}', '.less-error-message h3 {', 'font-size: 20px;', 'font-weight: bold;', 'padding: 15px 0 5px 0;', 'margin: 0;', '}', '.less-error-message a {', 'color: #10a', '}', '.less-error-message .error {', 'color: red;', 'font-weight: bold;', 'padding-bottom: 2px;', 'border-bottom: 1px dashed red;', '}' ].join('\n'), { title: 'error-message' }); elem.style.cssText = [ "font-family: Arial, sans-serif", "border: 1px solid #e00", "background-color: #eee", "border-radius: 5px", "-webkit-border-radius: 5px", "-moz-border-radius: 5px", "color: #e00", "padding: 15px", "margin-bottom: 15px" ].join(';'); if (less.env == 'development') { timer = setInterval(function () { if (document.body) { if (document.getElementById(id)) { document.body.replaceChild(elem, document.getElementById(id)); } else { document.body.insertBefore(elem, document.body.firstChild); } clearInterval(timer); } }, 10); } } function error(e, rootHref) { if (!less.errorReporting || less.errorReporting === "html") { errorHTML(e, rootHref); } else if (less.errorReporting === "console") { errorConsole(e, rootHref); } else if (typeof less.errorReporting === 'function') { less.errorReporting("add", e, rootHref); } } function removeErrorHTML(path) { var node = document.getElementById('less-error-message:' + extractId(path)); if (node) { node.parentNode.removeChild(node); } } function removeErrorConsole(path) { //no action } function removeError(path) { if (!less.errorReporting || less.errorReporting === "html") { removeErrorHTML(path); } else if (less.errorReporting === "console") { removeErrorConsole(path); } else if (typeof less.errorReporting === 'function') { less.errorReporting("remove", path); } } function loadStyles(modifyVars) { var styles = document.getElementsByTagName('style'), style; for (var i = 0; i < styles.length; i++) { style = styles[i]; if (style.type.match(typePattern)) { var env = new less.tree.parseEnv(less), lessText = style.innerHTML || ''; env.filename = document.location.href.replace(/#.*$/, ''); if (modifyVars || less.globalVars) { env.useFileCache = true; } /*jshint loopfunc:true */ // use closure to store current value of i var callback = (function(style) { return function (e, cssAST) { if (e) { return error(e, "inline"); } var css = cssAST.toCSS(less); style.type = 'text/css'; if (style.styleSheet) { style.styleSheet.cssText = css; } else { style.innerHTML = css; } }; })(style); new(less.Parser)(env).parse(lessText, callback, {globalVars: less.globalVars, modifyVars: modifyVars}); } } } function extractUrlParts(url, baseUrl) { // urlParts[1] = protocol&hostname || / // urlParts[2] = / if path relative to host base // urlParts[3] = directories // urlParts[4] = filename // urlParts[5] = parameters var urlPartsRegex = /^((?:[a-z-]+:)?\/+?(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i, urlParts = url.match(urlPartsRegex), returner = {}, directories = [], i, baseUrlParts; if (!urlParts) { throw new Error("Could not parse sheet href - '"+url+"'"); } // Stylesheets in IE don't always return the full path if (!urlParts[1] || urlParts[2]) { baseUrlParts = baseUrl.match(urlPartsRegex); if (!baseUrlParts) { throw new Error("Could not parse page url - '"+baseUrl+"'"); } urlParts[1] = urlParts[1] || baseUrlParts[1] || ""; if (!urlParts[2]) { urlParts[3] = baseUrlParts[3] + urlParts[3]; } } if (urlParts[3]) { directories = urlParts[3].replace(/\\/g, "/").split("/"); // extract out . before .. so .. doesn't absorb a non-directory for(i = 0; i < directories.length; i++) { if (directories[i] === ".") { directories.splice(i, 1); i -= 1; } } for(i = 0; i < directories.length; i++) { if (directories[i] === ".." && i > 0) { directories.splice(i-1, 2); i -= 2; } } } returner.hostPart = urlParts[1]; returner.directories = directories; returner.path = urlParts[1] + directories.join("/"); returner.fileUrl = returner.path + (urlParts[4] || ""); returner.url = returner.fileUrl + (urlParts[5] || ""); return returner; } function pathDiff(url, baseUrl) { // diff between two paths to create a relative path var urlParts = extractUrlParts(url), baseUrlParts = extractUrlParts(baseUrl), i, max, urlDirectories, baseUrlDirectories, diff = ""; if (urlParts.hostPart !== baseUrlParts.hostPart) { return ""; } max = Math.max(baseUrlParts.directories.length, urlParts.directories.length); for(i = 0; i < max; i++) { if (baseUrlParts.directories[i] !== urlParts.directories[i]) { break; } } baseUrlDirectories = baseUrlParts.directories.slice(i); urlDirectories = urlParts.directories.slice(i); for(i = 0; i < baseUrlDirectories.length-1; i++) { diff += "../"; } for(i = 0; i < urlDirectories.length-1; i++) { diff += urlDirectories[i] + "/"; } return diff; } function getXMLHttpRequest() { if (window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject)) { return new XMLHttpRequest(); } else { try { /*global ActiveXObject */ return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { log("browser doesn't support AJAX.", logLevel.errors); return null; } } } function doXHR(url, type, callback, errback) { var xhr = getXMLHttpRequest(); var async = isFileProtocol ? less.fileAsync : less.async; if (typeof(xhr.overrideMimeType) === 'function') { xhr.overrideMimeType('text/css'); } log("XHR: Getting '" + url + "'", logLevel.debug); xhr.open('GET', url+"?_nocache="+Math.random(), async); xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5'); xhr.send(null); function handleResponse(xhr, callback, errback) { if (xhr.status >= 200 && xhr.status < 300) { callback(xhr.responseText, xhr.getResponseHeader("Last-Modified")); } else if (typeof(errback) === 'function') { errback(xhr.status, url); } } if (isFileProtocol && !less.fileAsync) { if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) { callback(xhr.responseText); } else { errback(xhr.status, url); } } else if (async) { xhr.onreadystatechange = function () { if (xhr.readyState == 4) { handleResponse(xhr, callback, errback); } }; } else { handleResponse(xhr, callback, errback); } } function loadFile(originalHref, currentFileInfo, callback, env, modifyVars) { if (currentFileInfo && currentFileInfo.currentDirectory && !/^([a-z-]+:)?\//.test(originalHref)) { originalHref = currentFileInfo.currentDirectory + originalHref; } // sheet may be set to the stylesheet for the initial load or a collection of properties including // some env variables for imports var hrefParts = extractUrlParts(originalHref, window.location.href); var href = hrefParts.url; var newFileInfo = { currentDirectory: hrefParts.path, filename: href }; if (currentFileInfo) { newFileInfo.entryPath = currentFileInfo.entryPath; newFileInfo.rootpath = currentFileInfo.rootpath; newFileInfo.rootFilename = currentFileInfo.rootFilename; newFileInfo.relativeUrls = currentFileInfo.relativeUrls; } else { newFileInfo.entryPath = hrefParts.path; newFileInfo.rootpath = less.rootpath || hrefParts.path; newFileInfo.rootFilename = href; newFileInfo.relativeUrls = env.relativeUrls; } if (newFileInfo.relativeUrls) { if (env.rootpath) { newFileInfo.rootpath = extractUrlParts(env.rootpath + pathDiff(hrefParts.path, newFileInfo.entryPath)).path; } else { newFileInfo.rootpath = hrefParts.path; } } if (env.useFileCache && fileCache[href]) { try { var lessText = fileCache[href]; callback(null, lessText, href, newFileInfo, { lastModified: new Date() }); } catch (e) { callback(e, null, href); } return; } doXHR(href, env.mime, function (data, lastModified) { // per file cache fileCache[href] = data; // Use remote copy (re-parse) try { callback(null, data, href, newFileInfo, { lastModified: lastModified }); } catch (e) { callback(e, null, href); } }, function (status, url) { callback({ type: 'File', message: "'" + url + "' wasn't found (" + status + ")" }, null, href); }); } function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) { var env = new less.tree.parseEnv(less); env.mime = sheet.type; if (modifyVars || less.globalVars) { env.useFileCache = true; } loadFile(sheet.href, null, function(e, data, path, newFileInfo, webInfo) { if (webInfo) { webInfo.remaining = remaining; var css = cache && cache.getItem(path), timestamp = cache && cache.getItem(path + ':timestamp'); if (!reload && timestamp && webInfo.lastModified && (new(Date)(webInfo.lastModified).valueOf() === new(Date)(timestamp).valueOf())) { // Use local copy createCSS(css, sheet); webInfo.local = true; callback(null, null, data, sheet, webInfo, path); return; } } //TODO add tests around how this behaves when reloading removeError(path); if (data) { env.currentFileInfo = newFileInfo; new(less.Parser)(env).parse(data, function (e, root) { if (e) { return callback(e, null, null, sheet); } try { callback(e, root, data, sheet, webInfo, path); } catch (e) { callback(e, null, null, sheet); } }, {modifyVars: modifyVars, globalVars: less.globalVars}); } else { callback(e, null, null, sheet, webInfo, path); } }, env, modifyVars); } function loadStyleSheets(callback, reload, modifyVars) { for (var i = 0; i < less.sheets.length; i++) { loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1), modifyVars); } } function initRunningMode(){ if (less.env === 'development') { less.optimization = 0; less.watchTimer = setInterval(function () { if (less.watchMode) { loadStyleSheets(function (e, root, _, sheet, env) { if (e) { error(e, sheet.href); } else if (root) { var styles = root.toCSS(less); styles = postProcessCSS(styles); createCSS(styles, sheet, env.lastModified); } }); } }, less.poll); } else { less.optimization = 3; } } // // Watch mode // less.watch = function () { if (!less.watchMode ){ less.env = 'development'; initRunningMode(); } this.watchMode = true; return true; }; less.unwatch = function () {clearInterval(less.watchTimer); this.watchMode = false; return false; }; if (/!watch/.test(location.hash)) { less.watch(); } if (less.env != 'development') { try { cache = (typeof(window.localStorage) === 'undefined') ? null : window.localStorage; } catch (_) {} } // // Get all <link> tags with the 'rel' attribute set to "stylesheet/less" // var links = document.getElementsByTagName('link'); less.sheets = []; for (var i = 0; i < links.length; i++) { if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) && (links[i].type.match(typePattern)))) { less.sheets.push(links[i]); } } // // With this function, it's possible to alter variables and re-render // CSS without reloading less-files // less.modifyVars = function(record) { less.refresh(false, record); }; less.refresh = function (reload, modifyVars) { var startTime, endTime; startTime = endTime = new Date(); loadStyleSheets(function (e, root, _, sheet, env) { if (e) { return error(e, sheet.href); } if (env.local) { log("loading " + sheet.href + " from cache.", logLevel.info); } else { log("parsed " + sheet.href + " successfully.", logLevel.debug); var styles = root.toCSS(less); styles = postProcessCSS(styles); createCSS(styles, sheet, env.lastModified); } log("css for " + sheet.href + " generated in " + (new Date() - endTime) + 'ms', logLevel.info); if (env.remaining === 0) { log("less has finished. css generated in " + (new Date() - startTime) + 'ms', logLevel.info); } endTime = new Date(); }, reload, modifyVars); loadStyles(modifyVars); }; less.refreshStyles = loadStyles; less.Parser.fileLoader = loadFile; less.refresh(less.env === 'development'); // amd.js // // Define Less as an AMD module. if (typeof define === "function" && define.amd) { define(function () { return less; } ); } })(window);
lnc2014/sxg
ace-v1.3/build/lib/less.js
JavaScript
apache-2.0
280,205
#!/usr/bin/env bash # start ssh to be tested "running" by netstat service ssh start # run the tests - every test should result in "passed" cd /app && \ java -jar /app/dda-serverspec-standalone.jar -v /app/certificate-file.edn && \ echo "----------" && \ java -jar /app/dda-serverspec-standalone.jar -v /app/command.edn && \ echo "----------" && \ java -jar /app/dda-serverspec-standalone.jar -v /app/file.edn && \ echo "----------" && \ java -jar /app/dda-serverspec-standalone.jar -v /app/package.edn && \ echo "----------" && \ java -jar /app/dda-serverspec-standalone.jar --install-dependencies /app/http-cert.edn && \ java -jar /app/dda-serverspec-standalone.jar -v /app/http-cert.edn && \ echo "----------" && \ java -jar /app/dda-serverspec-standalone.jar --install-dependencies /app/netstat.edn && \ java -jar /app/dda-serverspec-standalone.jar -v /app/netstat.edn && \ echo "----------" && \ java -jar /app/dda-serverspec-standalone.jar --install-dependencies /app/netcat.edn && \ java -jar /app/dda-serverspec-standalone.jar -v /app/netcat.edn && \ echo "----------" && \ java -jar /app/dda-serverspec-standalone.jar --install-dependencies /app/iproute.edn && \ java -jar /app/dda-serverspec-standalone.jar -v /app/iproute.edn -v
DomainDrivenArchitecture/dda-serverspec-crate
integration/resources/test_it.sh
Shell
apache-2.0
1,241
package org.devspark.aws.tools; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.devspark.aws.lambdasupport.endpoint.annotations.apigateway.ApiGateway; import org.devspark.aws.lambdasupport.endpoint.annotations.apigateway.Resource; import org.devspark.aws.lambdasupport.endpoint.annotations.apigateway.ResourceMethod; import org.devspark.aws.tools.model.resources.EndpointResource; import org.devspark.aws.tools.model.resources.EndpointResourceMethod; import org.devspark.aws.tools.model.resources.EndpointResourceMethodParameter; import org.devspark.aws.tools.model.resources.EndpointResponse; import org.devspark.aws.tools.model.resources.EndpointResponseHeader; import org.devspark.aws.tools.model.resources.EndpointResponseSchema; import org.devspark.aws.tools.swagger.SwaggerFileWriter; import org.devspark.aws.tools.swagger.VelocitySwaggerFileWriter; import org.reflections.ReflectionUtils; import org.reflections.Reflections; import org.reflections.scanners.SubTypesScanner; import org.reflections.scanners.TypeAnnotationsScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; @Mojo(name = "apigateway-deployer") public class AWSAPIGatewayDeployer extends AbstractMojo { @Parameter(property = "base-package") private String basePackage; private SwaggerFileWriter fileWriter = new VelocitySwaggerFileWriter(); @Override public void execute() throws MojoExecutionException, MojoFailureException { Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage(basePackage)).setScanners( new SubTypesScanner(), new TypeAnnotationsScanner())); Set<Class<?>> resources = reflections .getTypesAnnotatedWith(Resource.class); Set<Class<?>> apis = reflections .getTypesAnnotatedWith(ApiGateway.class); Map<String, EndpointResource> endpointResources = getEndpointResources(resources); String apiName = getApiName(apis); fileWriter.createSwaggerFile(new ArrayList<EndpointResource>(endpointResources.values()), apiName); } private String getApiName(Set<Class<?>> apis) { if (apis.size() != 1) { getLog().warn("Invalid number of @ApiGateway found."); } return apis.iterator().next().getAnnotationsByType(ApiGateway.class)[0].name(); } @SuppressWarnings("unchecked") private Map<String, EndpointResource> getEndpointResources(Set<Class<?>> resources) { Map<String, EndpointResource> endpointResources = new HashMap<String, EndpointResource>(); for (Class<?> type : resources) { Set<Method> resourceMethods = ReflectionUtils.getAllMethods(type, ReflectionUtils.withAnnotation(ResourceMethod.class)); if (resourceMethods.isEmpty()) { getLog().warn( "No methods annotated with @Resource found in type: " + type.getName()); continue; } for (Method method : resourceMethods) { Resource methodResource = method.getAnnotation(Resource.class); String resourceName = type.getAnnotationsByType(Resource.class)[0].name(); if(methodResource != null) { resourceName = resourceName + "/" + methodResource.name(); } EndpointResourceMethod endpointMethod = createMethodResource(method, resourceName); EndpointResource endpointResource = endpointResources.get(resourceName); if (endpointResource == null) { endpointResource = new EndpointResource(); endpointResource.setName(resourceName); endpointResource.setMethods(new ArrayList<EndpointResourceMethod>()); endpointResources.put(resourceName, endpointResource); } endpointResource.getMethods().add(endpointMethod); } } return endpointResources; } private EndpointResourceMethod createMethodResource(Method method, String resourceName) { EndpointResourceMethod endpointMethod = new EndpointResourceMethod(); ResourceMethod resourceMethod = method.getAnnotation(ResourceMethod.class); endpointMethod.setVerb(resourceMethod.httpMethod().name()); endpointMethod.setParameters(getParameters(resourceName)); endpointMethod.setProduces(Arrays.asList("application/json")); endpointMethod.setResponses(getMethodResponses()); return endpointMethod; } //TODO: Replace mocked list with the generation of the responses of the method. private List<EndpointResponse> getMethodResponses() { List<EndpointResponse> responses = new ArrayList<EndpointResponse>(); EndpointResponse sucessfulResponse = new EndpointResponse(); sucessfulResponse.setHttpStatus("200"); sucessfulResponse.setDescription("200 response"); sucessfulResponse.setHeaders(new EndpointResponseHeader()); EndpointResponseSchema schema = new EndpointResponseSchema(); schema.setRef("#/definitions/Empty"); sucessfulResponse.setSchema(schema); return responses; } private List<EndpointResourceMethodParameter> getParameters(String resourceName) { String pattern = "\\{[a-zA-A]*\\}"; Pattern r = Pattern.compile(pattern); List<EndpointResourceMethodParameter> parameters = new ArrayList<EndpointResourceMethodParameter>(); Matcher m = r.matcher(resourceName); while(m.find()){ EndpointResourceMethodParameter parameter = new EndpointResourceMethodParameter(); parameter.setName(m.group(0).replaceAll("\\{*\\}*", "")); //TODO: Review how to populate the parameter metadata. parameter.setRequired(true); parameter.setType("string"); parameter.setIn("path"); parameters.add(parameter); } return parameters; } }
devspark-com/aws-lambda-deploy
src/main/java/org/devspark/aws/tools/AWSAPIGatewayDeployer.java
Java
apache-2.0
5,913
<?php //-------------------------------- //db_mysqli, db_pdo $var->db_driver = 'db_mysqli'; //$var->db_driver = 'db_pdo'; //for pdo: mysql, sqlite, ... //$var->db_engine = 'mysql'; $var->db_host = 'localhost'; $var->db_database = 'ada'; $var->db_user = 'ad'; $var->db_pass = 'dddd'; //$var->db_database = 'kargosha'; //$var->db_user = 'root'; //$var->db_pass = ''; $var->db_perfix = 'x_'; $var->db_set_utf8 = true; //-------------------------------- $var->session_unique = 'kargosha'; //-------------------------------- $var->auto_lang = false; $var->multi_domain = false; //------------ News letter { -------------------- $var->use_mailer_lite_api = true; $var->mailer_lite_api_key = ''; $var->mailer_lite_group_id = ''; //------------ } News letter -------------------- //-------------------------------- $var->cache_page = false; $var->cache_image = false; $var->cache_page_time = 1*24*60*60; // 1 day = 1 days * 24 hours * 60 mins * 60 secs $var->cache_image_time = 1*24*60*60; // 1 day = 1 days * 24 hours * 60 mins * 60 secs $var->cookie_expire_time = 30*24*60*60; // 30 day = 30 days * 24 hours * 60 mins * 60 secs //-------------------------------- $var->hit_counter = true; $var->hit_online = true; $var->hit_referers = false; $var->hit_requests = false; //-------------------------------- //--------------------------------bank: Beh Pardakht - Bank e Mellat $var->bank_mellat_terminal = 0; $var->bank_mellat_user = ''; $var->bank_mellat_pass = ''; $var->callBackUrl = "http://site.com/?a=transaction.callBack"; $var->bank_startpayUrl = "https://bpm.shaparak.ir/pgwchannel/startpay.mellat"; $var->bank_nusoap_client = "https://bpm.shaparak.ir/pgwchannel/services/pgw?wsdl"; $var->bank_namespace = "http://interfaces.core.sw.bps.com/"; //-------------------------------- $var->zarinpal_merchant_code = "AAAA-BBBB-CCCC-DDDD"; $var->zarinpal_callBackUrl = "http://site.com/?a=transaction_zarinpal.callBack"; //-------------------------------- ?>
ariax/phpcms
core/config.php
PHP
apache-2.0
1,959
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.actions; import com.intellij.CommonBundle; import com.intellij.history.LocalHistory; import com.intellij.history.LocalHistoryAction; import com.intellij.ide.IdeBundle; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.application.WriteActionAware; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.UndoConfirmationPolicy; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.NlsContexts; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.SmartPointerManager; import com.intellij.psi.SmartPsiElementPointer; import com.intellij.util.ThrowableRunnable; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; /** * @author peter */ public abstract class ElementCreator implements WriteActionAware { private static final Logger LOG = Logger.getInstance(ElementCreator.class); private final Project myProject; private final @NlsContexts.DialogTitle String myErrorTitle; protected ElementCreator(Project project, @NotNull @NlsContexts.DialogTitle String errorTitle) { myProject = project; myErrorTitle = errorTitle; } protected abstract PsiElement @NotNull [] create(@NotNull String newName) throws Exception; @NlsContexts.Command @NotNull protected abstract String getActionName(@NotNull String newName); public @NotNull PsiElement @NotNull [] tryCreate(@NotNull final String inputString) { if (inputString.isEmpty()) { Messages.showMessageDialog(myProject, IdeBundle.message("error.name.should.be.specified"), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); return PsiElement.EMPTY_ARRAY; } Ref<List<SmartPsiElementPointer<?>>> createdElements = Ref.create(); Exception exception = executeCommand(getActionName(inputString), () -> { PsiElement[] psiElements = create(inputString); SmartPointerManager manager = SmartPointerManager.getInstance(myProject); createdElements.set(ContainerUtil.map(psiElements, manager::createSmartPsiElementPointer)); }); if (exception != null) { handleException(exception); return PsiElement.EMPTY_ARRAY; } return ContainerUtil.mapNotNull(createdElements.get(), SmartPsiElementPointer::getElement).toArray(PsiElement.EMPTY_ARRAY); } @Nullable private Exception executeCommand(@NotNull @NlsContexts.Command String commandName, @NotNull ThrowableRunnable<? extends Exception> invokeCreate) { final Exception[] exception = new Exception[1]; CommandProcessor.getInstance().executeCommand(myProject, () -> { LocalHistoryAction action = LocalHistory.getInstance().startAction(commandName); try { if (startInWriteAction()) { WriteAction.run(invokeCreate); } else { invokeCreate.run(); } } catch (Exception ex) { exception[0] = ex; } finally { action.finish(); } }, commandName, null, UndoConfirmationPolicy.REQUEST_CONFIRMATION); return exception[0]; } private void handleException(Exception t) { LOG.info(t); String errorMessage = getErrorMessage(t); Messages.showMessageDialog(myProject, errorMessage, myErrorTitle, Messages.getErrorIcon()); } public static @NlsContexts.DialogMessage String getErrorMessage(Throwable t) { String errorMessage = CreateElementActionBase.filterMessage(t.getMessage()); if (StringUtil.isEmpty(errorMessage)) { errorMessage = t.toString(); } return errorMessage; } }
jwren/intellij-community
platform/lang-api/src/com/intellij/ide/actions/ElementCreator.java
Java
apache-2.0
4,462
import tempfile from git import InvalidGitRepositoryError try: from unittest2 import TestCase from mock import patch, Mock except ImportError: from unittest import TestCase from mock import patch, Mock import textwrap from datetime import datetime from botocore.exceptions import ClientError from dateutil.tz import tzutc from cfn_sphere import util, CloudFormationStack from cfn_sphere.exceptions import CfnSphereException, CfnSphereBotoError from cfn_sphere.template import CloudFormationTemplate class UtilTests(TestCase): def test_convert_yaml_to_json_string_returns_valid_json_string(self): data = textwrap.dedent(""" foo: foo: baa """) self.assertEqual('{\n "foo": {\n "foo": "baa"\n }\n}', util.convert_yaml_to_json_string(data)) def test_convert_yaml_to_json_string_returns_valid_json_string_on_empty_string_input(self): data = "" self.assertEqual('{}', util.convert_yaml_to_json_string(data)) def test_convert_json_to_yaml_string_returns_valid_yaml_string(self): data = textwrap.dedent(""" { "foo": { "foo": "baa" } } """) self.assertEqual('foo:\n foo: baa\n', util.convert_json_to_yaml_string(data)) def test_convert_json_to_yaml_string_returns_empty_string_on_empty_json_input(self): data = {} self.assertEqual('', util.convert_json_to_yaml_string(data)) @patch("cfn_sphere.util.urllib2.urlopen") def test_get_cfn_api_server_time_returns_gmt_datetime(self, urlopen_mock): urlopen_mock.return_value.info.return_value.get.return_value = "Mon, 21 Sep 2015 17:17:26 GMT" expected_timestamp = datetime(year=2015, month=9, day=21, hour=17, minute=17, second=26, tzinfo=tzutc()) self.assertEqual(expected_timestamp, util.get_cfn_api_server_time()) @patch("cfn_sphere.util.urllib2.urlopen") def test_get_cfn_api_server_time_raises_exception_on_empty_date_header(self, urlopen_mock): urlopen_mock.return_value.info.return_value.get.return_value = "" with self.assertRaises(CfnSphereException): util.get_cfn_api_server_time() def test_with_boto_retry_retries_method_call_for_throttling_exception(self): count_func = Mock() @util.with_boto_retry(max_retries=1, pause_time_multiplier=1) def my_retried_method(count_func): count_func() exception = CfnSphereBotoError( ClientError(error_response={"Error": {"Code": "Throttling", "Message": "Rate exceeded"}}, operation_name="DescribeStacks")) raise exception with self.assertRaises(CfnSphereBotoError): my_retried_method(count_func) self.assertEqual(2, count_func.call_count) def test_with_boto_retry_does_not_retry_for_simple_exception(self): count_func = Mock() @util.with_boto_retry(max_retries=1, pause_time_multiplier=1) def my_retried_method(count_func): count_func() raise Exception with self.assertRaises(Exception): my_retried_method(count_func) self.assertEqual(1, count_func.call_count) def test_with_boto_retry_does_not_retry_for_another_boto_client_error(self): count_func = Mock() @util.with_boto_retry(max_retries=1, pause_time_multiplier=1) def my_retried_method(count_func): count_func() exception = ClientError(error_response={"Error": {"Code": "Another Error", "Message": "Foo"}}, operation_name="DescribeStacks") raise exception with self.assertRaises(ClientError): my_retried_method(count_func) self.assertEqual(1, count_func.call_count) def test_with_boto_retry_does_not_retry_without_exception(self): count_func = Mock() @util.with_boto_retry(max_retries=1, pause_time_multiplier=1) def my_retried_method(count_func): count_func() return "foo" self.assertEqual("foo", my_retried_method(count_func)) self.assertEqual(1, count_func.call_count) def test_get_pretty_parameters_string(self): template_body = { 'Parameters': { 'myParameter1': { 'Type': 'String', 'NoEcho': True }, 'myParameter2': { 'Type': 'String' }, 'myParameter3': { 'Type': 'Number', 'NoEcho': 'true' }, 'myParameter4': { 'Type': 'Number', 'NoEcho': 'false' }, 'myParameter5': { 'Type': 'Number', 'NoEcho': False } } } parameters = { 'myParameter1': 'super-secret', 'myParameter2': 'not-that-secret', 'myParameter3': 'also-super-secret', 'myParameter4': 'could-be-public', 'myParameter5': 'also-ok' } template = CloudFormationTemplate(template_body, 'just-another-template') stack = CloudFormationStack(template, parameters, 'just-another-stack', 'eu-west-1') expected_string = """+--------------+-----------------+ | Parameter | Value | +--------------+-----------------+ | myParameter1 | *** | | myParameter2 | not-that-secret | | myParameter3 | *** | | myParameter4 | could-be-public | | myParameter5 | also-ok | +--------------+-----------------+""" self.assertEqual(expected_string, util.get_pretty_parameters_string(stack)) def test_get_pretty_stack_outputs_returns_proper_table(self): outputs = [ { 'OutputKey': 'key1', 'OutputValue': 'value1', 'Description': 'desc1' }, { 'OutputKey': 'key2', 'OutputValue': 'value2', 'Description': 'desc2' }, { 'OutputKey': 'key3', 'OutputValue': 'value3', 'Description': 'desc3' } ] expected = """+--------+--------+ | Output | Value | +--------+--------+ | key1 | value1 | | key2 | value2 | | key3 | value3 | +--------+--------+""" result = util.get_pretty_stack_outputs(outputs) self.assertEqual(expected, result) def test_strip_string_strips_string(self): s = "sfsdklgashgslkadghkafhgaknkbndkjfbnwurtqwhgsdnkshGLSAKGKLDJFHGSKDLGFLDFGKSDFLGKHAsdjdghskjdhsdcxbvwerA323" result = util.strip_string(s) self.assertEqual( "sfsdklgashgslkadghkafhgaknkbndkjfbnwurtqwhgsdnkshGLSAKGKLDJFHGSKDLGFLDFGKSDFLGKHAsdjdghskjdhsdcxbvwe...", result) def test_strip_string_doesnt_strip_short_strings(self): s = "my-short-string" result = util.strip_string(s) self.assertEqual("my-short-string...", result) @patch("cfn_sphere.util.Repo") def test_get_git_repository_remote_url_returns_none_if_no_repository_present(self, repo_mock): repo_mock.side_effect = InvalidGitRepositoryError self.assertEqual(None, util.get_git_repository_remote_url(tempfile.mkdtemp())) @patch("cfn_sphere.util.Repo") def test_get_git_repository_remote_url_returns_repo_url(self, repo_mock): url = "http://config.repo.git" repo_mock.return_value.remotes.origin.url = url self.assertEqual(url, util.get_git_repository_remote_url(tempfile.mkdtemp())) @patch("cfn_sphere.util.Repo") def test_get_git_repository_remote_url_returns_repo_url_from_parent_dir(self, repo_mock): url = "http://config.repo.git" repo_object_mock = Mock() repo_object_mock.remotes.origin.url = url repo_mock.side_effect = [InvalidGitRepositoryError, repo_object_mock] self.assertEqual(url, util.get_git_repository_remote_url(tempfile.mkdtemp())) def test_get_git_repository_remote_url_returns_none_for_none_working_dir(self): self.assertEqual(None, util.get_git_repository_remote_url(None)) def test_get_git_repository_remote_url_returns_none_for_empty_string_working_dir(self): self.assertEqual(None, util.get_git_repository_remote_url("")) def test_kv_list_to_dict_returns_empty_dict_for_empty_list(self): result = util.kv_list_to_dict([]) self.assertEqual({}, result) def test_kv_list_to_dict(self): result = util.kv_list_to_dict(["k1=v1", "k2=v2"]) self.assertEqual({"k1": "v1", "k2": "v2"}, result) def test_kv_list_to_dict_raises_exception_on_syntax_error(self): with self.assertRaises(CfnSphereException): util.kv_list_to_dict(["k1=v1", "k2:v2"])
marco-hoyer/cfn-sphere
src/unittest/python/util_tests.py
Python
apache-2.0
8,933
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Basic tests for TF-TensorRT integration.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.compiler.tensorrt.test import tf_trt_integration_test_base as trt_test from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.platform import test class ReshapeTest(trt_test.TfTrtIntegrationTestBase): def GraphFn(self, inp): outputs = [] # Here we test two types of reshapes, one changes the batch dimension and # the other does not. Note that we're not able to test reshaping to # scalar, since TRT requires input tensor to be of rank at least 2, so a # reshape with scalar input will be filtered out of the segment before # conversion. # # These reshapes happen at batch dimension, thus conversion should fail. for shape in [[2, 50, 24, 24, 2], [-1, 50, 24, 24, 2], [2, 50, -1, 24, 2]]: incompatible_reshape = array_ops.reshape(inp, shape) reshape_back = array_ops.reshape(incompatible_reshape, [-1, 24, 24, 2]) outputs.append(self.trt_incompatible_op(reshape_back)) # Add another block with many reshapes that don't change the batch # dimension. compatible_reshape = array_ops.reshape( inp, [-1, 24 * 24, 2], name="reshape-0") compatible_reshape = array_ops.reshape( compatible_reshape, [100, 24, -1], name="reshape-1") compatible_reshape = array_ops.reshape( compatible_reshape, [100, 24 * 2, 24], name="reshape-2") compatible_reshape = array_ops.reshape( compatible_reshape, [-1, 24, 24 * 2], name="reshape-3") compatible_reshape = array_ops.reshape( compatible_reshape, [-1, 6, 4, 24, 2], name="reshape-4") compatible_reshape = array_ops.reshape( compatible_reshape, [-1, 6, 4, 6, 4, 2, 1], name="reshape-5") compatible_reshape = array_ops.reshape( compatible_reshape, [-1, 24, 24, 2], name="reshape-6") outputs.append(self.trt_incompatible_op(compatible_reshape)) return math_ops.add_n(outputs, name="output_0") def GetParams(self): return self.BuildParams(self.GraphFn, dtypes.float32, [[100, 24, 24, 2]], [[100, 24, 24, 2]]) def ExpectedEnginesToBuild(self, run_params): """Return the expected engines to build.""" return { "TRTEngineOp_0": ["reshape-%d" % i for i in range(7)] + ["reshape-%d/shape" % i for i in range(7)] } def ShouldRunTest(self, run_params): """Whether to run the test.""" return (not trt_test.IsQuantizationMode(run_params.precision_mode) and not run_params.dynamic_engine) class TransposeTest(trt_test.TfTrtIntegrationTestBase): def GraphFn(self, inp): # Add a block with compatible transposes. compatible_transpose = array_ops.transpose( inp, [0, 3, 1, 2], name="transpose-1") compatible_transpose = array_ops.transpose( compatible_transpose, [0, 2, 3, 1], name="transposeback") # Add an incompatible op so the first block will not be in the same # subgraph where the following block belongs. bridge = self.trt_incompatible_op(compatible_transpose) # Add a block with incompatible transposes. # # Note: by default Grappler will run the TRT optimizer twice. At the # first time it will group the two transpose ops below to same segment # then fail the conversion due to the expected batch dimension problem. # At the second time, since the input of bridge op is TRTEngineOp_0, it # will fail to do shape inference which then cause conversion to fail. # TODO(laigd): support shape inference, make TRT optimizer run only # once, and fix this. incompatible_transpose = array_ops.transpose( bridge, [2, 1, 0, 3], name="transpose-2") excluded_transpose = array_ops.transpose( incompatible_transpose, [0, 2, 3, 1], name="transpose-3") return array_ops.identity(excluded_transpose, name="output_0") def GetParams(self): return self.BuildParams(self.GraphFn, dtypes.float32, [[100, 24, 24, 2]], [[24, 100, 2, 24]]) def ExpectedEnginesToBuild(self, run_params): """Return the expected engines to build.""" return { "TRTEngineOp_0": [ "transpose-1", "transpose-1/perm", "transposeback", "transposeback/perm" ] } def ShouldRunTest(self, run_params): """Whether to run the test.""" return (not trt_test.IsQuantizationMode(run_params.precision_mode) and not run_params.dynamic_engine) if __name__ == "__main__": test.main()
ghchinoy/tensorflow
tensorflow/python/compiler/tensorrt/test/reshape_transpose_test.py
Python
apache-2.0
5,407
-- -- Copyright 2009-2012 the original author or authors. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- drop table if exists users; create table users ( id int, name varchar(20) ); insert into users (id, name) values(1, 'User1'); insert into users (id, name) values(2, 'User2'); insert into users (id, name) values(3, 'User3');
qiuyesuifeng/mybatis-3
src/test/java/org/apache/ibatis/submitted/result_handler/CreateDB.sql
SQL
apache-2.0
879
// Copyright 2018-2020 Authors of Cilium // // 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 datapath import ( "net" "github.com/cilium/cilium/pkg/cidr" ) // NodeAddressingFamily is the node addressing information for a particular // address family type NodeAddressingFamily interface { // Router is the address that will act as the router on each node where // an agent is running on. Endpoints have a default route that points // to this address. Router() net.IP // PrimaryExternal is the primary external address of the node. Nodes // must be able to reach each other via this address. PrimaryExternal() net.IP // AllocationCIDR is the CIDR used for IP allocation of all endpoints // on the node AllocationCIDR() *cidr.CIDR // LocalAddresses lists all local addresses LocalAddresses() ([]net.IP, error) // LoadBalancerNodeAddresses lists all addresses on which HostPort and // NodePort services should be responded to LoadBalancerNodeAddresses() []net.IP } // NodeAddressing implements addressing of a node type NodeAddressing interface { IPv6() NodeAddressingFamily IPv4() NodeAddressingFamily }
tgraf/cilium
pkg/datapath/node_addressing.go
GO
apache-2.0
1,642
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.huaweicloud.smn; import java.util.HashMap; import com.huaweicloud.sdk.core.auth.BasicCredentials; import com.huaweicloud.sdk.core.http.HttpConfig; import com.huaweicloud.sdk.smn.v2.SmnClient; import com.huaweicloud.sdk.smn.v2.model.PublishMessageRequest; import com.huaweicloud.sdk.smn.v2.model.PublishMessageRequestBody; import com.huaweicloud.sdk.smn.v2.model.PublishMessageResponse; import org.apache.camel.Exchange; import org.apache.camel.component.huaweicloud.smn.constants.SmnConstants; import org.apache.camel.component.huaweicloud.smn.constants.SmnOperations; import org.apache.camel.component.huaweicloud.smn.constants.SmnProperties; import org.apache.camel.component.huaweicloud.smn.constants.SmnServices; import org.apache.camel.component.huaweicloud.smn.models.ClientConfigurations; import org.apache.camel.support.DefaultProducer; import org.apache.camel.util.ObjectHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SimpleNotificationProducer extends DefaultProducer { private static final Logger LOG = LoggerFactory.getLogger(SimpleNotificationProducer.class); private SmnClient smnClient; private ClientConfigurations clientConfigurations; public SimpleNotificationProducer(SimpleNotificationEndpoint endpoint) { super(endpoint); } @Override protected void doStart() throws Exception { super.doStart(); validateAndInitializeSmnClient((SimpleNotificationEndpoint) super.getEndpoint()); } public void process(Exchange exchange) throws Exception { String service = ((SimpleNotificationEndpoint) super.getEndpoint()).getSmnService(); if (!ObjectHelper.isEmpty(service)) { switch (service) { case SmnServices.PUBLISH_MESSAGE: if (LOG.isDebugEnabled()) { LOG.debug("Using message publishing service"); } performPublishMessageServiceOperations((SimpleNotificationEndpoint) super.getEndpoint(), exchange); if (LOG.isDebugEnabled()) { LOG.debug("Completed publishing message"); } break; default: if (LOG.isErrorEnabled()) { LOG.error("Unsupported service name {}", service); } throw new UnsupportedOperationException(String.format("service %s is not a supported service", service)); } } else { if (LOG.isErrorEnabled()) { LOG.error("Service name is null/empty"); } throw new IllegalStateException("service name cannot be null/empty"); } } /** * Publish message service operations * * @param endpoint * @param exchange */ private void performPublishMessageServiceOperations(SimpleNotificationEndpoint endpoint, Exchange exchange) { PublishMessageResponse response; PublishMessageRequestBody apiBody; this.clientConfigurations = validateServiceConfigurations(endpoint, exchange); if (LOG.isDebugEnabled()) { LOG.debug("Checking operation name"); } switch (clientConfigurations.getOperation()) { case SmnOperations.PUBLISH_AS_TEXT_MESSAGE: if (LOG.isDebugEnabled()) { LOG.debug("Publishing as text message"); } apiBody = new PublishMessageRequestBody() .withMessage(exchange.getMessage().getBody(String.class)) .withSubject(clientConfigurations.getSubject()) .withTimeToLive(String.valueOf(clientConfigurations.getMessageTtl())); response = smnClient.publishMessage(new PublishMessageRequest() .withBody(apiBody) .withTopicUrn(clientConfigurations.getTopicUrn())); break; case SmnOperations.PUBLISH_AS_TEMPLATED_MESSAGE: if (LOG.isDebugEnabled()) { LOG.debug("Publishing as templated message"); } apiBody = new PublishMessageRequestBody() .withMessage(exchange.getMessage().getBody(String.class)) .withSubject(clientConfigurations.getSubject()) .withTimeToLive(String.valueOf(clientConfigurations.getMessageTtl())) .withMessageTemplateName((String) exchange.getProperty(SmnProperties.TEMPLATE_NAME)) .withTags((HashMap<String, String>) exchange.getProperty(SmnProperties.TEMPLATE_TAGS)) .withTimeToLive(String.valueOf(clientConfigurations.getMessageTtl())); response = smnClient.publishMessage(new PublishMessageRequest() .withBody(apiBody) .withTopicUrn(clientConfigurations.getTopicUrn())); break; default: throw new UnsupportedOperationException( String.format("operation %s not supported in publishMessage service", clientConfigurations.getOperation())); } setResponseParameters(exchange, response); } /** * maps api response parameters as exchange property * * @param exchange * @param response */ private void setResponseParameters(Exchange exchange, PublishMessageResponse response) { if (response == null) { return; // mapping is not required if response object is null } if (!ObjectHelper.isEmpty(response.getMessageId())) { exchange.setProperty(SmnProperties.SERVICE_MESSAGE_ID, response.getMessageId()); } if (!ObjectHelper.isEmpty(response.getRequestId())) { exchange.setProperty(SmnProperties.SERVICE_REQUEST_ID, response.getRequestId()); } } /** * validation and initialization of SmnClient object * * @param simpleNotificationEndpoint */ private void validateAndInitializeSmnClient(SimpleNotificationEndpoint simpleNotificationEndpoint) { if (simpleNotificationEndpoint.getSmnClient() != null) { if (LOG.isWarnEnabled()) { LOG.warn( "Instance of SmnClient was set on the endpoint. Skipping creation of SmnClient from endpoint parameters"); } this.smnClient = simpleNotificationEndpoint.getSmnClient(); return; } this.clientConfigurations = new ClientConfigurations(); //checking for cloud SK (secret key) if (ObjectHelper.isEmpty(simpleNotificationEndpoint.getSecretKey()) && ObjectHelper.isEmpty(simpleNotificationEndpoint.getServiceKeys())) { if (LOG.isErrorEnabled()) { LOG.error("secret key (SK) not found"); } throw new IllegalArgumentException("authentication parameter 'secret key (SK)' not found"); } else { clientConfigurations.setSecretKey(simpleNotificationEndpoint.getSecretKey() != null ? simpleNotificationEndpoint.getSecretKey() : simpleNotificationEndpoint.getServiceKeys().getSecretKey()); } //checking for cloud AK (auth key) if (ObjectHelper.isEmpty(simpleNotificationEndpoint.getAuthKey()) && ObjectHelper.isEmpty(simpleNotificationEndpoint.getServiceKeys())) { if (LOG.isErrorEnabled()) { LOG.error("authentication key (AK) not found"); } throw new IllegalArgumentException("authentication parameter 'authentication key (AK)' not found"); } else { clientConfigurations.setAuthenticationkey(simpleNotificationEndpoint.getAuthKey() != null ? simpleNotificationEndpoint.getAuthKey() : simpleNotificationEndpoint.getServiceKeys().getAuthenticationKey()); } //checking for project ID if (ObjectHelper.isEmpty(simpleNotificationEndpoint.getProjectId())) { if (LOG.isErrorEnabled()) { LOG.error("Project ID not found"); } throw new IllegalArgumentException("project ID not found"); } else { clientConfigurations.setProjectId(simpleNotificationEndpoint.getProjectId()); } //checking for region String endpointUrl = SimpleNotificationUtils.resolveSmnServiceEndpoint(simpleNotificationEndpoint.getRegion()); if (endpointUrl == null) { if (LOG.isErrorEnabled()) { LOG.error("Valid region not found"); } throw new IllegalArgumentException("enter a valid region"); } else { clientConfigurations.setServiceEndpoint(endpointUrl); } //checking for ignore ssl verification boolean ignoreSslVerification = simpleNotificationEndpoint.isIgnoreSslVerification(); if (ignoreSslVerification) { if (LOG.isWarnEnabled()) { LOG.warn("SSL verification is ignored. This is unsafe in production environment"); } clientConfigurations.setIgnoreSslVerification(ignoreSslVerification); } //checking if http proxy authentication is used if (simpleNotificationEndpoint.getProxyHost() != null) { if (LOG.isDebugEnabled()) { LOG.debug("Reading http proxy configurations"); } clientConfigurations.setProxyHost(simpleNotificationEndpoint.getProxyHost()); clientConfigurations.setProxyPort(simpleNotificationEndpoint.getProxyPort()); clientConfigurations.setProxyUser(simpleNotificationEndpoint.getProxyUser()); clientConfigurations.setProxyPassword(simpleNotificationEndpoint.getProxyPassword()); } this.smnClient = initializeClient(clientConfigurations); } /** * initialization of smn client. this is lazily initialized on the first message * * @param clientConfigurations * @return */ private SmnClient initializeClient(ClientConfigurations clientConfigurations) { if (LOG.isDebugEnabled()) { LOG.debug("Initializing Smn client"); } HttpConfig httpConfig = null; if (clientConfigurations.getProxyHost() != null) { httpConfig = HttpConfig.getDefaultHttpConfig(); httpConfig.withProxyHost(clientConfigurations.getProxyHost()) .withProxyPort(clientConfigurations.getProxyPort()) .setIgnoreSSLVerification(clientConfigurations.isIgnoreSslVerification()); if (clientConfigurations.getProxyUser() != null) { httpConfig.withProxyUsername(clientConfigurations.getProxyUser()); httpConfig.withProxyPassword(clientConfigurations.getProxyPassword()); } } BasicCredentials credentials = new BasicCredentials() .withAk(clientConfigurations.getAuthenticationkey()) .withSk(clientConfigurations.getSecretKey()) .withProjectId(clientConfigurations.getProjectId()); if (LOG.isDebugEnabled()) { LOG.debug("Building Smn client"); } // building smn client object SmnClient smnClient = SmnClient.newBuilder() .withCredential(credentials) .withHttpConfig(httpConfig) .withEndpoint(clientConfigurations.getServiceEndpoint()) .build(); if (LOG.isDebugEnabled()) { LOG.debug("Successfully initialized Smn client"); } return smnClient; } /** * validation of all user inputs before attempting to invoke a service operation * * @param simpleNotificationEndpoint * @param exchange * @return */ private ClientConfigurations validateServiceConfigurations( SimpleNotificationEndpoint simpleNotificationEndpoint, Exchange exchange) { ClientConfigurations clientConfigurations = new ClientConfigurations(); if (LOG.isDebugEnabled()) { LOG.debug("Inspecting exchange body"); } // verifying if exchange has valid body content. this is mandatory for 'publish as text' operation if (ObjectHelper.isEmpty(exchange.getMessage().getBody())) { if (simpleNotificationEndpoint.getOperation().equals("publishAsTextMessage")) { if (LOG.isErrorEnabled()) { LOG.error("Found null/empty body. Cannot perform publish as text operation"); } throw new IllegalArgumentException("exchange body cannot be null / empty"); } } // checking for mandatory field 'operation name' if (LOG.isDebugEnabled()) { LOG.debug("Inspecting operation name"); } if (ObjectHelper.isEmpty(exchange.getProperty(SmnProperties.SMN_OPERATION)) && ObjectHelper.isEmpty(simpleNotificationEndpoint.getOperation())) { if (LOG.isErrorEnabled()) { LOG.error("Found null/empty operation name. Cannot proceed with Smn operations"); } throw new IllegalArgumentException("operation name not found"); } else { clientConfigurations.setOperation(exchange.getProperty(SmnProperties.SMN_OPERATION) != null ? (String) exchange.getProperty(SmnProperties.SMN_OPERATION) : simpleNotificationEndpoint.getOperation()); } // checking for mandatory field 'topic name' if (LOG.isDebugEnabled()) { LOG.debug("Inspecting topic name"); } if (ObjectHelper.isEmpty(exchange.getProperty(SmnProperties.NOTIFICATION_TOPIC_NAME))) { if (LOG.isErrorEnabled()) { LOG.error("Found null/empty topic name"); } throw new IllegalArgumentException("topic name not found"); } else { clientConfigurations.setTopicUrn(String.format(SmnConstants.TOPIC_URN_FORMAT, simpleNotificationEndpoint.getRegion(), simpleNotificationEndpoint.getProjectId(), exchange.getProperty(SmnProperties.NOTIFICATION_TOPIC_NAME))); } // checking for optional field 'message subject' if (LOG.isDebugEnabled()) { LOG.debug("Inspecting notification subject value"); } if (ObjectHelper.isEmpty(exchange.getProperty(SmnProperties.NOTIFICATION_SUBJECT))) { if (LOG.isWarnEnabled()) { LOG.warn("notification subject not found. defaulting to 'DEFAULT_SUBJECT'"); } clientConfigurations.setSubject("DEFAULT_SUBJECT"); } else { clientConfigurations.setSubject((String) exchange.getProperty(SmnProperties.NOTIFICATION_SUBJECT)); } // checking for optional field 'message ttl' if (LOG.isDebugEnabled()) { LOG.debug("Inspecting TTL"); } if (ObjectHelper.isEmpty(exchange.getProperty(SmnProperties.NOTIFICATION_TTL))) { if (LOG.isWarnEnabled()) { LOG.warn("TTL not found. defaulting to default value {}", simpleNotificationEndpoint.getMessageTtl()); } clientConfigurations.setMessageTtl(simpleNotificationEndpoint.getMessageTtl()); } else { clientConfigurations.setMessageTtl((int) exchange.getProperty(SmnProperties.NOTIFICATION_TTL)); } return clientConfigurations; } }
pmoerenhout/camel
components/camel-huaweicloud-smn/src/main/java/org/apache/camel/component/huaweicloud/smn/SimpleNotificationProducer.java
Java
apache-2.0
16,562
package com.zswxsqxt.wf.dao; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Repository; import cn.org.rapid_framework.page.Page; import com.opendata.common.base.BaseHibernateDao; import com.zswxsqxt.wf.model.WfActivity; import com.zswxsqxt.wf.model.WfProject; import com.zswxsqxt.wf.query.WfActivityQuery; /** describe:流程节点表Dao */ @Repository public class WfActivityDao extends BaseHibernateDao<WfActivity,String> { public Class getEntityClass() { return WfActivity.class; } /** 通过WfActivityQuery对象,查询流程节点表 */ public Page findPage(WfActivityQuery query,int pageSize,int pageNum) { StringBuilder hql=new StringBuilder(); hql.append(" from WfActivity ett where 1=1"); List param=new ArrayList(); if(query!=null) { if(!StringUtils.isEmpty(query.getId())) { hql.append(" and ett.id=?"); param.add(query.getId()); } if(!StringUtils.isEmpty(query.getName())) { hql.append(" and ett.name like ?"); param.add("%"+query.getName()+"%"); } if(query.getOrderNum()!=null) { hql.append(" and ett.orderNum=?"); param.add(query.getOrderNum()); } if(query.getActType()!=null) { hql.append(" and ett.actType=?"); param.add(query.getActType()); } if(query.getActFlag()!=null) { hql.append(" and ett.actFlag=?"); param.add(query.getActFlag()); } if(!StringUtils.isEmpty(query.getDescription())) { hql.append(" and ett.description=?"); param.add(query.getDescription()); } if(!StringUtils.isEmpty(query.getUrl())) { hql.append(" and ett.url=?"); param.add(query.getUrl()); } if(!StringUtils.isEmpty(query.getGroupFlag())) { hql.append(" and ett.groupFlag=?"); param.add(query.getGroupFlag()); } if(!StringUtils.isEmpty(query.getExtFiled3())) { hql.append(" and ett.extFiled3=?"); param.add(query.getExtFiled3()); } if(query.getTs()!=null) { hql.append(" and ett.ts=?"); param.add(query.getTs()); } if(query.getWfProject()!=null) { hql.append(" and ett.wfProject.id=?"); param.add(query.getWfProject().getId()); } if(query.getWfInstance()!=null) { hql.append(" and ett.wfInstance=?"); param.add(query.getWfInstance()); } } if(!StringUtils.isEmpty(query.getSortColumns())){ if(!query.getSortColumns().equals("ts")){ hql.append(" order by ett."+query.getSortColumns()+" , ett.ts desc "); }else{ hql.append(" order by ett.orderNum asc "); } }else{ hql.append(" order by ett.orderNum asc "); } return super.findByHql(hql.toString(), pageSize, pageNum, param.toArray()); } /** * 根据流程id得到流程下所有节点,并按照节点顺序排序 * @param proId * @return */ public List<WfActivity> getWfActivity(String proId){ String hql = "from WfActivity where wfProject.id = ? order by orderNum asc"; List<WfActivity> list = super.findFastByHql(hql, proId); if(list.size()>0){ return list; }else{ return null; } } }
TuWei1992/zswxsqxt
src/main/zswxsqxt/com/zswxsqxt/wf/dao/WfActivityDao.java
Java
apache-2.0
3,115
/** * Copyright 2015-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.swarm.plugin.maven; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.stream.Collectors; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.eclipse.aether.repository.RemoteRepository; import org.wildfly.swarm.bootstrap.util.BootstrapProperties; import org.wildfly.swarm.fractionlist.FractionList; import org.wildfly.swarm.spi.api.SwarmProperties; import org.wildfly.swarm.tools.ArtifactSpec; import org.wildfly.swarm.tools.BuildTool; import org.wildfly.swarm.tools.DependencyManager; import org.wildfly.swarm.tools.FractionDescriptor; import org.wildfly.swarm.tools.FractionUsageAnalyzer; import org.wildfly.swarm.tools.exec.SwarmExecutor; import org.wildfly.swarm.tools.exec.SwarmProcess; /** * @author Bob McWhirter * @author Ken Finnigan */ @Mojo(name = "start", requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME, requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME) public class StartMojo extends AbstractSwarmMojo { @Parameter(alias = "stdoutFile", property = "swarm.stdout") public File stdoutFile; @Parameter(alias = "stderrFile", property = "swarm.stderr" ) public File stderrFile; @Parameter(alias = "useUberJar", defaultValue = "${wildfly-swarm.useUberJar}") public boolean useUberJar; @Parameter(alias = "debug", property = SwarmProperties.DEBUG_PORT) public Integer debugPort; @Parameter(alias = "jvmArguments", property = "swarm.jvmArguments") public List<String> jvmArguments = new ArrayList<>(); @Parameter(alias = "arguments" ) public List<String> arguments = new ArrayList<>(); @Parameter(property = "swarm.arguments", defaultValue = "") public String argumentsProp; boolean waitForProcess; @SuppressWarnings({"unchecked", "ThrowableResultOfMethodCallIgnored"}) @Override public void execute() throws MojoExecutionException, MojoFailureException { initProperties(true); initEnvironment(); final SwarmExecutor executor; if (this.useUberJar) { executor = uberJarExecutor(); } else if (this.project.getPackaging().equals("war")) { executor = warExecutor(); } else if (this.project.getPackaging().equals("jar")) { executor = jarExecutor(); } else { throw new MojoExecutionException("Unsupported packaging: " + this.project.getPackaging()); } executor.withJVMArguments( this.jvmArguments ); if ( this.argumentsProp != null ) { StringTokenizer args = new StringTokenizer(this.argumentsProp); while ( args.hasMoreTokens() ) { this.arguments.add( args.nextToken() ); } } executor.withArguments( this.arguments ); final SwarmProcess process; try { process = executor.withDebug(debugPort) .withProperties(this.properties) .withStdoutFile(this.stdoutFile != null ? this.stdoutFile.toPath() : null) .withStderrFile(this.stderrFile != null ? this.stderrFile.toPath() : null) .withEnvironment(this.environment) .withWorkingDirectory(this.project.getBasedir().toPath()) .withProperty("remote.maven.repo", String.join(",", this.project.getRemoteProjectRepositories().stream() .map(RemoteRepository::getUrl) .collect(Collectors.toList()))) .execute(); Runtime.getRuntime().addShutdownHook( new Thread(()->{ try { // Sleeping for a few millis will give time to shutdown gracefully Thread.sleep(100L); process.stop( 10, TimeUnit.SECONDS ); } catch (InterruptedException e) { } })); process.awaitReadiness(2, TimeUnit.MINUTES); if (!process.isAlive()) { throw new MojoFailureException("Process failed to start"); } if (process.getError() != null) { throw new MojoFailureException("Error starting process", process.getError()); } } catch (IOException e) { throw new MojoFailureException("unable to execute", e); } catch (InterruptedException e) { throw new MojoFailureException("Error waiting for deployment", e); } List<SwarmProcess> procs = (List<SwarmProcess>) getPluginContext().get("swarm-process"); if (procs == null) { procs = new ArrayList<>(); getPluginContext().put("swarm-process", procs); } procs.add(process); if (waitForProcess) { try { process.waitFor(); } catch (InterruptedException e) { try { process.stop( 10, TimeUnit.SECONDS ); } catch (InterruptedException ie) { // Do nothing } } finally { process.destroyForcibly(); } } } protected SwarmExecutor uberJarExecutor() throws MojoFailureException { getLog().info("Starting -swarm.jar"); String finalName = this.project.getBuild().getFinalName(); if (finalName.endsWith(".war") || finalName.endsWith(".jar")) { finalName = finalName.substring(0, finalName.length() - 4); } return new SwarmExecutor() .withExecutableJar(Paths.get(this.projectBuildDir, finalName + "-swarm.jar")); } protected SwarmExecutor warExecutor() throws MojoFailureException { getLog().info("Starting .war"); String finalName = this.project.getBuild().getFinalName(); if (!finalName.endsWith(".war")) { finalName = finalName + ".war"; } return executor(Paths.get(this.projectBuildDir, finalName), finalName, false); } protected SwarmExecutor jarExecutor() throws MojoFailureException { getLog().info("Starting .jar"); final String finalName = this.project.getBuild().getFinalName(); return executor(Paths.get(this.project.getBuild().getOutputDirectory()), finalName.endsWith(".jar") ? finalName : finalName + ".jar", true); } protected SwarmExecutor executor(final Path appPath, final String name, final boolean scanDependencies) throws MojoFailureException { final SwarmExecutor executor = new SwarmExecutor() .withModules(expandModules()) .withProperty(BootstrapProperties.APP_NAME, name) .withClassPathEntries(dependencies(appPath, scanDependencies)); if (this.mainClass != null) { executor.withMainClass(this.mainClass); } else { executor.withDefaultMainClass(); } return executor; } List<Path> findNeededFractions(final Set<Artifact> existingDeps, final Path source, final boolean scanDeps) throws MojoFailureException { getLog().info("Scanning for needed WildFly Swarm fractions with mode: " + fractionDetectMode); final Set<String> existingDepGASet = existingDeps.stream() .map(d -> String.format("%s:%s", d.getGroupId(), d.getArtifactId())) .collect(Collectors.toSet()); final Set<FractionDescriptor> fractions; final FractionUsageAnalyzer analyzer = new FractionUsageAnalyzer(FractionList.get()).source(source); if (scanDeps) { existingDeps.forEach(d -> analyzer.source(d.getFile())); } final Predicate<FractionDescriptor> notExistingDep = d -> !existingDepGASet.contains(String.format("%s:%s", d.getGroupId(), d.getArtifactId())); try { fractions = analyzer.detectNeededFractions().stream() .filter(notExistingDep) .collect(Collectors.toSet()); } catch (IOException e) { throw new MojoFailureException("failed to scan for fractions", e); } getLog().info("Detected fractions: " + String.join(", ", fractions.stream() .map(FractionDescriptor::av) .sorted() .collect(Collectors.toList()))); fractions.addAll(this.additionalFractions.stream() .map(f -> FractionDescriptor.fromGav(FractionList.get(), f)) .collect(Collectors.toSet())); final Set<FractionDescriptor> allFractions = new HashSet<>(fractions); allFractions.addAll(fractions.stream() .flatMap(f -> f.getDependencies().stream()) .filter(notExistingDep) .collect(Collectors.toSet())); getLog().info("Using fractions: " + String.join(", ", allFractions.stream() .map(FractionDescriptor::gavOrAv) .sorted() .collect(Collectors.toList()))); final Set<ArtifactSpec> specs = new HashSet<>(); specs.addAll(existingDeps.stream() .map(this::artifactToArtifactSpec) .collect(Collectors.toList())); specs.addAll(allFractions.stream() .map(FractionDescriptor::toArtifactSpec) .collect(Collectors.toList())); try { return mavenArtifactResolvingHelper().resolveAll(specs).stream() .map(s -> s.file.toPath()) .collect(Collectors.toList()); } catch (Exception e) { throw new MojoFailureException("failed to resolve fraction dependencies", e); } } List<Path> dependencies(final Path archiveContent, final boolean scanDependencies) throws MojoFailureException { final List<Path> elements = new ArrayList<>(); final Set<Artifact> artifacts = this.project.getArtifacts(); boolean hasSwarmDeps = false; for (Artifact each : artifacts) { if (each.getGroupId().equals(DependencyManager.WILDFLY_SWARM_GROUP_ID) && each.getArtifactId().equals(DependencyManager.WILDFLY_SWARM_BOOTSTRAP_ARTIFACT_ID)) { hasSwarmDeps = true; } if (each.getGroupId().equals("org.jboss.logmanager") && each.getArtifactId().equals("jboss-logmanager")) { continue; } if (each.getScope().equals("provided")) { continue; } elements.add(each.getFile().toPath()); } elements.add(Paths.get(this.project.getBuild().getOutputDirectory())); if (fractionDetectMode != BuildTool.FractionDetectionMode.never) { if (fractionDetectMode == BuildTool.FractionDetectionMode.force || !hasSwarmDeps) { List<Path> fractionDeps = findNeededFractions(artifacts, archiveContent, scanDependencies); for(Path p : fractionDeps) { if(!elements.contains(p)) elements.add(p); } } } else if (!hasSwarmDeps) { getLog().warn("No WildFly Swarm dependencies found and fraction detection disabled"); } return elements; } List<Path> expandModules() { return this.additionalModules.stream() .map(m -> Paths.get(this.project.getBuild().getOutputDirectory(), m)) .collect(Collectors.toList()); } }
bobmcwhirter/wildfly-swarm
plugin/src/main/java/org/wildfly/swarm/plugin/maven/StartMojo.java
Java
apache-2.0
13,234
from O365 import attachment import unittest import json import base64 from random import randint att_rep = open('attachment.json','r').read() att_j = json.loads(att_rep) class TestAttachment (unittest.TestCase): def setUp(self): self.att = attachment.Attachment(att_j['value'][0]) def test_isType(self): self.assertTrue(self.att.isType('txt')) def test_getType(self): self.assertEqual(self.att.getType(),'.txt') def test_save(self): name = self.att.json['Name'] name1 = self.newFileName(name) self.att.json['Name'] = name1 self.assertTrue(self.att.save('/tmp')) with open('/tmp/'+name1,'r') as ins: f = ins.read() self.assertEqual('testing w00t!',f) name2 = self.newFileName(name) self.att.json['Name'] = name2 self.assertTrue(self.att.save('/tmp/')) with open('/tmp/'+name2,'r') as ins: f = ins.read() self.assertEqual('testing w00t!',f) def newFileName(self,val): for i in range(4): val = str(randint(0,9)) + val return val def test_getByteString(self): self.assertEqual(self.att.getByteString(),b'testing w00t!') def test_getBase64(self): self.assertEqual(self.att.getBase64(),'dGVzdGluZyB3MDB0IQ==\n') def test_setByteString(self): test_string = b'testing testie test' self.att.setByteString(test_string) enc = base64.encodebytes(test_string) self.assertEqual(self.att.json['ContentBytes'],enc) def setBase64(self): wrong_test_string = 'I am sooooo not base64 encoded.' right_test_string = 'Base64 <3 all around!' enc = base64.encodestring(right_test_string) self.assertRaises(self.att.setBase64(wrong_test_string)) self.assertEqual(self.att.json['ContentBytes'],'dGVzdGluZyB3MDB0IQ==\n') self.att.setBase64(enc) self.assertEqual(self.att.json['ContentBytes'],enc) if __name__ == '__main__': unittest.main()
roycem90/python-o365
tests/test_attachment.py
Python
apache-2.0
1,812
/* * Copyright (C) 2007-2015 Peter Monks. * * 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. * * This file is part of an unsupported extension to Alfresco. * */ package org.alfresco.extension.bulkimport.source.fs; import java.io.File; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.SortedMap; import java.util.TreeMap; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.alfresco.repo.content.ContentStore; import org.alfresco.service.ServiceRegistry; import org.alfresco.util.Pair; import org.alfresco.extension.bulkimport.source.BulkImportSourceStatus; import static org.alfresco.extension.bulkimport.util.LogUtils.*; import static org.alfresco.extension.bulkimport.source.fs.FilesystemSourceUtils.*; /** * This interface defines a directory analyser. This is the process by which * the contents of a source directory are grouped together into a list of * <code>FilesystemBulkImportItem</code>s. * * @author Peter Monks (pmonks@gmail.com) */ public final class DirectoryAnalyser { private final static Log log = LogFactory.getLog(DirectoryAnalyser.class); // Status counters private final static String COUNTER_NAME_FILES_SCANNED = "Files scanned"; private final static String COUNTER_NAME_DIRECTORIES_SCANNED = "Directories scanned"; private final static String COUNTER_NAME_UNREADABLE_ENTRIES = "Unreadable entries"; private final static String[] COUNTER_NAMES = { COUNTER_NAME_FILES_SCANNED, COUNTER_NAME_DIRECTORIES_SCANNED, COUNTER_NAME_UNREADABLE_ENTRIES }; private final ServiceRegistry serviceRegistry; private final ContentStore configuredContentStore; private final MetadataLoader metadataLoader; private BulkImportSourceStatus importStatus; public DirectoryAnalyser(final ServiceRegistry serviceRegistry, final ContentStore configuredContentStore, final MetadataLoader metadataLoader) { // PRECONDITIONS assert serviceRegistry != null : "serviceRegistry must not be null."; assert configuredContentStore != null : "configuredContentStore must not be null."; assert metadataLoader != null : "metadataLoader must not be null."; assert importStatus != null : "importStatus must not be null."; // Body this.serviceRegistry = serviceRegistry; this.configuredContentStore = configuredContentStore; this.metadataLoader = metadataLoader; } public void init(final BulkImportSourceStatus importStatus) { this.importStatus = importStatus; importStatus.preregisterSourceCounters(COUNTER_NAMES); } /** * Analyses the given directory. * * @param sourceDirectory The source directory for the entire import (note: <u>must</u> be a directory) <i>(must not be null)</i>. * @param directory The directory to analyse (note: <u>must</u> be a directory) <i>(must not be null)</i>. * @return An <code>AnalysedDirectory</code> object <i>(will not be null)</i>. * @throws InterruptedException If the thread executing the method is interrupted. */ public Pair<List<FilesystemBulkImportItem>, List<FilesystemBulkImportItem>> analyseDirectory(final File sourceDirectory, final File directory) throws InterruptedException { // PRECONDITIONS if (sourceDirectory == null) throw new IllegalArgumentException("sourceDirectory cannot be null."); if (directory == null) throw new IllegalArgumentException("directory cannot be null."); // Body if (debug(log)) debug(log, "Analysing directory " + getFileName(directory) + "..."); Pair<List<FilesystemBulkImportItem>, List<FilesystemBulkImportItem>> result = null; File[] directoryListing = null; long analysisStart = 0L; long analysisEnd = 0L; long start = 0L; long end = 0L; String sourceRelativeParentDirectory = sourceDirectory.toPath().relativize(directory.toPath()).toString(); // Note: JDK 1.7 specific // List the directory start = System.nanoTime(); analysisStart = start; directoryListing = directory.listFiles(); end = System.nanoTime(); if (trace(log)) trace(log, "List directory (" + directoryListing.length + " entries) took: " + (float)(end - start) / (1000 * 1000 * 1000) + "s."); // Build up the list of items from the directory listing start = System.nanoTime(); result = analyseDirectory(sourceRelativeParentDirectory, directoryListing); end = System.nanoTime(); if (trace(log)) trace(log, "Convert directory listing to set of filesystem import items took: " + (float)(end - start) / (1000 * 1000 * 1000) + "s."); analysisEnd = end; if (debug(log)) debug(log, "Finished analysing directory " + getFileName(directory) + ", in " + (float)(analysisEnd - analysisStart) / (1000 * 1000 * 1000) + "s."); return(result); } private Pair<List<FilesystemBulkImportItem>, List<FilesystemBulkImportItem>> analyseDirectory(final String sourceRelativeParentDirectory, final File[] directoryListing) { Pair<List<FilesystemBulkImportItem>, List<FilesystemBulkImportItem>> result = null; if (directoryListing != null) { // This needs some Clojure, desperately... Map<String, SortedMap<BigDecimal, Pair<File, File>>> categorisedFiles = categoriseFiles(directoryListing); if (debug(log)) debug(log, "Categorised files: " + String.valueOf(categorisedFiles)); result = constructImportItems(sourceRelativeParentDirectory, categorisedFiles); } return(result); } private Map<String, SortedMap<BigDecimal, Pair<File, File>>> categoriseFiles(final File[] directoryListing) { Map<String, SortedMap<BigDecimal, Pair<File, File>>> result = null; if (directoryListing != null) { result = new HashMap<String, SortedMap<BigDecimal, Pair<File, File>>>(); for (final File file : directoryListing) { categoriseFile(result, file); } } return(result); } /* * This method does the hard work of figuring out where the file belongs (which parent item, and where in that item's * version history). */ private void categoriseFile(final Map<String, SortedMap<BigDecimal, Pair<File, File>>> categorisedFiles, final File file) { if (file != null) { if (file.canRead()) { final String fileName = file.getName(); final String parentName = getParentName(metadataLoader, fileName); final boolean isMetadata = isMetadataFile(metadataLoader, fileName); final BigDecimal versionNumber = getVersionNumber(fileName); SortedMap<BigDecimal, Pair<File, File>> versions = categorisedFiles.get(parentName); // Find the item if (versions == null) { versions = new TreeMap<BigDecimal, Pair<File, File>>(); categorisedFiles.put(parentName, versions); } // Find the version within the item Pair<File, File> version = versions.get(versionNumber); if (version == null) { version = new Pair<File, File>(null, null); } // Categorise the incoming file in that version of the item if (isMetadata) { version = new Pair<File, File>(version.getFirst(), file); } else { version = new Pair<File, File>(file, version.getSecond()); } versions.put(versionNumber, version); if (file.isDirectory()) { importStatus.incrementSourceCounter(COUNTER_NAME_DIRECTORIES_SCANNED); } else { importStatus.incrementSourceCounter(COUNTER_NAME_FILES_SCANNED); } } else { if (warn(log)) warn(log, "Skipping '" + getFileName(file) + "' as Alfresco does not have permission to read it."); importStatus.incrementSourceCounter(COUNTER_NAME_UNREADABLE_ENTRIES); } } } private Pair<List<FilesystemBulkImportItem>, List<FilesystemBulkImportItem>> constructImportItems(final String sourceRelativeParentDirectory, final Map<String, SortedMap<BigDecimal,Pair<File,File>>> categorisedFiles) { Pair<List<FilesystemBulkImportItem>, List<FilesystemBulkImportItem>> result = null; if (categorisedFiles != null) { final List<FilesystemBulkImportItem> directoryItems = new ArrayList<FilesystemBulkImportItem>(); final List<FilesystemBulkImportItem> fileItems = new ArrayList<FilesystemBulkImportItem>(); result = new Pair<List<FilesystemBulkImportItem>, List<FilesystemBulkImportItem>>(directoryItems, fileItems); for (final String parentName : categorisedFiles.keySet()) { final SortedMap<BigDecimal,Pair<File,File>> itemVersions = categorisedFiles.get(parentName); final NavigableSet<FilesystemBulkImportItemVersion> versions = constructImportItemVersions(itemVersions); final boolean isDirectory = versions.last().isDirectory(); final FilesystemBulkImportItem item = new FilesystemBulkImportItem(parentName, isDirectory, sourceRelativeParentDirectory, versions); if (isDirectory) { directoryItems.add(item); } else { fileItems.add(item); } } } return(result); } private final NavigableSet<FilesystemBulkImportItemVersion> constructImportItemVersions(final SortedMap<BigDecimal,Pair<File,File>> itemVersions) { // PRECONDITIONS if (itemVersions == null) throw new IllegalArgumentException("itemVersions cannot be null."); if (itemVersions.size() <= 0) throw new IllegalArgumentException("itemVersions cannot be empty."); // Body final NavigableSet<FilesystemBulkImportItemVersion> result = new TreeSet<FilesystemBulkImportItemVersion>(); for (final BigDecimal versionNumber : itemVersions.keySet()) { final Pair<File,File> contentAndMetadataFiles = itemVersions.get(versionNumber); final FilesystemBulkImportItemVersion version = new FilesystemBulkImportItemVersion(serviceRegistry, configuredContentStore, metadataLoader, versionNumber, contentAndMetadataFiles.getFirst(), contentAndMetadataFiles.getSecond()); result.add(version); } return(result); } }
aureg/alfresco-bulk-import
amp/src/main/java/org/alfresco/extension/bulkimport/source/fs/DirectoryAnalyser.java
Java
apache-2.0
13,939
# Change Log All releases of the BOSH CPI for Google Cloud Platform will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). ## [30.0.0] - 2019-01-04 ### Added - MULTI_IP_SUBNET support in GCE ### Changed - Go 1.12 - BOSH API v2 ## [29.0.0] - 2019-01-04 ### Fixed - VM IP address is cleared when dynamic network is used ### Added - Logs are returned in response to BOSH, making them viewable in task log - If a disk is already attached to a VM, it will only be attached via the BOSH agent ## [28.0.1] - 2018-10-02 ### Fixed - Avoid keeping old golang installation files in GOROOT ## [28.0.0] - 2018-09-18 ### Added - Support for scheme agnostic backend services. - Made it possible to inject a Google client when testing. - Implement a Find Service for accelerator types. - Implements creation of VM with accelerator. - Support for Accelerator in Cloud Properties. - Support for CPI Config. ### Changed - Use Debian 9 in test infrastructure. - Avoid Sandy Bridge CPUs. - Use Go 1.9. - Update types to pointer where is needed. ### Fixed - Fixes for integration tests modifying the CPI request to include context necessary for the 'cpi-config'-enabled CPI. - Fixes for unit tests. ## [25.10.0] - 2017-08-17 ### Added - Google Cloud Storage is a supported blobstore backend ### Changed - Improved documentation to include the new BOSH CLI ## [25.9.0] - 2017-05-23 ### Fixed - Address inconsistent stream error: stream ID 1; PROTOCOL_ERROR errors in CPI calls by updating to Go 1.8.1 CI: ### Changed - Tests use proper custom backend - Add publish light-stemcell 3421 jobs ## [25.8.0] - 2017-05-16 ### Changed - Tags no longer become labels on GCP - Support XPN VPC Networks via the `xpn_host_project_id` cloud property - Support for customizing user agent strings - Publish CentOS Lite 3363.x, 3312.x, Ubuntu Alpha Lite stemcells - Docs: update ubuntu image for bosh-bastion - Docs: simplify grabbing project ID - Docs: add backend_service docs for internal load balancers ## [25.7.1] - 2017-03-07 ### Fixed - Previously, requests to Google APIs that returned 5xx response codes were retried. This change adds retry support to transport errors (net.Error) that are known to be temporary. ## [25.7.0] - 2017-03-03 ### Fixed - Various docs changes ### Changed - Labels may be specified in cloud properties - CF docs include TCP router - Use lateset Docker image in CIA - Support internal load balancer ## [25.6.2] - 2016-12-19 ### Fixed - Improve tests - Corrects MTU on garden job ### Changed - Support `ImageURL` for specifying stemcellA - Concourse docs incude SSL support - Docs require setting a password instead of using default ## [25.6.1] - 2016-11-02 ### Fixed - Handles large disk sizes ### Changed - CF docs run under free-tier quota - Integration tests can use local stemcell ## [25.6.0] - 2016-10-27 ### Changed - Supports `has_disk` method - Improvements to stemcell pipelines ## [25.5.0] - 2016-10-17 ### Changed - Release uses Go 1.7.1 ### Fixed - A backend service previously could not have multiple instance groups with the same name. This release fixes that, and you may have instance groups with the same name associated to a backend service. ## [25.4.1] - 2016-09-14 ### Fixed - Tags that are applied by the director on VM create will be truncated to ensure they do not violate the 63-char max limit imposed by GCE. ## [25.4.0] - 2016-09-14 ### Changed - When using a custom service account, a default `cloud-platform` scope is used if no custom scopes are specified. ## [25.3.0] - 2016-09-02 ### Added - S3 is now a supported blobstore type. ## [25.2.1] - 2016-08-18 ### Fixed - Underscores are replaced with hyphens in metadata that is applied as labels to a VM. ### Added - Complete Concourse installation instructions, including cloud config and Terraform. ## [25.2.0] - 2016-08-18 ### Changed - Any metadata provided by bosh in the `set_vm_metadata` action will also be propagated to the VM as [labels](https://cloud.google.com/compute/docs/label-or-tag-resources), allowing sorting and filter in the web console based on job, deployment, etc. ## [25.1.0] - 2016-08-18 ### Added - The `service_account` cloud-config property may now use the e-mail address of a custom service account. ## [25.0.0] - 2016-07-25 ### Changed - The `default_zone` config property (in the `google` section of a manifest) is no longer supported. The `zone` property must be explicitly set in the `cloud_properties` section of `resource_pools` (or `azs` for a cloud-config director.) ## [24.4.0] - 2016-07-25 ### Fixed - An explicit region is used to locate a subnet, allowing subnets with the same name to be differentiated. ## [24.3.0] - 2016-07-25 ### Added - A `resource_pool`'s manifest can now specify `ephemeral_external_ip` and `ip_forwarding` properties, overriding those same properties in a manifest's `networks` section. ## [24.2.0] - 2016-07-25 ### Added - This changelog ### Changed - 3262.4 stemcell ### Fixed - All tests now use light stemcells ## [24.1.0] - 2016-07-25 ### Changed - Instance tags can be specified in any `cloud_properties` section of a BOSH manifest ### Removed - The dummy BOSH release is no longer part of the CI pipeline ### Fixed - Integration tests will use the CI pipeline stemcell rather than requiring an existing stemcell in a project [30.0.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v29.0.1...v30.0.0 [29.0.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v28.0.1...v29.0.0 [28.0.1]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v28.0.0...v28.0.1 [25.10.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.9.0...v25.10.0 [25.9.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.8.0...v25.9.0 [25.8.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.7.1...v25.8.0 [25.7.1]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.7.0...v25.7.1 [25.7.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.6.2...v25.7.0 [25.6.2]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.6.1...v25.6.2 [25.6.1]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.6.0...v25.6.1 [25.6.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.5.0...v25.6.0 [25.5.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.4.1...v25.5.0 [25.4.1]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.4.0...v25.4.1 [25.4.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.3.0...v25.4.0 [25.3.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.2.1...v25.3.0 [25.2.1]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.2.0...v25.2.1 [25.2.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.1.0...v25.2.0 [25.1.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.0.0...v25.1.0 [25.0.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v24.4.0...v25.0.0 [24.4.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v24.3.0...v24.4.0 [24.3.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v24.2.0...v24.3.0 [24.2.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v24.1.0...v24.2.0 [24.1.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v24...v24.1.0
cloudfoundry-incubator/bosh-google-cpi-release
CHANGELOG.md
Markdown
apache-2.0
7,760
# Copyright 2014 The Oppia 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. """Base model class.""" __author__ = 'Sean Lip' import feconf import utils from core.platform import models transaction_services = models.Registry.import_transaction_services() from google.appengine.ext import ndb class BaseModel(ndb.Model): """Base model for all persistent object storage classes.""" # When this entity was first created. created_on = ndb.DateTimeProperty(auto_now_add=True) # When this entity was last updated. last_updated = ndb.DateTimeProperty(auto_now=True) # Whether the current version of the file is deleted. deleted = ndb.BooleanProperty(indexed=True, default=False) @property def id(self): """A unique id for this model instance.""" return self.key.id() def _pre_put_hook(self): """This is run before model instances are saved to the datastore. Subclasses of BaseModel should override this method. """ pass class EntityNotFoundError(Exception): """Raised when no entity for a given id exists in the datastore.""" pass @classmethod def get(cls, entity_id, strict=True): """Gets an entity by id. Fails noisily if strict == True. Args: entity_id: str. The id of the entity. strict: bool. Whether to fail noisily if no entity with the given id exists in the datastore. Returns: None, if strict == False and no undeleted entity with the given id exists in the datastore. Otherwise, the entity instance that corresponds to the given id. Raises: - base_models.BaseModel.EntityNotFoundError: if strict == True and no undeleted entity with the given id exists in the datastore. """ entity = cls.get_by_id(entity_id) if entity and entity.deleted: entity = None if strict and entity is None: raise cls.EntityNotFoundError( 'Entity for class %s with id %s not found' % (cls.__name__, entity_id)) return entity def put(self): super(BaseModel, self).put() @classmethod def get_multi(cls, entity_ids): entity_keys = [ndb.Key(cls, entity_id) for entity_id in entity_ids] return ndb.get_multi(entity_keys) @classmethod def put_multi(cls, entities): return ndb.put_multi(entities) def delete(self): super(BaseModel, self).key.delete() @classmethod def get_all(cls, include_deleted_entities=False): """Returns a filterable iterable of all entities of this class. If include_deleted_entities is True then entities that have been marked deleted are returned as well. """ query = cls.query() if not include_deleted_entities: query = query.filter(cls.deleted == False) return query @classmethod def get_new_id(cls, entity_name): """Gets a new id for an entity, based on its name. The returned id is guaranteed to be unique among all instances of this entity. Args: entity_name: the name of the entity. Coerced to a utf-8 encoded string. Defaults to ''. Returns: str: a new unique id for this entity class. Raises: - Exception: if an id cannot be generated within a reasonable number of attempts. """ try: entity_name = unicode(entity_name).encode('utf-8') except Exception: entity_name = '' MAX_RETRIES = 10 RAND_RANGE = 127 * 127 ID_LENGTH = 12 for i in range(MAX_RETRIES): new_id = utils.convert_to_hash( '%s%s' % (entity_name, utils.get_random_int(RAND_RANGE)), ID_LENGTH) if not cls.get_by_id(new_id): return new_id raise Exception('New id generator is producing too many collisions.') class VersionedModel(BaseModel): """Model that handles storage of the version history of model instances. To use this class, you must declare a SNAPSHOT_METADATA_CLASS and a SNAPSHOT_CONTENT_CLASS. The former must contain the String fields 'committer_id', 'commit_type' and 'commit_message', and a JSON field for the Python list of dicts, 'commit_cmds'. The latter must contain the JSON field 'content'. The item that is being versioned must be serializable to a JSON blob. Note that commit() should be used for VersionedModels, as opposed to put() for direct subclasses of BaseModel. """ # The class designated as the snapshot model. This should be a subclass of # BaseSnapshotMetadataModel. SNAPSHOT_METADATA_CLASS = None # The class designated as the snapshot content model. This should be a # subclass of BaseSnapshotContentModel. SNAPSHOT_CONTENT_CLASS = None # Whether reverting is allowed. Default is False. ALLOW_REVERT = False ### IMPORTANT: Subclasses should only overwrite things above this line. ### # The possible commit types. _COMMIT_TYPE_CREATE = 'create' _COMMIT_TYPE_REVERT = 'revert' _COMMIT_TYPE_EDIT = 'edit' _COMMIT_TYPE_DELETE = 'delete' # A list containing the possible commit types. COMMIT_TYPE_CHOICES = [ _COMMIT_TYPE_CREATE, _COMMIT_TYPE_REVERT, _COMMIT_TYPE_EDIT, _COMMIT_TYPE_DELETE ] # The delimiter used to separate the version number from the model instance # id. To get the instance id from a snapshot id, use Python's rfind() # method to find the location of this delimiter. _VERSION_DELIMITER = '-' # The reserved prefix for keys that are automatically inserted into a # commit_cmd dict by this model. _AUTOGENERATED_PREFIX = 'AUTO' # The current version number of this instance. In each PUT operation, # this number is incremented and a snapshot of the modified instance is # stored in the snapshot metadata and content models. The snapshot # version number starts at 1 when the model instance is first created. # All data in this instance represents the version at HEAD; data about the # previous versions is stored in the snapshot models. version = ndb.IntegerProperty(default=0) def _require_not_marked_deleted(self): if self.deleted: raise Exception('This model instance has been deleted.') def _compute_snapshot(self): """Generates a snapshot (a Python dict) from the model fields.""" return self.to_dict(exclude=['created_on', 'last_updated']) def _reconstitute(self, snapshot_dict): """Makes this instance into a reconstitution of the given snapshot.""" self.populate(**snapshot_dict) return self def _reconstitute_from_snapshot_id(self, snapshot_id): """Makes this instance into a reconstitution of the given snapshot.""" snapshot_model = self.SNAPSHOT_CONTENT_CLASS.get(snapshot_id) snapshot_dict = snapshot_model.content return self._reconstitute(snapshot_dict) @classmethod def _get_snapshot_id(cls, instance_id, version_number): return '%s%s%s' % ( instance_id, cls._VERSION_DELIMITER, version_number) def _trusted_commit( self, committer_id, commit_type, commit_message, commit_cmds): if self.SNAPSHOT_METADATA_CLASS is None: raise Exception('No snapshot metadata class defined.') if self.SNAPSHOT_CONTENT_CLASS is None: raise Exception('No snapshot content class defined.') if not isinstance(commit_cmds, list): raise Exception( 'Expected commit_cmds to be a list of dicts, received %s' % commit_cmds) for item in commit_cmds: if not isinstance(item, dict): raise Exception( 'Expected commit_cmds to be a list of dicts, received %s' % commit_cmds) self.version += 1 snapshot = self._compute_snapshot() snapshot_id = self._get_snapshot_id(self.id, self.version) snapshot_metadata_instance = self.SNAPSHOT_METADATA_CLASS( id=snapshot_id, committer_id=committer_id, commit_type=commit_type, commit_message=commit_message, commit_cmds=commit_cmds) snapshot_content_instance = self.SNAPSHOT_CONTENT_CLASS( id=snapshot_id, content=snapshot) transaction_services.run_in_transaction( ndb.put_multi, [snapshot_metadata_instance, snapshot_content_instance, self]) def delete(self, committer_id, commit_message, force_deletion=False): if force_deletion: current_version = self.version version_numbers = [str(num + 1) for num in range(current_version)] snapshot_ids = [ self._get_snapshot_id(self.id, version_number) for version_number in version_numbers] metadata_keys = [ ndb.Key(self.SNAPSHOT_METADATA_CLASS, snapshot_id) for snapshot_id in snapshot_ids] ndb.delete_multi(metadata_keys) content_keys = [ ndb.Key(self.SNAPSHOT_CONTENT_CLASS, snapshot_id) for snapshot_id in snapshot_ids] ndb.delete_multi(content_keys) super(VersionedModel, self).delete() else: self._require_not_marked_deleted() self.deleted = True CMD_DELETE = '%s_mark_deleted' % self._AUTOGENERATED_PREFIX commit_cmds = [{ 'cmd': CMD_DELETE }] self._trusted_commit( committer_id, self._COMMIT_TYPE_DELETE, commit_message, commit_cmds) def put(self, *args, **kwargs): """For VersionedModels, this method is replaced with commit().""" raise NotImplementedError def commit(self, committer_id, commit_message, commit_cmds): """Saves a version snapshot and updates the model. commit_cmds should give sufficient information to reconstruct the commit. """ self._require_not_marked_deleted() for commit_cmd in commit_cmds: if 'cmd' not in commit_cmd: raise Exception( 'Invalid commit_cmd: %s. Expected a \'cmd\' key.' % commit_cmd) if commit_cmd['cmd'].startswith(self._AUTOGENERATED_PREFIX): raise Exception( 'Invalid change list command: ' % commit_cmd['cmd']) commit_type = ( self._COMMIT_TYPE_CREATE if self.version == 0 else self._COMMIT_TYPE_EDIT) self._trusted_commit( committer_id, commit_type, commit_message, commit_cmds) def revert(self, committer_id, commit_message, version_number): self._require_not_marked_deleted() if not self.ALLOW_REVERT: raise Exception( 'Reverting of objects of type %s is not allowed.' % self.__class__.__name__) CMD_REVERT = '%s_revert_version_number' % self._AUTOGENERATED_PREFIX commit_cmds = [{ 'cmd': CMD_REVERT, 'version_number': version_number }] # Do not overwrite the version number. current_version = self.version snapshot_id = self._get_snapshot_id(self.id, version_number) self._reconstitute_from_snapshot_id(snapshot_id) self.version = current_version self._trusted_commit( committer_id, self._COMMIT_TYPE_REVERT, commit_message, commit_cmds) @classmethod def get_version(cls, model_instance_id, version_number): """Returns a model instance representing the given version. The snapshot content is used to populate this model instance. The snapshot metadata is not used. """ cls.get(model_instance_id)._require_not_marked_deleted() snapshot_id = cls._get_snapshot_id(model_instance_id, version_number) return cls(id=model_instance_id)._reconstitute_from_snapshot_id( snapshot_id) @classmethod def get(cls, entity_id, strict=True, version=None): """Gets an entity by id. Fails noisily if strict == True.""" if version is None: return super(VersionedModel, cls).get(entity_id, strict=strict) else: return cls.get_version(entity_id, version) @classmethod def get_snapshots_metadata(cls, model_instance_id, version_numbers): """Returns a list of dicts, each representing a model snapshot. One dict is returned for each version number in the list of version numbers requested. If any of the version numbers does not exist, an error is raised. """ cls.get(model_instance_id)._require_not_marked_deleted() snapshot_ids = [ cls._get_snapshot_id(model_instance_id, version_number) for version_number in version_numbers] metadata_keys = [ ndb.Key(cls.SNAPSHOT_METADATA_CLASS, snapshot_id) for snapshot_id in snapshot_ids] returned_models = ndb.get_multi(metadata_keys) for ind, model in enumerate(returned_models): if model is None: raise Exception( 'Invalid version number %s for model %s with id %s' % (version_numbers[ind], cls.__name__, model_instance_id)) return [{ 'committer_id': model.committer_id, 'commit_message': model.commit_message, 'commit_cmds': model.commit_cmds, 'commit_type': model.commit_type, 'version_number': version_numbers[ind], 'created_on': model.created_on.strftime( feconf.HUMAN_READABLE_DATETIME_FORMAT), } for (ind, model) in enumerate(returned_models)] class BaseSnapshotMetadataModel(BaseModel): """Base class for snapshot metadata classes. The id of this model is computed using VersionedModel.get_snapshot_id(). """ # The id of the user who committed this revision. committer_id = ndb.StringProperty(required=True) # The type of the commit associated with this snapshot. commit_type = ndb.StringProperty( required=True, choices=VersionedModel.COMMIT_TYPE_CHOICES) # The commit message associated with this snapshot. commit_message = ndb.TextProperty(indexed=False) # A sequence of commands that can be used to describe this commit. # Represented as a list of dicts. commit_cmds = ndb.JsonProperty(indexed=False) class BaseSnapshotContentModel(BaseModel): """Base class for snapshot content classes. The id of this model is computed using VersionedModel.get_snapshot_id(). """ # The snapshot content, as a JSON blob. content = ndb.JsonProperty(indexed=False)
openhatch/oh-missions-oppia-beta
core/storage/base_model/gae_models.py
Python
apache-2.0
15,533
using TestMonkeys.EntityTest.Framework; namespace UsageExample.PropertySetValidatorTests.TestObjects { public class TestObjectImproperGreaterThan { [ValidateActualGreaterThan(0)] public object GreaterThanValue { get; set; } } }
TestMonkeys/Assert
UsageExample/PropertySetValidatorTests/TestObjects/TestObjectImproperGreaterThan.cs
C#
apache-2.0
259
// Copyright 2022 Google LLC // // 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. // Generated code. DO NOT EDIT! namespace Google.Cloud.Tpu.V1.Snippets { // [START tpu_v1_generated_Tpu_CreateNode_async] using Google.Api.Gax.ResourceNames; using Google.Cloud.Tpu.V1; using Google.LongRunning; using System.Threading.Tasks; public sealed partial class GeneratedTpuClientSnippets { /// <summary>Snippet for CreateNodeAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task CreateNodeRequestObjectAsync() { // Create client TpuClient tpuClient = await TpuClient.CreateAsync(); // Initialize request argument(s) CreateNodeRequest request = new CreateNodeRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), NodeId = "", Node = new Node(), }; // Make the request Operation<Node, OperationMetadata> response = await tpuClient.CreateNodeAsync(request); // Poll until the returned long-running operation is complete Operation<Node, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Node result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Node, OperationMetadata> retrievedResponse = await tpuClient.PollOnceCreateNodeAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Node retrievedResult = retrievedResponse.Result; } } } // [END tpu_v1_generated_Tpu_CreateNode_async] }
googleapis/google-cloud-dotnet
apis/Google.Cloud.Tpu.V1/Google.Cloud.Tpu.V1.GeneratedSnippets/TpuClient.CreateNodeRequestObjectAsyncSnippet.g.cs
C#
apache-2.0
2,721
/* * Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com) * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mycontroller.standalone.api.jaxrs.mixins.deserializers; import java.io.IOException; import org.mycontroller.standalone.timer.TimerUtils.FREQUENCY_TYPE; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; /** * @author Jeeva Kandasamy (jkandasa) * @since 0.0.2 */ public class FrequencyTypeDeserializer extends JsonDeserializer<FREQUENCY_TYPE> { @Override public FREQUENCY_TYPE deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException { final String nodeType = parser.getText(); if (nodeType != null) { return FREQUENCY_TYPE.fromString(nodeType); } else { return null; } } }
pgh70/mycontroller
modules/core/src/main/java/org/mycontroller/standalone/api/jaxrs/mixins/deserializers/FrequencyTypeDeserializer.java
Java
apache-2.0
1,580
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Definitions { public class GoToDefinitionTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGotoDefinitionAsync() { var markup = @"class A { string {|definition:aString|} = 'hello'; void M() { var len = {|caret:|}aString.Length; } }"; var (solution, locations) = CreateTestSolution(markup); var results = await RunGotoDefinitionAsync(solution, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoDefinitionAsync_DifferentDocument() { var markups = new string[] { @"namespace One { class A { public static int {|definition:aInt|} = 1; } }", @"namespace One { class B { int bInt = One.A.{|caret:|}aInt; } }" }; var (solution, locations) = CreateTestSolution(markups); var results = await RunGotoDefinitionAsync(solution, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoDefinitionAsync_InvalidLocation() { var markup = @"class A { void M() {{|caret:|} var len = aString.Length; } }"; var (solution, locations) = CreateTestSolution(markup); var results = await RunGotoDefinitionAsync(solution, locations["caret"].Single()); Assert.Empty(results); } private static async Task<LSP.Location[]> RunGotoDefinitionAsync(Solution solution, LSP.Location caret) => (LSP.Location[])await GetLanguageServer(solution).GoToDefinitionAsync(solution, CreateTextDocumentPositionParams(caret), new LSP.ClientCapabilities(), CancellationToken.None); } }
nguerrera/roslyn
src/Features/LanguageServer/ProtocolUnitTests/Definitions/GoToDefinitionTests.cs
C#
apache-2.0
2,280
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.mskcc.shenkers.data.interval; import htsjdk.tribble.Feature; import htsjdk.tribble.annotation.Strand; import htsjdk.tribble.bed.FullBEDFeature; import java.awt.Color; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * * @author sol */ public interface IntervalFeature<T> extends Feature { Strand getStrand(); T getValue(); }
shenkers/CrossBrowse
src/main/java/org/mskcc/shenkers/data/interval/IntervalFeature.java
Java
apache-2.0
585
/* fixed page header & footer configuration */ .ui-header-fixed, .ui-footer-fixed { left: 0; right: 0; width: 100%; position: fixed; z-index: 1000; } .ui-header-fixed { top: -1px; padding-top: 1px; } .ui-header-fixed.ui-fixed-hidden { top: 0; padding-top: 0; } .ui-header-fixed .ui-btn-left, .ui-header-fixed .ui-btn-right { margin-top: 1px; } .ui-header-fixed.ui-fixed-hidden .ui-btn-left, .ui-header-fixed.ui-fixed-hidden .ui-btn-right { margin-top: 0; } .ui-footer-fixed { bottom: -1px; padding-bottom: 1px; } .ui-footer-fixed.ui-fixed-hidden { bottom: 0; padding-bottom: 0; } .ui-header-fullscreen, .ui-footer-fullscreen { filter: Alpha(Opacity=90); opacity: .9; } /* updatePagePadding() will update the padding to actual height of header and footer. */ .ui-page-header-fixed { padding-top: 2.8125em; } .ui-page-footer-fixed { padding-bottom: 2.8125em; } .ui-page-header-fullscreen > .ui-content, .ui-page-footer-fullscreen > .ui-content { padding: 0; } .ui-fixed-hidden { position: absolute; } .ui-page-header-fullscreen .ui-fixed-hidden, .ui-page-footer-fullscreen .ui-fixed-hidden { position: absolute !important; height: 1px; width: 1px; overflow: hidden; clip: rect(1px,1px,1px,1px); } .ui-header-fixed .ui-btn, .ui-footer-fixed .ui-btn { z-index: 10; } /* workarounds for other widgets */ .ui-android-2x-fixed .ui-li-has-thumb { -webkit-transform: translate3d(0,0,0); }
ronagapitz/matchdrobe-app
www/css/structure/jquery.mobile.fixedToolbar.css
CSS
apache-2.0
1,409
/*! @license * Shaka Player * Copyright 2016 Google LLC * SPDX-License-Identifier: Apache-2.0 */ goog.provide('shaka.ui.FastForwardButton'); goog.require('shaka.ui.Controls'); goog.require('shaka.ui.Element'); goog.require('shaka.ui.Enums'); goog.require('shaka.ui.Locales'); goog.require('shaka.ui.Localization'); goog.require('shaka.util.Dom'); /** * @extends {shaka.ui.Element} * @final * @export */ shaka.ui.FastForwardButton = class extends shaka.ui.Element { /** * @param {!HTMLElement} parent * @param {!shaka.ui.Controls} controls */ constructor(parent, controls) { super(parent, controls); /** @private {!HTMLButtonElement} */ this.button_ = shaka.util.Dom.createButton(); this.button_.classList.add('material-icons-round'); this.button_.classList.add('shaka-fast-forward-button'); this.button_.classList.add('shaka-tooltip-status'); this.button_.setAttribute('shaka-status', '1x'); this.button_.textContent = shaka.ui.Enums.MaterialDesignIcons.FAST_FORWARD; this.parent.appendChild(this.button_); this.updateAriaLabel_(); /** @private {!Array.<number>} */ this.fastForwardRates_ = this.controls.getConfig().fastForwardRates; this.eventManager.listen( this.localization, shaka.ui.Localization.LOCALE_UPDATED, () => { this.updateAriaLabel_(); }); this.eventManager.listen( this.localization, shaka.ui.Localization.LOCALE_CHANGED, () => { this.updateAriaLabel_(); }); this.eventManager.listen(this.button_, 'click', () => { this.fastForward_(); }); } /** * @private */ updateAriaLabel_() { this.button_.ariaLabel = this.localization.resolve(shaka.ui.Locales.Ids.FAST_FORWARD); } /** * Cycles trick play rate between the selected fast forward rates. * @private */ fastForward_() { if (!this.video.duration) { return; } const trickPlayRate = this.player.getPlaybackRate(); const newRateIndex = this.fastForwardRates_.indexOf(trickPlayRate) + 1; // When the button is clicked, the next rate in this.fastForwardRates_ is // selected. If no more rates are available, the first one is set. const newRate = (newRateIndex != this.fastForwardRates_.length) ? this.fastForwardRates_[newRateIndex] : this.fastForwardRates_[0]; this.player.trickPlay(newRate); this.button_.setAttribute('shaka-status', newRate + 'x'); } }; /** * @implements {shaka.extern.IUIElement.Factory} * @final */ shaka.ui.FastForwardButton.Factory = class { /** @override */ create(rootElement, controls) { return new shaka.ui.FastForwardButton(rootElement, controls); } }; shaka.ui.Controls.registerElement( 'fast_forward', new shaka.ui.FastForwardButton.Factory());
tvoli/shaka-player
ui/fast_forward_button.js
JavaScript
apache-2.0
2,812
# General Information for Windows This file describes how to install, or build, and use Julia on Windows. For more general information about Julia, please see the [main README](https://github.com/JuliaLang/julia/blob/master/README.md) or the [documentation](http://docs.julialang.org/). # Unicode font support The built-in Windows fonts have rather poor coverage of the Unicode character space. The free [`DejaVu Sans Mono`](http://dejavu-fonts.org/) font can be used as a replacement font in the Windows console. Since Windows 2000, simply downloading the font and installing it is insufficient, since Windows keeps a list of approved fonts in the registry. Instructions for adding fonts to the terminal are available at: [http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q247815](http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q247815) Additionally, rather than sticking with the default command prompt, you may want to use a different terminal emulator program, such as [`Conemu`](https://code.google.com/p/conemu-maximus5/) or [`Mintty`](https://code.google.com/p/mintty/) (note that running Julia on Mintty needs a copy of `stty.exe` in your `%PATH%` to work properly). Alternatively, you may prefer the features of a more full-function IDE, such as [`LightTable`](https://github.com/one-more-minute/Jupiter-LT), [`Sublime-IJulia`](https://github.com/quinnj/Sublime-IJulia), [`IJulia`](https://github.com/JuliaLang/IJulia.jl), or [`Julia Studio`](http://forio.com/labs/julia-studio/). # Binary distribution Julia runs on Windows XP-SP2 and later (including Windows Vista, Windows 7, and Windows 8). Both the 32-bit and 64-bit versions are supported. The 32-bit (i686) binary will run on either a 32-bit and 64-bit operating system. The 64-bit (x86_64) binary will only run on 64-bit Windows and will otherwise refuse to launch. 1. Download and install [7-Zip](http://www.7-zip.org/download.html). Install the full program, not just the command line version. 2. [Download](http://julialang.org/downloads) the latest version of Julia. Extract the binary to a reasonable destination folder, e.g. `C:\julia`. 3. Double-click the file `julia.bat` to launch Julia. # Line endings Julia uses binary-mode files exclusively. Unlike many other Window's programs, if you write '\n' to a file, you get a '\n' in the file, not some other bit pattern. This matches the behavior exhibited by other operating systems. If you have installed msysGit, it is suggested, but not required, that you configure your system msysGit to use the same convention: git config --global core.eol = lf git config --global core.autocrlf = input or edit `%USERPROFILE%\.gitconfig` and add/edit the lines: [core] eol = lf autocrlf = input # Source distribution ## Supported build platforms - Windows 8: supported (32 and 64 bits) - Windows 7: supported (32 and 64 bits) - Windows Vista: unknown - Windows XP: not supported (however, there have been some reports of success following the msys2 steps) ## Compiling with MinGW/MSYS2 ### MSYS2 provides a robust MSYS experience. ### The instructions in this section were tested with the latest versions of all packages specified as of 2014-02-28. 1. Install [7-Zip](http://www.7-zip.org/download.html). 2. Install [Python 2.x](http://www.python.org/download/releases). Do **not** install Python 3. 3. Install [MinGW-builds](http://sourceforge.net/projects/mingwbuilds/), a Windows port of GCC, as follows. Do **not** use the regular MinGW distribution. 1. Download the [MinGW-builds installer](http://downloads.sourceforge.net/project/mingwbuilds/mingw-builds-install/mingw-builds-install.exe). 2. Run the installer. When prompted, choose: - Version: the most recent version (these instructions were tested with 4.8.1) - Architecture: `x32` or `x64` as appropriate and desired. - Threads: `win32` (not posix) - Exception: `sjlj` (for x32) or `seh` (for x64). Do not choose dwarf2. - Build revision: most recent available (tested with 5) 3. Do **not** install to a directory with spaces in the name. You will have to change the default installation path, for example, - `C:\mingw-builds\x64-4.8.1-win32-seh-rev5` for 64 bits - `C:\mingw-builds\x32-4.8.1-win32-sjlj-rev5` for 32 bits 4. Install and configure [MSYS2](http://sourceforge.net/projects/msys2), a minimal POSIX-like environment for Windows. 1. Download the latest base [32-bit](http://sourceforge.net/projects/msys2/files/Base/i686/) or [64-bit](http://sourceforge.net/projects/msys2/files/Base/x86_64/) distribution, consistent with the architecture you chose for MinGW-builds. The archive will have a name like `msys2-base-x86_64-yyyymmdd.tar.xz` and these instructions were tested with `msys2-base-x86_64-20140216.tar.xz`. 2. Using [7-Zip](http://www.7-zip.org/download.html), extract the archive to any convenient directory. - *N.B.* Some versions of this archive contain zero-byte files that clash with existing files. If prompted, choose **not** to overwrite existing files. - You may need to extract the tarball in a separate step. This will create an `msys32` or `msys64` directory, according to the architecture you chose. - Move the `msys32` or `msys64` directory into your MinGW-builds directory, which is `C:\mingw-builds` if you followed the suggestions in step 3. We will omit the "32" or "64" in the steps below and refer to this as "the msys directory". 3. Double-click `msys2_shell.bat` in the msys directory. This will initialize MSYS2. The shell will tell you to `exit` and restart the shell. For now, ignore it. 4. Update MSYS2 and install packages required to build julia, using the `pacman` package manager included in MSYS2: ``` pacman-key --init #Download keys pacman -Syu #Update package database and full system upgrade ``` Now `exit` the MSYS2 shell and restart it, *even if you already restarted it above*. This is necessary in case the system upgrade updated the main MSYS2 libs. Reopen the MSYS2 shell and continue with: ``` pacman -S diffutils git m4 make patch tar msys/openssh ``` 5. Configure your MSYS2 shell for convenience: ``` echo "mount C:/Python27 /python" >> ~/.bashrc # uncomment ONE of the following two lines #echo "mount C:/mingw-builds/x64-4.8.1-win32-seh-rev5/mingw64 /mingw" >> ~/.bashrc #echo "mount C:/mingw-builds/x32-4.8.1-win32-sjlj-rev5/mingw32 /mingw" >> ~/.bashrc echo "export PATH=/usr/local/bin:/usr/bin:/opt/bin:/mingw/bin:/python" >> ~/.bashrc ``` *N.B.* The `export` clobbers whatever `$PATH` is already defined. This is suggested to avoid path-masking. If you use MSYS2 for purposes other than building Julia, you may prefer to append rather than clobber. *N.B.* All of the path-separators in the mount commands are unix-style. 6. Configuration of the toolchain is complete. Now `exit` the MSYS2 shell. 5. Build Julia and its dependencies from source. 1. Relaunch the MSYS2 shell and type ``` . ~/.bashrc # Some versions of MSYS2 do not run this automatically ``` Ignore any warnings you see from `mount` about `/mingw` and `/python` not existing. 2. Get the Julia sources and start the build: ``` git clone https://github.com/JuliaLang/julia.git cd julia make -j 4 # Adjust the number of cores (4) to match your build environment. ``` 3. The Julia build can (as of 2014-02-28) fail after building OpenBLAS. This appears (?) to be a result of the OpenBLAS build trying to run the Microsoft Visual C++ `lib.exe` tool -- which we don't need to do -- without checking for its existence. This uncaught error kills the Julia build. If this happens, follow the instructions in the helpful error message and continue the build, *viz.* ``` cd deps/openblas-v0.2.9.rc1 # This path will depend on the version of OpenBLAS. make install cd ../.. make -j 4 # Adjust the number of cores (4) to match your build environment. ``` 4. Some versions of PCRE (*e.g.* 8.31) will compile correctly but fail a test. This will cause the Julia build to fail. To circumvent testing for PCRE and allow the rest of the build to continue, ``` touch deps/pcre-8.31/checked # This path will depend on the version of PCRE. make -j 4 # Adjust the number of cores (4) to match your build environment. ``` 6. Setup Package Development Environment 1. The `Pkg` module in Base provides many convenient tools for [developing and publishing packages](http://docs.julialang.org/en/latest/manual/packages/). One of the packages added through pacman above was `openssh`, which will allow secure access to GitHub APIs. Follow GitHub's [guide](https://help.github.com/articles/generating-ssh-keys) to setting up SSH keys to ensure your local machine can communicate with GitHub effectively. 5. In case of the issues with building packages (i.e. ICU fails to build with the following error message ```error compiling xp_parse: error compiling xp_make_parser: could not load module libexpat-1: %```) run ```make win-extras``` and then copy everything from the ```dist-extras``` folder into ```usr/bin```. ## Building on Windows with MinGW-builds/MSYS ### The MSYS build of `make` is fragile and may not reliably support parallel builds. Use MSYS2 as described above, if you can. If you must use MSYS, take care to notice the special comments in this section. 1. Install [7-Zip](http://www.7-zip.org/download.html). 2. Install [Python 2.x](http://www.python.org/download/releases). Do **not** install Python 3. 3. Install [MinGW-builds](http://sourceforge.net/projects/mingwbuilds/), a Windows port of GCC. as follows. Do **not** use the regular MinGW distribution. 1. Download the [MinGW-builds installer](http://downloads.sourceforge.net/project/mingwbuilds/mingw-builds-install/mingw-builds-install.exe). 2. Run the installer. When prompted, choose: - Version: the most recent version (these instructions were tested with 4.8.1) - Architecture: x32 or x64 as appropriate and desired. - Threads: win32 (not posix) - Exception: sjlj (for x32) or seh (for x64). Do not choose dwarf2. - Build revision: most recent available (tested with 5) 3. Do **not** install to a directory with spaces in the name. You will have to change the default installation path. The following instructions will assume `C:\mingw-builds\x64-4.8.1-win32-seh-rev5\mingw64`. 4. Download and extract the [MSYS distribution for MinGW-builds](http://sourceforge.net/projects/mingwbuilds/files/external-binary-packages/) (e.g. msys+7za+wget+svn+git+mercurial+cvs-rev13.7z) to a directory *without* spaces in the name, e.g. `C:/mingw-builds/msys`. 5. Download the [MSYS distribution of make](http://sourceforge.net/projects/mingw/files/MSYS/Base/make) and use this `make.exe` to replace the one in the `mingw64\bin` subdirectory of the MinGW-builds installation. 6. Run the `msys.bat` installed in Step 4. Set up MSYS by running at the MSYS prompt: ``` mount C:/mingw-builds/x64-4.8.1-win32-seh-rev5/mingw64 /mingw mount C:/Python27 /python export PATH=$PATH:/mingw/bin:/python ``` Replace the directories as appropriate. 7. Download the Julia source repository and build it ``` git clone https://github.com/JuliaLang/julia.git cd julia make ``` *Tips:* - The MSYS build of `make` is fragile and will occasionally corrupt the build process. You can minimize the changes of this occurring by only running `make` in serial, i.e. avoid the `-j` argument. - When the build process fails for no apparent reason, try running `make` again. - Sometimes, `make` will appear to hang, consuming 100% cpu but without apparent progress. If this happens, kill `make` from the Task Manager and try again. - Expect this to take a very long time (dozens of hours is not uncommon). - If `make` fails complaining that `./flisp/flisp` is not found, force `make` to build FemtoLisp before Julia by running `make -C src/flisp && make`. 8. Run Julia with _either_ of: - Using `make` ``` make run-julia ``` (the full syntax is `make run-julia[-release|-debug]`) - Using the Julia executables directly ``` usr/bin/julia ``` ## Cross-compiling If you prefer to cross-compile, the following steps should get you started. ### Ubuntu and Mac Dependencies (these steps will work for almost any linux platform) First, you will need to ensure your system has the required dependencies. We need wine (>=1.7.5), a system compiler, and some downloaders. On Ubuntu: apt-add-repository ppa:ubuntu-wine/ppa apt-get upate apt-get install wine1.7 subversion cvs gcc wget p7zip-full On Mac: Install XCode, XCode command line tools, X11 (now [XQuartz](http://xquartz.macosforge.org/)), and [MacPorts](http://www.macports.org/install.php) or [Homebrew](http://mxcl.github.io/homebrew/). Then run ```port install wine wget``` or ```brew install wine wget```, as appropriate. On Both: Unfortunately, the version of gcc installed by Ubuntu is currently 4.6, which does not compile OpenBLAS correctly. On Mac, the situation is the same: the version in MacPorts is very old and Homebrew does not have it. So first we need to get a cross-compile version of gcc. Most binary packages appear to not include gfortran, so we will need to compile it from source (or ask @vtjnash to send you a tgz of his build). This is typically quite a bit of work, so we will use [this script](https://code.google.com/p/mingw-w64-dgn/) to make it easy. 1. `svn checkout http://mingw-w64-dgn.googlecode.com/svn/trunk/ mingw-w64-dgn` 2. `cd mingw-w64-dgn` 3. edit `rebuild_cross.sh` and make the following two changes: a. uncomment `export MAKE_OPT="-j 2"`, if appropriate for your machine b. add `fortran` to the end of `--enable-languages=c,c++,objc,obj-c++` 5. `bash update_source.sh` 4. `bash rebuild_cross.sh` 5. `mv cross ~/cross-w64` 6. `export PATH=$HOME/cross-w64/bin:$PATH` # NOTE: it is important that you remember to always do this before using make in the following steps!, you can put this line in your .profile to make it easy Then we can essentially just repeat these steps for the 32-bit compiler, reusing some of the work: 7. `cd ..` 8. `cp -a mingw-w64-dgn mingw-w32-dgn` 9. `cd mingw-w32-dgn` 10. `rm -r cross build` 11. `bash rebuild_cross.sh 32r` 12. `mv cross ~/cross-w32` 13. `export PATH=$HOME/cross-w32/bin:$PATH` # NOTE: it is important that you remember to always do this before using make in the following steps!, you can put this line in your .profile to make it easy Note: for systems that support rpm-based package managers, the OpenSUSE build service appears to contain a fully up-to-date versions of the necessary dependencies. ### Arch Linux Dependencies 1. Install the following packages from the official Arch repository: `sudo pacman -S cloog gcc-ada libmpc p7zip ppl subversion zlib` 2. The rest of the prerequisites consist of the mingw-w64 packages, which are available in the AUR Arch repository. They must be installed exactly in the order they are given or else their installation will fail. The `yaourt` package manager is used for illustration purposes; you may instead follow the [Arch instructions for installing packages from AUR](https://wiki.archlinux.org/index.php/Arch_User_Repository#Installing_packages) or may use your preferred package manager. To start with, install `mingw-w64-binutils` via the command `yaourt -S mingw-w64-binutils` 3. `yaourt -S mingw-w64-headers-svn` 4. `yaourt -S mingw-w64-headers-bootstrap` 5. `yaourt -S mingw-w64-gcc-base` 6. `yaourt -S mingw-w64-crt-svn` 7. Remove `mingw-w64-headers-bootstrap` without removing its dependent mingw-w64 installed packages by using the command `yaourt -Rdd mingw-w64-headers-bootstrap` 8. `yaourt -S mingw-w64-winpthreads` 9. Remove `mingw-w64-gcc-base` without removing its installed mingw-w64 dependencies: `yaourt -Rdd mingw-w64-gcc-base` 10. Complete the installation of the required `mingw-w64` packages: `yaourt -S mingw-w64-gcc` ### Cross-building Julia Finally, the build and install process for Julia: 1. `git clone https://github.com/JuliaLang/julia.git julia-win32` 2. `echo override XC_HOST = i686-w64-mingw32 >> Make.user` 3. `make` 4. `make win-extras` (Necessary before running `make dist`p) 5. `make dist` 6. move the julia-* directory / zip file to the target machine If you are building for 64-bit windows, the steps are essentially the same. Just replace i686 in XC_HOST with x86_64. (note: on Mac, wine only runs in 32-bit mode) ## Windows Build Debugging ### Build process is slow/eats memory/hangs my computer - Disable the Windows [Superfetch](http://en.wikipedia.org/wiki/Windows_Vista_I/O_technologies#SuperFetch) and [Program Compatibility Assistant](http://blogs.msdn.com/b/cjacks/archive/2011/11/22/managing-the-windows-7-program-compatibility-assistant-pca.aspx) services, as they are known to have [spurious interactions]((https://cygwin.com/ml/cygwin/2011-12/msg00058.html)) with MinGW/Cygwin. As mentioned in the link above: excessive memory use by `svchost` specifically may be investigated in the Task Manager by clicking on the high-memory `svchost.exe` process and selecting `Go to Services`. Disable child services one-by-one until a culprit is found. - Beware of [BLODA](https://cygwin.com/faq/faq.html#faq.using.bloda) The [vmmap](http://technet.microsoft.com/en-us/sysinternals/dd535533.aspx) tool is indispensable for identifying such software conflicts. Use vmmap to inspect the list of loaded DLLs for bash, mintty, or another persistent process used to drive the build. Essentially *any* DLL outside of the Windows System directory is potential BLODA.
shubhamg31/columbus_julia
lib/julia/README.windows.md
Markdown
apache-2.0
17,806
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.console.configcreator; import java.io.File; import javax.enterprise.deploy.shared.factories.DeploymentFactoryManager; import javax.enterprise.deploy.spi.DeploymentManager; import javax.enterprise.deploy.spi.Target; import javax.enterprise.deploy.spi.status.ProgressObject; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.portlet.PortletException; import javax.portlet.PortletRequest; import org.apache.geronimo.deployment.plugin.jmx.CommandContext; import org.apache.geronimo.deployment.plugin.jmx.JMXDeploymentManager; import org.apache.geronimo.deployment.plugin.local.DistributeCommand; import org.apache.geronimo.j2ee.deployment.ApplicationInfo; import org.apache.geronimo.j2ee.deployment.EARConfigBuilder; import org.apache.geronimo.kernel.Kernel; import org.apache.geronimo.kernel.KernelRegistry; /** * Util class for JSR-88 related functions * * @version $Rev$ $Date$ */ public class JSR88_Util { /*private static List getEjbClassLoaders(PortletRequest request) { List deployedEjbs = JSR77_Util.getDeployedEJBs(request); List configurations = new ArrayList(); for (int i = 0; i < deployedEjbs.size(); i++) { String ejbPatternName = ((ReferredData) deployedEjbs.get(i)).getPatternName(); configurations.add(getDependencyString(ejbPatternName)); } return getConfigClassLoaders(configurations); } private static List getConfigClassLoaders(List configurationNames) { List classLoaders = new ArrayList(); ConfigurationManager configurationManager = PortletManager.getConfigurationManager(); for (int i = 0; i < configurationNames.size(); i++) { Artifact configurationId = Artifact.create((String) configurationNames.get(i)); classLoaders.add(configurationManager.getConfiguration(configurationId).getConfigurationClassLoader()); } return classLoaders; }*/ public static ApplicationInfo createApplicationInfo(PortletRequest actionRequest, File moduleFile) { ApplicationInfo applicationInfo = null; EARConfigBuilder.createPlanMode.set(Boolean.TRUE); try { DeploymentFactoryManager dfm = DeploymentFactoryManager.getInstance(); DeploymentManager mgr = dfm.getDeploymentManager("deployer:geronimo:inVM", null, null); if (mgr instanceof JMXDeploymentManager) { ((JMXDeploymentManager) mgr).setLogConfiguration(false, true); } Target[] targets = mgr.getTargets(); if (null == targets) { throw new IllegalStateException("No target to distribute to"); } targets = new Target[] { targets[0] }; DistributeCommand command = new DistributeCommand(getKernel(), targets, moduleFile, null); CommandContext commandContext = new CommandContext(true, true, null, null, false); commandContext.setUsername("system"); commandContext.setPassword("manager"); command.setCommandContext(commandContext); command.doDeploy(targets[0], true); } catch (Exception e) { // Any better ideas? if(EARConfigBuilder.appInfo.get() == null) throw new RuntimeException(e); } finally { EARConfigBuilder.createPlanMode.set(Boolean.FALSE); applicationInfo = EARConfigBuilder.appInfo.get(); EARConfigBuilder.appInfo.set(null); } return applicationInfo; } private static Kernel getKernel() { // todo: consider making this configurable; we could easily connect to a remote kernel if we wanted to Kernel kernel = null; try { kernel = (Kernel) new InitialContext().lookup("java:comp/GeronimoKernel"); } catch (NamingException e) { // log.error("Unable to look up kernel in JNDI", e); } if (kernel == null) { // log.debug("Unable to find kernel in JNDI; using KernelRegistry instead"); kernel = KernelRegistry.getSingleKernel(); } return kernel; } public static String[] deploy(PortletRequest actionRequest, File moduleFile, File planFile) throws PortletException { // TODO this is a duplicate of the code from // org.apache.geronimo.console.configmanager.DeploymentPortlet.processAction() // TODO need to eliminate this duplicate code DeploymentFactoryManager dfm = DeploymentFactoryManager.getInstance(); String[] statusMsgs = new String[2]; try { DeploymentManager mgr = dfm.getDeploymentManager("deployer:geronimo:inVM", null, null); try { if (mgr instanceof JMXDeploymentManager) { ((JMXDeploymentManager) mgr).setLogConfiguration(false, true); } Target[] targets = mgr.getTargets(); if (null == targets) { throw new IllegalStateException("No target to distribute to"); } targets = new Target[] { targets[0] }; ProgressObject progress = mgr.distribute(targets, moduleFile, planFile); while (progress.getDeploymentStatus().isRunning()) { Thread.sleep(100); } if (progress.getDeploymentStatus().isCompleted()) { progress = mgr.start(progress.getResultTargetModuleIDs()); while (progress.getDeploymentStatus().isRunning()) { Thread.sleep(100); } statusMsgs[0] = "infoMsg01"; } else { statusMsgs[0] = "errorMsg02"; statusMsgs[1] = progress.getDeploymentStatus().getMessage(); } } finally { mgr.release(); } } catch (Exception e) { throw new PortletException(e); } return statusMsgs; } }
apache/geronimo
plugins/plancreator/plancreator-portlets/src/main/java/org/apache/geronimo/console/configcreator/JSR88_Util.java
Java
apache-2.0
6,904
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_191) on Fri Dec 21 13:21:36 PST 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Constant Field Values (guacamole-ext 1.0.0 API)</title> <meta name="date" content="2018-12-21"> <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style"> <script type="text/javascript" src="script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Constant Field Values (guacamole-ext 1.0.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="overview-tree.html">Tree</a></li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="index-all.html">Index</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="index.html?constant-values.html" target="_top">Frames</a></li> <li><a href="constant-values.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Constant Field Values" class="title">Constant Field Values</h1> <h2 title="Contents">Contents</h2> <ul> <li><a href="#org.apache">org.apache.*</a></li> </ul> </div> <div class="constantValuesContainer"><a name="org.apache"> <!-- --> </a> <h2 title="org.apache">org.apache.*</h2> <ul class="blockList"> <li class="blockList"> <table class="constantsSummary" border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>org.apache.guacamole.form.<a href="org/apache/guacamole/form/DateField.html" title="class in org.apache.guacamole.form">DateField</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="org.apache.guacamole.form.DateField.FORMAT"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/form/DateField.html#FORMAT">FORMAT</a></code></td> <td class="colLast"><code>"yyyy-MM-dd"</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="constantsSummary" border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>org.apache.guacamole.form.<a href="org/apache/guacamole/form/TimeField.html" title="class in org.apache.guacamole.form">TimeField</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="org.apache.guacamole.form.TimeField.FORMAT"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/form/TimeField.html#FORMAT">FORMAT</a></code></td> <td class="colLast"><code>"HH:mm:ss"</code></td> </tr> </tbody> </table> </li> </ul> <ul class="blockList"> <li class="blockList"> <table class="constantsSummary" border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>org.apache.guacamole.net.auth.<a href="org/apache/guacamole/net/auth/AbstractUserContext.html" title="class in org.apache.guacamole.net.auth">AbstractUserContext</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="org.apache.guacamole.net.auth.AbstractUserContext.DEFAULT_ROOT_CONNECTION_GROUP"> <!-- --> </a><code>protected&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/net/auth/AbstractUserContext.html#DEFAULT_ROOT_CONNECTION_GROUP">DEFAULT_ROOT_CONNECTION_GROUP</a></code></td> <td class="colLast"><code>"ROOT"</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="constantsSummary" border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>org.apache.guacamole.net.auth.<a href="org/apache/guacamole/net/auth/AuthenticatedUser.html" title="interface in org.apache.guacamole.net.auth">AuthenticatedUser</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="org.apache.guacamole.net.auth.AuthenticatedUser.ANONYMOUS_IDENTIFIER"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/net/auth/AuthenticatedUser.html#ANONYMOUS_IDENTIFIER">ANONYMOUS_IDENTIFIER</a></code></td> <td class="colLast"><code>""</code></td> </tr> </tbody> </table> </li> </ul> <ul class="blockList"> <li class="blockList"> <table class="constantsSummary" border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>org.apache.guacamole.token.<a href="org/apache/guacamole/token/StandardTokens.html" title="class in org.apache.guacamole.token">StandardTokens</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="org.apache.guacamole.token.StandardTokens.CLIENT_ADDRESS_TOKEN"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/token/StandardTokens.html#CLIENT_ADDRESS_TOKEN">CLIENT_ADDRESS_TOKEN</a></code></td> <td class="colLast"><code>"GUAC_CLIENT_ADDRESS"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="org.apache.guacamole.token.StandardTokens.CLIENT_HOSTNAME_TOKEN"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/token/StandardTokens.html#CLIENT_HOSTNAME_TOKEN">CLIENT_HOSTNAME_TOKEN</a></code></td> <td class="colLast"><code>"GUAC_CLIENT_HOSTNAME"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="org.apache.guacamole.token.StandardTokens.DATE_TOKEN"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/token/StandardTokens.html#DATE_TOKEN">DATE_TOKEN</a></code></td> <td class="colLast"><code>"GUAC_DATE"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="org.apache.guacamole.token.StandardTokens.PASSWORD_TOKEN"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/token/StandardTokens.html#PASSWORD_TOKEN">PASSWORD_TOKEN</a></code></td> <td class="colLast"><code>"GUAC_PASSWORD"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="org.apache.guacamole.token.StandardTokens.TIME_TOKEN"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/token/StandardTokens.html#TIME_TOKEN">TIME_TOKEN</a></code></td> <td class="colLast"><code>"GUAC_TIME"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="org.apache.guacamole.token.StandardTokens.USERNAME_TOKEN"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/token/StandardTokens.html#USERNAME_TOKEN">USERNAME_TOKEN</a></code></td> <td class="colLast"><code>"GUAC_USERNAME"</code></td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="overview-tree.html">Tree</a></li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="index-all.html">Index</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="index.html?constant-values.html" target="_top">Frames</a></li> <li><a href="constant-values.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2018. All rights reserved.</small></p> <!-- Google Analytics --> <script type="text/javascript"> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-75289145-1', 'auto'); ga('send', 'pageview'); </script> </body> </html>
mike-jumper/incubator-guacamole-website
doc/1.0.0/guacamole-ext/constant-values.html
HTML
apache-2.0
12,352
package cmdserver_test import ( "testing" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func TestCmdServer(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "CmdServer Suite") }
fabiand/kubevirt
pkg/virt-launcher/virtwrap/cmd-server/cmd_server_suite_test.go
GO
apache-2.0
200
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.eas.widgets.containers; import com.eas.core.XElement; import com.google.gwt.dom.client.Style; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.RequiresResize; import com.google.gwt.user.client.ui.Widget; /** * * @author mg */ public class FlowGapPanel extends FlowPanel implements RequiresResize { protected int hgap; protected int vgap; public FlowGapPanel() { super(); getElement().<XElement>cast().addResizingTransitionEnd(this); getElement().getStyle().setLineHeight(0, Style.Unit.PX); } public int getHgap() { return hgap; } public void setHgap(int aValue) { hgap = aValue; for (int i = 0; i < getWidgetCount(); i++) { Widget w = getWidget(i); w.getElement().getStyle().setMarginLeft(hgap, Style.Unit.PX); } } public int getVgap() { return vgap; } public void setVgap(int aValue) { vgap = aValue; for (int i = 0; i < getWidgetCount(); i++) { Widget w = getWidget(i); w.getElement().getStyle().setMarginTop(vgap, Style.Unit.PX); } } @Override public void add(Widget w) { w.getElement().getStyle().setMarginLeft(hgap, Style.Unit.PX); w.getElement().getStyle().setMarginTop(vgap, Style.Unit.PX); w.getElement().getStyle().setDisplay(Style.Display.INLINE_BLOCK); w.getElement().getStyle().setVerticalAlign(Style.VerticalAlign.BOTTOM); super.add(w); } @Override public void onResize() { // reserved for future use. } }
jskonst/PlatypusJS
web-client/src/platypus/src/com/eas/widgets/containers/FlowGapPanel.java
Java
apache-2.0
1,696
package org.cohorte.herald.core.utils; import java.util.Iterator; import org.cohorte.herald.Message; import org.cohorte.herald.MessageReceived; import org.jabsorb.ng.JSONSerializer; import org.jabsorb.ng.serializer.MarshallException; import org.jabsorb.ng.serializer.UnmarshallException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class MessageUtils { /** The Jabsorb serializer */ private static JSONSerializer pSerializer = new JSONSerializer(); static { try { pSerializer.registerDefaultSerializers(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static String toJSON(Message aMsg) throws MarshallException { JSONObject json = new JSONObject(); try { // headers JSONObject headers = new JSONObject(); for (String key : aMsg.getHeaders().keySet()) { headers.put(key, aMsg.getHeaders().get(key)); } json.put(Message.MESSAGE_HEADERS, headers); // subject json.put(Message.MESSAGE_SUBJECT, aMsg.getSubject()); // content if (aMsg.getContent() != null) { if (aMsg.getContent() instanceof String) { json.put(Message.MESSAGE_CONTENT, aMsg.getContent()); } else { JSONObject content = new JSONObject(pSerializer.toJSON(aMsg.getContent())); json.put(Message.MESSAGE_CONTENT, content); } } // metadata JSONObject metadata = new JSONObject(); for (String key : aMsg.getMetadata().keySet()) { metadata.put(key, aMsg.getMetadata().get(key)); } json.put(Message.MESSAGE_METADATA, metadata); } catch (JSONException e) { e.printStackTrace(); return null; } return json.toString(); } @SuppressWarnings("unchecked") public static MessageReceived fromJSON(String json) throws UnmarshallException { try { JSONObject wParsedMsg = new JSONObject(json); { try { // check if valid herald message (respects herald specification version) int heraldVersion = -1; JSONObject jHeader = wParsedMsg.getJSONObject(Message.MESSAGE_HEADERS); if (jHeader != null) { if (jHeader.has(Message.MESSAGE_HERALD_VERSION)) { heraldVersion = jHeader.getInt(Message.MESSAGE_HERALD_VERSION); } } if (heraldVersion != Message.HERALD_SPECIFICATION_VERSION) { throw new JSONException("Herald specification of the received message is not supported!"); } MessageReceived wMsg = new MessageReceived( wParsedMsg.getJSONObject(Message.MESSAGE_HEADERS).getString(Message.MESSAGE_HEADER_UID), wParsedMsg.getString(Message.MESSAGE_SUBJECT), null, null, null, null, null, null); // content Object cont = wParsedMsg.opt(Message.MESSAGE_CONTENT); if (cont != null) { if (cont instanceof JSONObject || cont instanceof JSONArray) { wMsg.setContent(pSerializer.fromJSON(cont.toString())); } else wMsg.setContent(cont); } else { wMsg.setContent(null); } // headers Iterator<String> wKeys; if (wParsedMsg.getJSONObject(Message.MESSAGE_HEADERS) != null) { wKeys = wParsedMsg.getJSONObject(Message.MESSAGE_HEADERS).keys(); while(wKeys.hasNext()) { String key = wKeys.next(); wMsg.addHeader(key, wParsedMsg.getJSONObject(Message.MESSAGE_HEADERS).get(key)); } } // metadata Iterator<String> wKeys2; if (wParsedMsg.getJSONObject(Message.MESSAGE_METADATA) != null) { wKeys2 = wParsedMsg.getJSONObject(Message.MESSAGE_METADATA).keys(); while(wKeys2.hasNext()) { String key = wKeys2.next(); wMsg.addMetadata(key, wParsedMsg.getJSONObject(Message.MESSAGE_METADATA).get(key)); } } return wMsg; } catch (JSONException e) { e.printStackTrace(); return null; } } } catch (Exception e) { e.printStackTrace(); return null; } } }
isandlaTech/cohorte-herald
java/org.cohorte.herald.core/src/org/cohorte/herald/core/utils/MessageUtils.java
Java
apache-2.0
4,164
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cache.annotation; import java.util.Collection; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.CacheManager; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportAware; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; /** * Abstract base {@code @Configuration} class providing common structure for enabling * Spring's annotation-driven cache management capability. * * @author Chris Beams * @since 3.1 * @see EnableCaching */ @Configuration public abstract class AbstractCachingConfiguration implements ImportAware { protected AnnotationAttributes enableCaching; protected CacheManager cacheManager; protected KeyGenerator keyGenerator; @Autowired(required=false) private Collection<CacheManager> cacheManagerBeans; @Autowired(required=false) private Collection<CachingConfigurer> cachingConfigurers; @Override public void setImportMetadata(AnnotationMetadata importMetadata) { this.enableCaching = AnnotationAttributes.fromMap( importMetadata.getAnnotationAttributes(EnableCaching.class.getName(), false)); Assert.notNull(this.enableCaching, "@EnableCaching is not present on importing class " + importMetadata.getClassName()); } /** * Determine which {@code CacheManager} bean to use. Prefer the result of * {@link CachingConfigurer#cacheManager()} over any by-type matching. If none, fall * back to by-type matching on {@code CacheManager}. * @throws IllegalArgumentException if no CacheManager can be found; if more than one * CachingConfigurer implementation exists; if multiple CacheManager beans and no * CachingConfigurer exists to disambiguate. */ @PostConstruct protected void reconcileCacheManager() { if (!CollectionUtils.isEmpty(cachingConfigurers)) { int nConfigurers = cachingConfigurers.size(); if (nConfigurers > 1) { throw new IllegalStateException(nConfigurers + " implementations of " + "CachingConfigurer were found when only 1 was expected. " + "Refactor the configuration such that CachingConfigurer is " + "implemented only once or not at all."); } CachingConfigurer cachingConfigurer = cachingConfigurers.iterator().next(); this.cacheManager = cachingConfigurer.cacheManager(); this.keyGenerator = cachingConfigurer.keyGenerator(); } else if (!CollectionUtils.isEmpty(cacheManagerBeans)) { int nManagers = cacheManagerBeans.size(); if (nManagers > 1) { throw new IllegalStateException(nManagers + " beans of type CacheManager " + "were found when only 1 was expected. Remove all but one of the " + "CacheManager bean definitions, or implement CachingConfigurer " + "to make explicit which CacheManager should be used for " + "annotation-driven cache management."); } CacheManager cacheManager = cacheManagerBeans.iterator().next(); this.cacheManager = cacheManager; // keyGenerator remains null; will fall back to default within CacheInterceptor } else { throw new IllegalStateException("No bean of type CacheManager could be found. " + "Register a CacheManager bean or remove the @EnableCaching annotation " + "from your configuration."); } } }
sunpy1106/SpringBeanLifeCycle
src/main/java/org/springframework/cache/annotation/AbstractCachingConfiguration.java
Java
apache-2.0
4,164
package org.apache.cocoon.transformation; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Map; import java.util.zip.ZipInputStream; import java.util.zip.ZipEntry; import org.apache.avalon.framework.parameters.Parameters; import org.apache.cocoon.ProcessingException; import org.apache.cocoon.environment.SourceResolver; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * This transformer downloads a new file to disk. * <p> * It triggers for elements in the namespace "http://apache.org/cocoon/download/1.0". * Attributes: * @src : the file that should be downloaded * @target (optional): path where the file should be stored (includes filename) * @target-dir (optional): directory where the file should be stored * @unzip (optional): if "true" then unzip file after downloading. * If there is no @target or @target-dir attribute a temporary file is created. * <p> * Example XML input: * <pre> * {@code * <download:download src="http://some.server.com/zipfile.zip" * target="/tmp/zipfile.zip" unzip="true"/> * } * </pre> * The @src specifies the file that should be downloaded. The * @target specifies where the file should be stored. @unzip is true, so the * file will be unzipped immediately. * <p> * The result is * <pre> * {@code * <download:result unzipped="/path/to/unzipped/file/on/disk">/path/to/file/on/disk</download:result> * } * </pre> * (@unzipped is only present when @unzip="true") or * <pre> * {@code * <download:error>The error message</download:file> * } * </pre> * if an error (other than a HTTP error) occurs. * HTTP errors are thrown. * Define this transformer in the sitemap: * <pre> * {@code * <map:components> * <map:transformers> * <map:transformer name="download" logger="sitemap.transformer.download" * src="org.apache.cocoon.transformation.DownloadTransformer"/> * ... * } * </pre> * Use this transformer: * <pre> * {@code * <map:transform type="download"/> * } * </pre> * * * @author <a href="mailto:maarten.kroon@koop.overheid.nl">Maarten Kroon</a> * @author <a href="mailto:hhv@x-scale.nl">Huib Verweij</a> */ public class DownloadTransformer extends AbstractSAXTransformer { public static final String DOWNLOAD_NS = "http://apache.org/cocoon/download/1.0"; public static final String DOWNLOAD_ELEMENT = "download"; private static final String DOWNLOAD_PREFIX = "download"; public static final String RESULT_ELEMENT = "result"; public static final String ERROR_ELEMENT = "error"; public static final String SRC_ATTRIBUTE = "src"; public static final String TARGET_ATTRIBUTE = "target"; public static final String TARGETDIR_ATTRIBUTE = "target-dir"; public static final String UNZIP_ATTRIBUTE = "unzip"; public static final String RECURSIVE_UNZIP_ATTRIBUTE = "recursive-unzip"; public static final String UNZIPPED_ATTRIBUTE = "unzipped"; public DownloadTransformer() { this.defaultNamespaceURI = DOWNLOAD_NS; } @Override public void setup(SourceResolver resolver, Map objectModel, String src, Parameters params) throws ProcessingException, SAXException, IOException { super.setup(resolver, objectModel, src, params); } @Override public void startTransformingElement(String uri, String localName, String qName, Attributes attributes) throws SAXException, ProcessingException, IOException { if (DOWNLOAD_NS.equals(uri) && DOWNLOAD_ELEMENT.equals(localName)) { try { File[] downloadResult = download( attributes.getValue(SRC_ATTRIBUTE), attributes.getValue(TARGETDIR_ATTRIBUTE), attributes.getValue(TARGET_ATTRIBUTE), attributes.getValue(UNZIP_ATTRIBUTE), attributes.getValue(RECURSIVE_UNZIP_ATTRIBUTE) ); File downloadedFile = downloadResult[0]; File unzipDir = downloadResult[1]; String absPath = downloadedFile.getCanonicalPath(); AttributesImpl attrsImpl = new AttributesImpl(); if (unzipDir != null) { attrsImpl.addAttribute("", UNZIPPED_ATTRIBUTE, UNZIPPED_ATTRIBUTE, "CDATA", unzipDir.getAbsolutePath()); } xmlConsumer.startElement(uri, RESULT_ELEMENT, String.format("%s:%s", DOWNLOAD_PREFIX, RESULT_ELEMENT), attrsImpl); xmlConsumer.characters(absPath.toCharArray(), 0, absPath.length()); xmlConsumer.endElement(uri, RESULT_ELEMENT, String.format("%s:%s", DOWNLOAD_PREFIX, RESULT_ELEMENT)); } catch (Exception e) { // throw new SAXException("Error downloading file", e); xmlConsumer.startElement(uri, ERROR_ELEMENT, qName, attributes); String message = e.getMessage(); xmlConsumer.characters(message.toCharArray(), 0, message.length()); xmlConsumer.endElement(uri, ERROR_ELEMENT, qName); } } else { super.startTransformingElement(uri, localName, qName, attributes); } } @Override public void endTransformingElement(String uri, String localName, String qName) throws SAXException, ProcessingException, IOException { if (DOWNLOAD_NS.equals(namespaceURI) && DOWNLOAD_ELEMENT.equals(localName)) { return; } super.endTransformingElement(uri, localName, qName); } private File[] download(String sourceUri, String targetDir, String target, String unzip, String recursiveUnzip) throws ProcessingException, IOException, SAXException { File targetFile; File unZipped = null; if (null != target && !target.equals("")) { targetFile = new File(target); } else if (null != targetDir && !targetDir.equals("")) { targetFile = new File(targetDir); } else { String baseName = FilenameUtils.getBaseName(sourceUri); String extension = FilenameUtils.getExtension(sourceUri); targetFile = File.createTempFile(baseName, "." + extension); } if (!targetFile.getParentFile().exists()) { targetFile.getParentFile().mkdirs(); } boolean unzipFile = (null != unzip && unzip.equals("true")) || (null != recursiveUnzip && recursiveUnzip.equals("true")); String absPath = targetFile.getAbsolutePath(); String unzipDir = unzipFile ? FilenameUtils.removeExtension(absPath) : ""; HttpClient httpClient = new HttpClient(); httpClient.setConnectionTimeout(60000); httpClient.setTimeout(60000); if (System.getProperty("http.proxyHost") != null) { // getLogger().warn("PROXY: "+System.getProperty("http.proxyHost")); String nonProxyHostsRE = System.getProperty("http.nonProxyHosts", ""); if (nonProxyHostsRE.length() > 0) { String[] pHosts = nonProxyHostsRE.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*").split("\\|"); nonProxyHostsRE = ""; for (String pHost : pHosts) { nonProxyHostsRE += "|(^https?://" + pHost + ".*$)"; } nonProxyHostsRE = nonProxyHostsRE.substring(1); } if (nonProxyHostsRE.length() == 0 || !sourceUri.matches(nonProxyHostsRE)) { try { HostConfiguration hostConfiguration = httpClient.getHostConfiguration(); hostConfiguration.setProxy(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort", "80"))); httpClient.setHostConfiguration(hostConfiguration); } catch (Exception e) { throw new ProcessingException("Cannot set proxy!", e); } } } HttpMethod httpMethod = new GetMethod(sourceUri); try { int responseCode = httpClient.executeMethod(httpMethod); if (responseCode < 200 || responseCode >= 300) { throw new ProcessingException(String.format("Received HTTP status code %d (%s)", responseCode, httpMethod.getStatusText())); } OutputStream os = new BufferedOutputStream(new FileOutputStream(targetFile)); try { IOUtils.copyLarge(httpMethod.getResponseBodyAsStream(), os); } finally { os.close(); } } finally { httpMethod.releaseConnection(); } if (!"".equals(unzipDir)) { unZipped = unZipIt(targetFile, unzipDir, recursiveUnzip); } return new File[] {targetFile, unZipped}; } /** * Unzip it * @param zipFile input zip file * @param outputFolder zip file output folder */ private File unZipIt(File zipFile, String outputFolder, String recursiveUnzip){ byte[] buffer = new byte[4096]; File folder = null; try{ //create output directory is not exists folder = new File(outputFolder); if (!folder.exists()){ folder.mkdir(); } //get the zipped file list entry try ( //get the zip file content ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) { //get the zipped file list entry ZipEntry ze = zis.getNextEntry(); while(ze != null){ String fileName = ze.getName(); File newFile = new File(outputFolder + File.separator + fileName); // System.out.println("file unzip : "+ newFile.getAbsoluteFile()); // create all non existing folders // else you will hit FileNotFoundException for compressed folder new File(newFile.getParent()).mkdirs(); try (FileOutputStream fos = new FileOutputStream(newFile)) { int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } } if ((null != recursiveUnzip && "true".equals(recursiveUnzip)) && FilenameUtils.getExtension(fileName).equals("zip")) { unZipIt(newFile, FilenameUtils.concat(outputFolder, FilenameUtils.getBaseName(fileName)), recursiveUnzip); } ze = zis.getNextEntry(); } zis.closeEntry(); } // System.out.println("Done unzipping."); } catch(IOException ex){ ex.printStackTrace(); } return folder; } }
nverwer/cocooncomponents
src/org/apache/cocoon/transformation/DownloadTransformer.java
Java
apache-2.0
11,508
/* * ==================================================================== * 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 software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.hc.client5.testing.sync; import java.io.IOException; import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.UserTokenHandler; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.EndpointDetails; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.io.HttpRequestHandler; import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.protocol.BasicHttpContext; import org.apache.hc.core5.http.protocol.HttpContext; import org.junit.Assert; import org.junit.Test; /** * Test cases for state-ful connections. */ public class TestStatefulConnManagement extends LocalServerTestBase { private static class SimpleService implements HttpRequestHandler { public SimpleService() { super(); } @Override public void handle( final ClassicHttpRequest request, final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { response.setCode(HttpStatus.SC_OK); final StringEntity entity = new StringEntity("Whatever"); response.setEntity(entity); } } @Test public void testStatefulConnections() throws Exception { final int workerCount = 5; final int requestCount = 5; this.server.registerHandler("*", new SimpleService()); this.connManager.setMaxTotal(workerCount); this.connManager.setDefaultMaxPerRoute(workerCount); final UserTokenHandler userTokenHandler = new UserTokenHandler() { @Override public Object getUserToken(final HttpRoute route, final HttpContext context) { final String id = (String) context.getAttribute("user"); return id; } }; this.clientBuilder.setUserTokenHandler(userTokenHandler); final HttpHost target = start(); final HttpClientContext[] contexts = new HttpClientContext[workerCount]; final HttpWorker[] workers = new HttpWorker[workerCount]; for (int i = 0; i < contexts.length; i++) { final HttpClientContext context = HttpClientContext.create(); contexts[i] = context; workers[i] = new HttpWorker( "user" + i, context, requestCount, target, this.httpclient); } for (final HttpWorker worker : workers) { worker.start(); } for (final HttpWorker worker : workers) { worker.join(LONG_TIMEOUT.toMillis()); } for (final HttpWorker worker : workers) { final Exception ex = worker.getException(); if (ex != null) { throw ex; } Assert.assertEquals(requestCount, worker.getCount()); } for (final HttpContext context : contexts) { final String state0 = (String) context.getAttribute("r0"); Assert.assertNotNull(state0); for (int r = 1; r < requestCount; r++) { Assert.assertEquals(state0, context.getAttribute("r" + r)); } } } static class HttpWorker extends Thread { private final String uid; private final HttpClientContext context; private final int requestCount; private final HttpHost target; private final CloseableHttpClient httpclient; private volatile Exception exception; private volatile int count; public HttpWorker( final String uid, final HttpClientContext context, final int requestCount, final HttpHost target, final CloseableHttpClient httpclient) { super(); this.uid = uid; this.context = context; this.requestCount = requestCount; this.target = target; this.httpclient = httpclient; this.count = 0; } public int getCount() { return this.count; } public Exception getException() { return this.exception; } @Override public void run() { try { this.context.setAttribute("user", this.uid); for (int r = 0; r < this.requestCount; r++) { final HttpGet httpget = new HttpGet("/"); final ClassicHttpResponse response = this.httpclient.execute( this.target, httpget, this.context); this.count++; final EndpointDetails endpointDetails = this.context.getEndpointDetails(); final String connuid = Integer.toHexString(System.identityHashCode(endpointDetails)); this.context.setAttribute("r" + r, connuid); EntityUtils.consume(response.getEntity()); } } catch (final Exception ex) { this.exception = ex; } } } @Test public void testRouteSpecificPoolRecylcing() throws Exception { // This tests what happens when a maxed connection pool needs // to kill the last idle connection to a route to build a new // one to the same route. final int maxConn = 2; this.server.registerHandler("*", new SimpleService()); this.connManager.setMaxTotal(maxConn); this.connManager.setDefaultMaxPerRoute(maxConn); final UserTokenHandler userTokenHandler = new UserTokenHandler() { @Override public Object getUserToken(final HttpRoute route, final HttpContext context) { return context.getAttribute("user"); } }; this.clientBuilder.setUserTokenHandler(userTokenHandler); final HttpHost target = start(); // Bottom of the pool : a *keep alive* connection to Route 1. final HttpContext context1 = new BasicHttpContext(); context1.setAttribute("user", "stuff"); final ClassicHttpResponse response1 = this.httpclient.execute( target, new HttpGet("/"), context1); EntityUtils.consume(response1.getEntity()); // The ConnPoolByRoute now has 1 free connection, out of 2 max // The ConnPoolByRoute has one RouteSpcfcPool, that has one free connection // for [localhost][stuff] Thread.sleep(100); // Send a very simple HTTP get (it MUST be simple, no auth, no proxy, no 302, no 401, ...) // Send it to another route. Must be a keepalive. final HttpContext context2 = new BasicHttpContext(); final ClassicHttpResponse response2 = this.httpclient.execute( new HttpHost("127.0.0.1", this.server.getPort()), new HttpGet("/"), context2); EntityUtils.consume(response2.getEntity()); // ConnPoolByRoute now has 2 free connexions, out of its 2 max. // The [localhost][stuff] RouteSpcfcPool is the same as earlier // And there is a [127.0.0.1][null] pool with 1 free connection Thread.sleep(100); // This will put the ConnPoolByRoute to the targeted state : // [localhost][stuff] will not get reused because this call is [localhost][null] // So the ConnPoolByRoute will need to kill one connection (it is maxed out globally). // The killed conn is the oldest, which means the first HTTPGet ([localhost][stuff]). // When this happens, the RouteSpecificPool becomes empty. final HttpContext context3 = new BasicHttpContext(); final ClassicHttpResponse response3 = this.httpclient.execute( target, new HttpGet("/"), context3); // If the ConnPoolByRoute did not behave coherently with the RouteSpecificPool // this may fail. Ex : if the ConnPool discared the route pool because it was empty, // but still used it to build the request3 connection. EntityUtils.consume(response3.getEntity()); } }
UlrichColby/httpcomponents-client
httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestStatefulConnManagement.java
Java
apache-2.0
9,740
package droidkit.app; import android.content.Intent; import android.net.Uri; import android.support.annotation.NonNull; import java.util.Locale; /** * @author Daniel Serdyukov */ public final class MapsIntent { private static final String MAPS_URL = "https://maps.google.com/maps"; private MapsIntent() { } @NonNull public static Intent openMaps() { return new Intent(Intent.ACTION_VIEW, Uri.parse(MAPS_URL)); } @NonNull public static Intent openMaps(double lat, double lng) { return new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(Locale.US, MAPS_URL + "?q=%f,%f", lat, lng))); } @NonNull public static Intent route(double lat, double lng) { return new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(Locale.US, MAPS_URL + "?daddr=%f,%f", lat, lng))); } @NonNull public static Intent route(double fromLat, double fromLng, double toLat, double toLng) { return new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(Locale.US, MAPS_URL + "?saddr=%f,%f&daddr=%f,%f", fromLat, fromLng, toLat, toLng))); } @NonNull public static Intent search(@NonNull String query) { return new Intent(Intent.ACTION_VIEW, Uri.parse(MAPS_URL + "?q=" + query)); } }
DanielSerdyukov/droidkit-4.x
library/src/main/java/droidkit/app/MapsIntent.java
Java
apache-2.0
1,295
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.test; import com.google.common.base.Joiner; import org.apache.commons.cli.CommandLine; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HRegionLocation; import org.apache.hadoop.hbase.IntegrationTestingUtility; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.replication.ReplicationAdmin; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.replication.ReplicationPeerConfig; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; import java.util.TreeSet; import java.util.UUID; /** * This is an integration test for replication. It is derived off * {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList} that creates a large circular * linked list in one cluster and verifies that the data is correct in a sink cluster. The test * handles creating the tables and schema and setting up the replication. */ public class IntegrationTestReplication extends IntegrationTestBigLinkedList { protected String sourceClusterIdString; protected String sinkClusterIdString; protected int numIterations; protected int numMappers; protected long numNodes; protected String outputDir; protected int numReducers; protected int generateVerifyGap; protected Integer width; protected Integer wrapMultiplier; protected boolean noReplicationSetup = false; private final String SOURCE_CLUSTER_OPT = "sourceCluster"; private final String DEST_CLUSTER_OPT = "destCluster"; private final String ITERATIONS_OPT = "iterations"; private final String NUM_MAPPERS_OPT = "numMappers"; private final String OUTPUT_DIR_OPT = "outputDir"; private final String NUM_REDUCERS_OPT = "numReducers"; private final String NO_REPLICATION_SETUP_OPT = "noReplicationSetup"; /** * The gap (in seconds) from when data is finished being generated at the source * to when it can be verified. This is the replication lag we are willing to tolerate */ private final String GENERATE_VERIFY_GAP_OPT = "generateVerifyGap"; /** * The width of the linked list. * See {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList} for more details */ private final String WIDTH_OPT = "width"; /** * The number of rows after which the linked list points to the first row. * See {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList} for more details */ private final String WRAP_MULTIPLIER_OPT = "wrapMultiplier"; /** * The number of nodes in the test setup. This has to be a multiple of WRAP_MULTIPLIER * WIDTH * in order to ensure that the linked list can is complete. * See {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList} for more details */ private final String NUM_NODES_OPT = "numNodes"; private final int DEFAULT_NUM_MAPPERS = 1; private final int DEFAULT_NUM_REDUCERS = 1; private final int DEFAULT_NUM_ITERATIONS = 1; private final int DEFAULT_GENERATE_VERIFY_GAP = 60; private final int DEFAULT_WIDTH = 1000000; private final int DEFAULT_WRAP_MULTIPLIER = 25; private final int DEFAULT_NUM_NODES = DEFAULT_WIDTH * DEFAULT_WRAP_MULTIPLIER; /** * Wrapper around an HBase ClusterID allowing us * to get admin connections and configurations for it */ protected class ClusterID { private final Configuration configuration; private Connection connection = null; /** * This creates a new ClusterID wrapper that will automatically build connections and * configurations to be able to talk to the specified cluster * * @param base the base configuration that this class will add to * @param key the cluster key in the form of zk_quorum:zk_port:zk_parent_node */ public ClusterID(Configuration base, String key) { configuration = new Configuration(base); String[] parts = key.split(":"); configuration.set(HConstants.ZOOKEEPER_QUORUM, parts[0]); configuration.set(HConstants.ZOOKEEPER_CLIENT_PORT, parts[1]); configuration.set(HConstants.ZOOKEEPER_ZNODE_PARENT, parts[2]); } @Override public String toString() { return Joiner.on(":").join(configuration.get(HConstants.ZOOKEEPER_QUORUM), configuration.get(HConstants.ZOOKEEPER_CLIENT_PORT), configuration.get(HConstants.ZOOKEEPER_ZNODE_PARENT)); } public Configuration getConfiguration() { return this.configuration; } public Connection getConnection() throws Exception { if (this.connection == null) { this.connection = ConnectionFactory.createConnection(this.configuration); } return this.connection; } public void closeConnection() throws Exception { this.connection.close(); this.connection = null; } public boolean equals(ClusterID other) { return this.toString().equalsIgnoreCase(other.toString()); } } /** * The main runner loop for the test. It uses * {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList} * for the generation and verification of the linked list. It is heavily based on * {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList.Loop} */ protected class VerifyReplicationLoop extends Configured implements Tool { private final Log LOG = LogFactory.getLog(VerifyReplicationLoop.class); protected ClusterID source; protected ClusterID sink; IntegrationTestBigLinkedList integrationTestBigLinkedList; /** * This tears down any tables that existed from before and rebuilds the tables and schemas on * the source cluster. It then sets up replication from the source to the sink cluster by using * the {@link org.apache.hadoop.hbase.client.replication.ReplicationAdmin} * connection. * * @throws Exception */ protected void setupTablesAndReplication() throws Exception { TableName tableName = getTableName(source.getConfiguration()); ClusterID[] clusters = {source, sink}; // delete any old tables in the source and sink for (ClusterID cluster : clusters) { Admin admin = cluster.getConnection().getAdmin(); if (admin.tableExists(tableName)) { if (admin.isTableEnabled(tableName)) { admin.disableTable(tableName); } /** * TODO: This is a work around on a replication bug (HBASE-13416) * When we recreate a table against that has recently been * deleted, the contents of the logs are replayed even though * they should not. This ensures that we flush the logs * before the table gets deleted. Eventually the bug should be * fixed and this should be removed. */ Set<ServerName> regionServers = new TreeSet<>(); for (HRegionLocation rl : cluster.getConnection().getRegionLocator(tableName).getAllRegionLocations()) { regionServers.add(rl.getServerName()); } for (ServerName server : regionServers) { source.getConnection().getAdmin().rollWALWriter(server); } admin.deleteTable(tableName); } } // create the schema Generator generator = new Generator(); generator.setConf(source.getConfiguration()); generator.createSchema(); // setup the replication on the source if (!source.equals(sink)) { ReplicationAdmin replicationAdmin = new ReplicationAdmin(source.getConfiguration()); // remove any old replication peers for (String oldPeer : replicationAdmin.listPeerConfigs().keySet()) { replicationAdmin.removePeer(oldPeer); } // set the sink to be the target ReplicationPeerConfig peerConfig = new ReplicationPeerConfig(); peerConfig.setClusterKey(sink.toString()); // set the test table to be the table to replicate HashMap<TableName, ArrayList<String>> toReplicate = new HashMap<>(); toReplicate.put(tableName, new ArrayList<String>(0)); replicationAdmin.addPeer("TestPeer", peerConfig, toReplicate); replicationAdmin.enableTableRep(tableName); replicationAdmin.close(); } for (ClusterID cluster : clusters) { cluster.closeConnection(); } } protected void waitForReplication() throws Exception { // TODO: we shouldn't be sleeping here. It would be better to query the region servers // and wait for them to report 0 replication lag. Thread.sleep(generateVerifyGap * 1000); } /** * Run the {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList.Generator} in the * source cluster. This assumes that the tables have been setup via setupTablesAndReplication. * * @throws Exception */ protected void runGenerator() throws Exception { Path outputPath = new Path(outputDir); UUID uuid = UUID.randomUUID(); //create a random UUID. Path generatorOutput = new Path(outputPath, uuid.toString()); Generator generator = new Generator(); generator.setConf(source.getConfiguration()); int retCode = generator.run(numMappers, numNodes, generatorOutput, width, wrapMultiplier); if (retCode > 0) { throw new RuntimeException("Generator failed with return code: " + retCode); } } /** * Run the {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList.Verify} * in the sink cluster. If replication is working properly the data written at the source * cluster should be available in the sink cluster after a reasonable gap * * @param expectedNumNodes the number of nodes we are expecting to see in the sink cluster * @throws Exception */ protected void runVerify(long expectedNumNodes) throws Exception { Path outputPath = new Path(outputDir); UUID uuid = UUID.randomUUID(); //create a random UUID. Path iterationOutput = new Path(outputPath, uuid.toString()); Verify verify = new Verify(); verify.setConf(sink.getConfiguration()); int retCode = verify.run(iterationOutput, numReducers); if (retCode > 0) { throw new RuntimeException("Verify.run failed with return code: " + retCode); } if (!verify.verify(expectedNumNodes)) { throw new RuntimeException("Verify.verify failed"); } LOG.info("Verify finished with success. Total nodes=" + expectedNumNodes); } /** * The main test runner * * This test has 4 steps: * 1: setupTablesAndReplication * 2: generate the data into the source cluster * 3: wait for replication to propagate * 4: verify that the data is available in the sink cluster * * @param args should be empty * @return 0 on success * @throws Exception on an error */ @Override public int run(String[] args) throws Exception { source = new ClusterID(getConf(), sourceClusterIdString); sink = new ClusterID(getConf(), sinkClusterIdString); if (!noReplicationSetup) { setupTablesAndReplication(); } int expectedNumNodes = 0; for (int i = 0; i < numIterations; i++) { LOG.info("Starting iteration = " + i); expectedNumNodes += numMappers * numNodes; runGenerator(); waitForReplication(); runVerify(expectedNumNodes); } /** * we are always returning 0 because exceptions are thrown when there is an error * in the verification step. */ return 0; } } @Override protected void addOptions() { super.addOptions(); addRequiredOptWithArg("s", SOURCE_CLUSTER_OPT, "Cluster ID of the source cluster (e.g. localhost:2181:/hbase)"); addRequiredOptWithArg("r", DEST_CLUSTER_OPT, "Cluster ID of the sink cluster (e.g. localhost:2182:/hbase)"); addRequiredOptWithArg("d", OUTPUT_DIR_OPT, "Temporary directory where to write keys for the test"); addOptWithArg("nm", NUM_MAPPERS_OPT, "Number of mappers (default: " + DEFAULT_NUM_MAPPERS + ")"); addOptWithArg("nr", NUM_REDUCERS_OPT, "Number of reducers (default: " + DEFAULT_NUM_MAPPERS + ")"); addOptNoArg("nrs", NO_REPLICATION_SETUP_OPT, "Don't setup tables or configure replication before starting test"); addOptWithArg("n", NUM_NODES_OPT, "Number of nodes. This should be a multiple of width * wrapMultiplier." + " (default: " + DEFAULT_NUM_NODES + ")"); addOptWithArg("i", ITERATIONS_OPT, "Number of iterations to run (default: " + DEFAULT_NUM_ITERATIONS + ")"); addOptWithArg("t", GENERATE_VERIFY_GAP_OPT, "Gap between generate and verify steps in seconds (default: " + DEFAULT_GENERATE_VERIFY_GAP + ")"); addOptWithArg("w", WIDTH_OPT, "Width of the linked list chain (default: " + DEFAULT_WIDTH + ")"); addOptWithArg("wm", WRAP_MULTIPLIER_OPT, "How many times to wrap around (default: " + DEFAULT_WRAP_MULTIPLIER + ")"); } @Override protected void processOptions(CommandLine cmd) { processBaseOptions(cmd); sourceClusterIdString = cmd.getOptionValue(SOURCE_CLUSTER_OPT); sinkClusterIdString = cmd.getOptionValue(DEST_CLUSTER_OPT); outputDir = cmd.getOptionValue(OUTPUT_DIR_OPT); /** This uses parseInt from {@link org.apache.hadoop.hbase.util.AbstractHBaseTool} */ numMappers = parseInt(cmd.getOptionValue(NUM_MAPPERS_OPT, Integer.toString(DEFAULT_NUM_MAPPERS)), 1, Integer.MAX_VALUE); numReducers = parseInt(cmd.getOptionValue(NUM_REDUCERS_OPT, Integer.toString(DEFAULT_NUM_REDUCERS)), 1, Integer.MAX_VALUE); numNodes = parseInt(cmd.getOptionValue(NUM_NODES_OPT, Integer.toString(DEFAULT_NUM_NODES)), 1, Integer.MAX_VALUE); generateVerifyGap = parseInt(cmd.getOptionValue(GENERATE_VERIFY_GAP_OPT, Integer.toString(DEFAULT_GENERATE_VERIFY_GAP)), 1, Integer.MAX_VALUE); numIterations = parseInt(cmd.getOptionValue(ITERATIONS_OPT, Integer.toString(DEFAULT_NUM_ITERATIONS)), 1, Integer.MAX_VALUE); width = parseInt(cmd.getOptionValue(WIDTH_OPT, Integer.toString(DEFAULT_WIDTH)), 1, Integer.MAX_VALUE); wrapMultiplier = parseInt(cmd.getOptionValue(WRAP_MULTIPLIER_OPT, Integer.toString(DEFAULT_WRAP_MULTIPLIER)), 1, Integer.MAX_VALUE); if (cmd.hasOption(NO_REPLICATION_SETUP_OPT)) { noReplicationSetup = true; } if (numNodes % (width * wrapMultiplier) != 0) { throw new RuntimeException("numNodes must be a multiple of width and wrap multiplier"); } } @Override public int runTestFromCommandLine() throws Exception { VerifyReplicationLoop tool = new VerifyReplicationLoop(); tool.integrationTestBigLinkedList = this; return ToolRunner.run(getConf(), tool, null); } public static void main(String[] args) throws Exception { Configuration conf = HBaseConfiguration.create(); IntegrationTestingUtility.setUseDistributedCluster(conf); int ret = ToolRunner.run(conf, new IntegrationTestReplication(), args); System.exit(ret); } }
juwi/hbase
hbase-it/src/test/java/org/apache/hadoop/hbase/test/IntegrationTestReplication.java
Java
apache-2.0
17,081
'use strict'; var nconf = require('nconf'); var path = require('path'); /** * Handle the configuration management. * * @constructor */ function Config() { nconf.argv().env("_"); var environment = nconf.get("NODE:ENV") || "development"; nconf.file(environment, {file: path.resolve(__dirname, '../config/' + environment + '.json')}); nconf.file('default', {file: path.resolve(__dirname, '../config/default.json')}); } /** * Return the value of the provided key from the configuration object. * * @param {string} key - Key from the configuration object. */ Config.prototype.get = function (key) { return nconf.get(key); }; module.exports = new Config();
mxr576/webpage-content-extractor-api
lib/config.js
JavaScript
apache-2.0
676
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.calcite.test; import org.apache.calcite.sql.SqlNode; import org.apache.calcite.sql.parser.StringAndPos; import org.apache.calcite.sql.test.AbstractSqlTester; import org.apache.calcite.sql.test.SqlTestFactory; import org.apache.calcite.sql.test.SqlTests; import org.apache.calcite.sql.validate.SqlValidator; import org.checkerframework.checker.nullness.qual.Nullable; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Tester of {@link SqlValidator} and runtime execution of the input SQL. */ class SqlRuntimeTester extends AbstractSqlTester { SqlRuntimeTester() { } @Override public void checkFails(SqlTestFactory factory, StringAndPos sap, String expectedError, boolean runtime) { final StringAndPos sap2 = StringAndPos.of(runtime ? buildQuery2(factory, sap.addCarets()) : buildQuery(sap.addCarets())); assertExceptionIsThrown(factory, sap2, expectedError, runtime); } @Override public void checkAggFails(SqlTestFactory factory, String expr, String[] inputValues, String expectedError, boolean runtime) { String query = SqlTests.generateAggQuery(expr, inputValues); final StringAndPos sap = StringAndPos.of(query); assertExceptionIsThrown(factory, sap, expectedError, runtime); } @Override public void assertExceptionIsThrown(SqlTestFactory factory, StringAndPos sap, @Nullable String expectedMsgPattern) { assertExceptionIsThrown(factory, sap, expectedMsgPattern, false); } public void assertExceptionIsThrown(SqlTestFactory factory, StringAndPos sap, @Nullable String expectedMsgPattern, boolean runtime) { final SqlNode sqlNode; try { sqlNode = parseQuery(factory, sap.sql); } catch (Throwable e) { checkParseEx(e, expectedMsgPattern, sap); return; } Throwable thrown = null; final SqlTests.Stage stage; final SqlValidator validator = factory.createValidator(); if (runtime) { stage = SqlTests.Stage.RUNTIME; SqlNode validated = validator.validate(sqlNode); assertNotNull(validated); try { check(factory, sap.sql, SqlTests.ANY_TYPE_CHECKER, SqlTests.ANY_PARAMETER_CHECKER, SqlTests.ANY_RESULT_CHECKER); } catch (Throwable ex) { // get the real exception in runtime check thrown = ex; } } else { stage = SqlTests.Stage.VALIDATE; try { validator.validate(sqlNode); } catch (Throwable ex) { thrown = ex; } } SqlTests.checkEx(thrown, expectedMsgPattern, sap, stage); } }
apache/calcite
testkit/src/main/java/org/apache/calcite/test/SqlRuntimeTester.java
Java
apache-2.0
3,405
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Christian Schulte <schulte@gecode.org> * * Copyright: * Christian Schulte, 2004 * * Last modified: * $Date: 2010-03-04 03:40:32 +1100 (Thu, 04 Mar 2010) $ by $Author: schulte $ * $Revision: 10365 $ * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * 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 <gecode/int/element.hh> namespace Gecode { using namespace Int; void element(Home home, IntSharedArray c, IntVar x0, IntVar x1, IntConLevel) { if (c.size() == 0) throw TooFewArguments("Int::element"); if (home.failed()) return; for (int i = c.size(); i--; ) Limits::check(c[i],"Int::element"); GECODE_ES_FAIL((Element::post_int<IntView,IntView>(home,c,x0,x1))); } void element(Home home, IntSharedArray c, IntVar x0, BoolVar x1, IntConLevel) { if (c.size() == 0) throw TooFewArguments("Int::element"); if (home.failed()) return; for (int i = c.size(); i--; ) Limits::check(c[i],"Int::element"); GECODE_ES_FAIL((Element::post_int<IntView,BoolView>(home,c,x0,x1))); } void element(Home home, IntSharedArray c, IntVar x0, int x1, IntConLevel) { if (c.size() == 0) throw TooFewArguments("Int::element"); Limits::check(x1,"Int::element"); if (home.failed()) return; for (int i = c.size(); i--; ) Limits::check(c[i],"Int::element"); ConstIntView cx1(x1); GECODE_ES_FAIL( (Element::post_int<IntView,ConstIntView>(home,c,x0,cx1))); } void element(Home home, const IntVarArgs& c, IntVar x0, IntVar x1, IntConLevel icl) { if (c.size() == 0) throw TooFewArguments("Int::element"); if (home.failed()) return; Element::IdxViewArray<IntView> iv(home,c); if ((icl == ICL_DOM) || (icl == ICL_DEF)) { GECODE_ES_FAIL((Element::ViewDom<IntView,IntView,IntView> ::post(home,iv,x0,x1))); } else { GECODE_ES_FAIL((Element::ViewBnd<IntView,IntView,IntView> ::post(home,iv,x0,x1))); } } void element(Home home, const IntVarArgs& c, IntVar x0, int x1, IntConLevel icl) { if (c.size() == 0) throw TooFewArguments("Int::element"); Limits::check(x1,"Int::element"); if (home.failed()) return; Element::IdxViewArray<IntView> iv(home,c); ConstIntView v1(x1); if ((icl == ICL_DOM) || (icl == ICL_DEF)) { GECODE_ES_FAIL((Element::ViewDom<IntView,IntView,ConstIntView> ::post(home,iv,x0,v1))); } else { GECODE_ES_FAIL((Element::ViewBnd<IntView,IntView,ConstIntView> ::post(home,iv,x0,v1))); } } void element(Home home, const BoolVarArgs& c, IntVar x0, BoolVar x1, IntConLevel) { if (c.size() == 0) throw TooFewArguments("Int::element"); if (home.failed()) return; Element::IdxViewArray<BoolView> iv(home,c); GECODE_ES_FAIL((Element::ViewBnd<BoolView,IntView,BoolView> ::post(home,iv,x0,x1))); } void element(Home home, const BoolVarArgs& c, IntVar x0, int x1, IntConLevel) { if (c.size() == 0) throw TooFewArguments("Int::element"); Limits::check(x1,"Int::element"); if (home.failed()) return; Element::IdxViewArray<BoolView> iv(home,c); ConstIntView v1(x1); GECODE_ES_FAIL((Element::ViewBnd<BoolView,IntView,ConstIntView> ::post(home,iv,x0,v1))); } namespace { IntVar pair(Home home, IntVar x, int w, IntVar y, int h) { IntVar xy(home,0,w*h-1); if (Element::Pair::post(home,x,y,xy,w,h) != ES_OK) home.fail(); return xy; } } void element(Home home, IntSharedArray a, IntVar x, int w, IntVar y, int h, IntVar z, IntConLevel icl) { if (a.size() != w*h) throw Int::ArgumentSizeMismatch("Int::element"); if (home.failed()) return; element(home, a, pair(home,x,w,y,h), z, icl); } void element(Home home, IntSharedArray a, IntVar x, int w, IntVar y, int h, BoolVar z, IntConLevel icl) { if (a.size() != w*h) throw Int::ArgumentSizeMismatch("Int::element"); if (home.failed()) return; element(home, a, pair(home,x,w,y,h), z, icl); } void element(Home home, const IntVarArgs& a, IntVar x, int w, IntVar y, int h, IntVar z, IntConLevel icl) { if (a.size() != w*h) throw Int::ArgumentSizeMismatch("Int::element"); if (home.failed()) return; element(home, a, pair(home,x,w,y,h), z, icl); } void element(Home home, const BoolVarArgs& a, IntVar x, int w, IntVar y, int h, BoolVar z, IntConLevel icl) { if (a.size() != w*h) throw Int::ArgumentSizeMismatch("Int::element"); if (home.failed()) return; element(home, a, pair(home,x,w,y,h), z, icl); } } // STATISTICS: int-post
h4ck3rm1k3/dep-selector-libgecode
ext/libgecode3/vendor/gecode-3.7.3/gecode/int/element.cpp
C++
apache-2.0
6,133
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.operator.scalar; import com.facebook.presto.spi.type.ArrayType; import com.facebook.presto.spi.type.RowType; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.testng.annotations.Test; import java.util.Optional; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.IntegerType.INTEGER; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static com.facebook.presto.spi.type.VarcharType.createVarcharType; import static com.facebook.presto.type.UnknownType.UNKNOWN; import static com.facebook.presto.util.StructuralTestUtil.mapType; import static java.util.Arrays.asList; public class TestZipWithFunction extends AbstractTestFunctions { @Test public void testRetainedSizeBounded() { assertCachedInstanceHasBoundedRetainedSize("zip_with(ARRAY [25, 26, 27], ARRAY [1, 2, 3], (x, y) -> x + y)"); } @Test public void testSameLength() { assertFunction("zip_with(ARRAY[], ARRAY[], (x, y) -> (y, x))", new ArrayType(new RowType(ImmutableList.of(UNKNOWN, UNKNOWN), Optional.empty())), ImmutableList.of()); assertFunction("zip_with(ARRAY[1, 2], ARRAY['a', 'b'], (x, y) -> (y, x))", new ArrayType(new RowType(ImmutableList.of(createVarcharType(1), INTEGER), Optional.empty())), ImmutableList.of(ImmutableList.of("a", 1), ImmutableList.of("b", 2))); assertFunction("zip_with(ARRAY[1, 2], ARRAY[CAST('a' AS VARCHAR), CAST('b' AS VARCHAR)], (x, y) -> (y, x))", new ArrayType(new RowType(ImmutableList.of(VARCHAR, INTEGER), Optional.empty())), ImmutableList.of(ImmutableList.of("a", 1), ImmutableList.of("b", 2))); assertFunction("zip_with(ARRAY[1, 1], ARRAY[1, 2], (x, y) -> x + y)", new ArrayType(INTEGER), ImmutableList.of(2, 3)); assertFunction("zip_with(CAST(ARRAY[3, 5] AS ARRAY(BIGINT)), CAST(ARRAY[1, 2] AS ARRAY(BIGINT)), (x, y) -> x * y)", new ArrayType(BIGINT), ImmutableList.of(3L, 10L)); assertFunction("zip_with(ARRAY[true, false], ARRAY[false, true], (x, y) -> x OR y)", new ArrayType(BOOLEAN), ImmutableList.of(true, true)); assertFunction("zip_with(ARRAY['a', 'b'], ARRAY['c', 'd'], (x, y) -> concat(x, y))", new ArrayType(VARCHAR), ImmutableList.of("ac", "bd")); assertFunction("zip_with(ARRAY[MAP(ARRAY[CAST ('a' AS VARCHAR)], ARRAY[1]), MAP(ARRAY[CAST('b' AS VARCHAR)], ARRAY[2])], ARRAY[MAP(ARRAY['c'], ARRAY[3]), MAP()], (x, y) -> map_concat(x, y))", new ArrayType(mapType(VARCHAR, INTEGER)), ImmutableList.of(ImmutableMap.of("a", 1, "c", 3), ImmutableMap.of("b", 2))); } @Test public void testDifferentLength() { assertInvalidFunction("zip_with(ARRAY[1], ARRAY['a', 'b'], (x, y) -> (y, x))", "Arrays must have the same length"); assertInvalidFunction("zip_with(ARRAY[NULL, 2], ARRAY['a'], (x, y) -> (y, x))", "Arrays must have the same length"); assertInvalidFunction("zip_with(ARRAY[1, NULL], ARRAY[NULL, 2, 1], (x, y) -> x + y)", "Arrays must have the same length"); } @Test public void testWithNull() { assertFunction("zip_with(CAST(NULL AS ARRAY(UNKNOWN)), ARRAY[], (x, y) -> (y, x))", new ArrayType(new RowType(ImmutableList.of(UNKNOWN, UNKNOWN), Optional.empty())), null); assertFunction("zip_with(ARRAY[NULL], ARRAY[NULL], (x, y) -> (y, x))", new ArrayType(new RowType(ImmutableList.of(UNKNOWN, UNKNOWN), Optional.empty())), ImmutableList.of(asList(null, null))); assertFunction("zip_with(ARRAY[NULL], ARRAY[NULL], (x, y) -> x IS NULL AND y IS NULL)", new ArrayType(BOOLEAN), ImmutableList.of(true)); assertFunction("zip_with(ARRAY['a', NULL], ARRAY[NULL, 1], (x, y) -> x IS NULL OR y IS NULL)", new ArrayType(BOOLEAN), ImmutableList.of(true, true)); assertFunction("zip_with(ARRAY[1, NULL], ARRAY[3, 4], (x, y) -> x + y)", new ArrayType(INTEGER), asList(4, null)); assertFunction("zip_with(ARRAY['a', 'b'], ARRAY[1, 3], (x, y) -> NULL)", new ArrayType(UNKNOWN), asList(null, null)); } }
Teradata/presto
presto-main/src/test/java/com/facebook/presto/operator/scalar/TestZipWithFunction.java
Java
apache-2.0
5,166
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.admin.jmx.internal; import javax.management.ObjectName; import javax.management.modelmbean.ModelMBean; import org.apache.geode.admin.internal.SystemMemberCacheImpl; import org.apache.geode.cache.Region; import org.apache.geode.internal.admin.GemFireVM; /** * MBean representation of {@link org.apache.geode.admin.SystemMemberRegion}. * * @since GemFire 3.5 */ public class SystemMemberRegionJmxImpl extends org.apache.geode.admin.internal.SystemMemberRegionImpl implements org.apache.geode.admin.jmx.internal.ManagedResource { /** The object name of this managed resource */ private ObjectName objectName; // ------------------------------------------------------------------------- // Constructor(s) // ------------------------------------------------------------------------- /** * Constructs an instance of SystemMemberRegionJmxImpl. * * @param cache the cache this region belongs to * @param region internal region to delegate real work to */ public SystemMemberRegionJmxImpl(SystemMemberCacheImpl cache, Region region) throws org.apache.geode.admin.AdminException { super(cache, region); initializeMBean(cache); } /** Create and register the MBean to manage this resource */ private void initializeMBean(SystemMemberCacheImpl cache) throws org.apache.geode.admin.AdminException { GemFireVM vm = cache.getVM(); mbeanName = "GemFire.Cache:" + "path=" + MBeanUtils.makeCompliantMBeanNameProperty(getFullPath()) + ",name=" + MBeanUtils.makeCompliantMBeanNameProperty(cache.getName()) + ",id=" + cache.getId() + ",owner=" + MBeanUtils.makeCompliantMBeanNameProperty(vm.getId().toString()) + ",type=Region"; objectName = MBeanUtils.createMBean(this); } // ------------------------------------------------------------------------- // ManagedResource implementation // ------------------------------------------------------------------------- /** The name of the MBean that will manage this resource */ private String mbeanName; /** The ModelMBean that is configured to manage this resource */ private ModelMBean modelMBean; @Override public String getMBeanName() { return mbeanName; } @Override public ModelMBean getModelMBean() { return modelMBean; } @Override public void setModelMBean(ModelMBean modelMBean) { this.modelMBean = modelMBean; } @Override public ObjectName getObjectName() { return objectName; } @Override public ManagedResourceType getManagedResourceType() { return ManagedResourceType.SYSTEM_MEMBER_REGION; } @Override public void cleanupResource() {} /** * Checks equality of the given object with <code>this</code> based on the type (Class) and the * MBean Name returned by <code>getMBeanName()</code> methods. * * @param obj object to check equality with * @return true if the given object is if the same type and its MBean Name is same as * <code>this</code> object's MBean Name, false otherwise */ @Override public boolean equals(Object obj) { if (!(obj instanceof SystemMemberRegionJmxImpl)) { return false; } SystemMemberRegionJmxImpl other = (SystemMemberRegionJmxImpl) obj; return getMBeanName().equals(other.getMBeanName()); } /** * Returns hash code for <code>this</code> object which is based on the MBean Name generated. * * @return hash code for <code>this</code> object */ @Override public int hashCode() { return getMBeanName().hashCode(); } }
jdeppe-pivotal/geode
geode-core/src/main/java/org/apache/geode/admin/jmx/internal/SystemMemberRegionJmxImpl.java
Java
apache-2.0
4,385
let hookTypes; const callStyles = { sync: 'applyPlugins', syncWaterfall: 'applyPluginsWaterfall', syncBail: 'applyPluginsBailResult', sync_map: 'applyPlugins', asyncWaterfall: 'applyPluginsAsyncWaterfall', asyncParallel: 'applyPluginsParallel', asyncSerial: 'applyPluginsAsync', }; const camelToDash = camel => camel.replace(/_/g, '--').replace(/[A-Z]/g, c => `-${c.toLowerCase()}`); const knownPluginRegistrations = { Compilation: { needAdditionalPass: ['sync', []], succeedModule: ['sync', ['module']], buildModule: ['sync', ['module']], seal: ['sync', []], }, Compiler: { afterCompile: ['asyncSerial', ['compilation']], afterEnvironment: ['sync', []], afterPlugins: ['sync', []], afterResolvers: ['sync', []], compilation: ['sync', ['compilation', 'params']], emit: ['asyncSerial', ['compilation']], make: ['asyncParallel', ['compilation']], watchRun: ['asyncSerial', ['watcher']], run: ['asyncSerial', ['compiler']], }, NormalModuleFactory: { createModule: ['syncBail', ['data']], parser: ['sync_map', ['parser', 'parserOptions']], resolver: ['syncWaterfall', ['nextResolver']], }, ContextModuleFactory: { afterResolve: ['asyncWaterfall', ['data']], }, }; exports.register = (tapable, name, style, args) => { if (tapable.hooks) { if (!hookTypes) { const Tapable = require('tapable'); hookTypes = { sync: Tapable.SyncHook, syncWaterfall: Tapable.SyncWaterfallHook, syncBail: Tapable.SyncBailHook, asyncWaterfall: Tapable.AsyncWaterfallHook, asyncParallel: Tapable.AsyncParallelHook, asyncSerial: Tapable.AsyncSeriesHook, asyncSeries: Tapable.AsyncSeriesHook, }; } if (!tapable.hooks[name]) { tapable.hooks[name] = new hookTypes[style](args); } } else { if (!tapable.__hardSource_hooks) { tapable.__hardSource_hooks = {}; } if (!tapable.__hardSource_hooks[name]) { tapable.__hardSource_hooks[name] = { name, dashName: camelToDash(name), style, args, async: style.startsWith('async'), map: style.endsWith('_map'), }; } if (!tapable.__hardSource_proxy) { tapable.__hardSource_proxy = {}; } if (!tapable.__hardSource_proxy[name]) { if (tapable.__hardSource_hooks[name].map) { const _forCache = {}; tapable.__hardSource_proxy[name] = { _forCache, for: key => { let hook = _forCache[key]; if (hook) { return hook; } _forCache[key] = { tap: (...args) => exports.tapFor(tapable, name, key, ...args), tapPromise: (...args) => exports.tapPromiseFor(tapable, name, key, ...args), call: (...args) => exports.callFor(tapable, name, key, ...args), promise: (...args) => exports.promiseFor(tapable, name, key, ...args), }; return _forCache[key]; }, tap: (...args) => exports.tapFor(tapable, name, ...args), tapPromise: (...args) => exports.tapPromiseFor(tapable, name, ...args), call: (...args) => exports.callFor(tapable, name, ...args), promise: (...args) => exports.promiseFor(tapable, name, ...args), }; } else { tapable.__hardSource_proxy[name] = { tap: (...args) => exports.tap(tapable, name, ...args), tapPromise: (...args) => exports.tapPromise(tapable, name, ...args), call: (...args) => exports.call(tapable, name, args), promise: (...args) => exports.promise(tapable, name, args), }; } } } }; exports.tap = (tapable, name, reason, callback) => { if (tapable.hooks) { tapable.hooks[name].tap(reason, callback); } else { if (!tapable.__hardSource_hooks || !tapable.__hardSource_hooks[name]) { const registration = knownPluginRegistrations[tapable.constructor.name][name]; exports.register(tapable, name, registration[0], registration[1]); } const dashName = tapable.__hardSource_hooks[name].dashName; if (tapable.__hardSource_hooks[name].async) { tapable.plugin(dashName, (...args) => { const cb = args.pop(); cb(null, callback(...args)); }); } else { tapable.plugin(dashName, callback); } } }; exports.tapPromise = (tapable, name, reason, callback) => { if (tapable.hooks) { tapable.hooks[name].tapPromise(reason, callback); } else { if (!tapable.__hardSource_hooks || !tapable.__hardSource_hooks[name]) { const registration = knownPluginRegistrations[tapable.constructor.name][name]; exports.register(tapable, name, registration[0], registration[1]); } const dashName = tapable.__hardSource_hooks[name].dashName; tapable.plugin(dashName, (...args) => { const cb = args.pop(); return callback(...args).then(value => cb(null, value), cb); }); } }; exports.tapAsync = (tapable, name, reason, callback) => { if (tapable.hooks) { tapable.hooks[name].tapAsync(reason, callback); } else { if (!tapable.__hardSource_hooks || !tapable.__hardSource_hooks[name]) { const registration = knownPluginRegistrations[tapable.constructor.name][name]; exports.register(tapable, name, registration[0], registration[1]); } const dashName = tapable.__hardSource_hooks[name].dashName; tapable.plugin(dashName, callback); } }; exports.call = (tapable, name, args) => { if (tapable.hooks) { const hook = tapable.hooks[name]; return hook.call(...args); } else { const dashName = tapable.__hardSource_hooks[name].dashName; const style = tapable.__hardSource_hooks[name].style; return tapable[callStyles[style]](...[dashName].concat(args)); } }; exports.promise = (tapable, name, args) => { if (tapable.hooks) { const hook = tapable.hooks[name]; return hook.promise(...args); } else { const dashName = tapable.__hardSource_hooks[name].dashName; const style = tapable.__hardSource_hooks[name].style; return new Promise((resolve, reject) => { tapable[callStyles[style]]( ...[dashName].concat(args, (err, value) => { if (err) { reject(err); } else { resolve(value); } }), ); }); } }; exports.tapFor = (tapable, name, key, reason, callback) => { if (tapable.hooks) { tapable.hooks[name].for(key).tap(reason, callback); } else { exports.tap(tapable, name, reason, callback); } }; exports.tapPromiseFor = (tapable, name, key, reason, callback) => { if (tapable.hooks) { tapable.hooks[name].for(key).tapPromise(reason, callback); } else { exports.tapPromise(tapable, name, reason, callback); } }; exports.callFor = (tapable, name, key, args) => { if (tapable.hooks) { tapable.hooks[name].for(key).call(...args); } else { exports.call(tapable, name, args); } }; exports.promiseFor = (tapable, name, key, args) => { if (tapable.hooks) { tapable.hooks[name].for(key).promise(...args); } else { exports.promise(tapable, name, args); } }; exports.hooks = tapable => { if (tapable.hooks) { return tapable.hooks; } if (!tapable.__hardSource_proxy) { tapable.__hardSource_proxy = {}; } const registrations = knownPluginRegistrations[tapable.constructor.name]; if (registrations) { for (const name in registrations) { const registration = registrations[name]; exports.register(tapable, name, registration[0], registration[1]); } } return tapable.__hardSource_proxy; };
BigBoss424/portfolio
v6/node_modules/hard-source-webpack-plugin/lib/util/plugin-compat.js
JavaScript
apache-2.0
7,732