code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/* * Copyright 2013-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.util; /** * Currently provided encoding schemes "out of the box". * * @author Hanson Char * * See http://www.ietf.org/rfc/rfc4648.txt */ public enum EncodingSchemeEnum implements EncodingScheme { BASE16 { @Override public String encodeAsString(byte[] bytes) { return Base16.encodeAsString(bytes); } @Override public byte[] decode(String encoded) { return Base16.decode(encoded); } }, BASE32 { @Override public String encodeAsString(byte[] bytes) { return Base32.encodeAsString(bytes); } @Override public byte[] decode(String encoded) { return Base32.decode(encoded); } }, BASE64 { @Override public String encodeAsString(byte[] bytes) { return Base64.encodeAsString(bytes); } @Override public byte[] decode(String encoded) { return Base64.decode(encoded); } }, ; @Override public abstract String encodeAsString(byte[] bytes); }
mahaliachante/aws-sdk-java
aws-java-sdk-core/src/main/java/com/amazonaws/util/EncodingSchemeEnum.java
Java
apache-2.0
1,657
#!/usr/bin/env python # # Copyright 2008 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. # """Unittests for taskthread.py""" import unittest import sys import time import wx import launcher class FakeAppController(object): def RefreshMainView(self): pass class TaskThreadTest(unittest.TestCase): def setUp(self): # Must always create a wx.App first self.app = wx.PySimpleApp() def doTestThreadRun(self, killit=False): """Run a command, watch for state change. Optionally kill it to speed up death. """ controller = launcher.TaskController(FakeAppController()) project = launcher.Project('himom', 8000) secs = 3 if killit: # If in killit mode, make sure it'll last longer than us so we # don't confuse kill with runout secs = 20 # Start a task ripe for the killing. command = [sys.executable, '-c', 'import time; time.sleep(%d)' % secs] tt = launcher.TaskThread(controller, project, command) tt.start() # TODO(jrg): is this a reasonable chance? for i in range(20): time.sleep(0.25) if tt.isAlive(): break self.assertTrue(tt.isAlive()) if killit: tt.stop() for i in range(20): time.sleep(0.25) if not tt.isAlive(): break self.assertFalse(tt.isAlive()) pass def testRunOut(self): self.doTestThreadRun(killit=False) def testKilled(self): self.doTestThreadRun(killit=True) def testLaunchLogLineCompleted(self): tt = launcher.TaskThread(self, None, None) line = ('INFO 2009-04-08 15:36:23,888 dev_appserver_main.py] Running ' 'application TheDen on port 8015: http://localhost:8015') self.assertTrue(tt._IsLaunchCompletedLogLine(line)) line = ('INFO 2009-04-08 15:36:23,888 dev_appserver_main.py] Running ' 'application greeblebork on port 8000: ' 'http://oop.ack.blarg.co.ukt:8000') self.assertTrue(tt._IsLaunchCompletedLogLine(line)) line = 'Running application http://x:5' self.assertTrue(tt._IsLaunchCompletedLogLine(line)) # Take some output from a real dev_appserver and make sure it doesn't match. line = 'socket.error: (48, \'Address already in use\')' self.assertFalse(tt._IsLaunchCompletedLogLine(line)) line = ('WARNING 2009-04-08 15:56:55,495 dev_appserver.py] Could not ' 'initialize images API; you are likely missing the Python "PIL" ' 'module. ImportError: No module named _imaging') self.assertFalse(tt._IsLaunchCompletedLogLine(line)) # NOTE: the following pieces of TaskThread are explicitly tested in # deploy_controller_unittest.py's testTaskThreadForProject(): # - use of stdin to on __init__ # - _TaskWillStart() # - _TaskDidStart() # - _TaskDidStop(code) if __name__ == "__main__": unittest.main()
aykuttasil/google-appengine-wx-launcher
launcher/taskthread_unittest.py
Python
apache-2.0
3,337
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.cloudfront_2012_03_15.model; /** * <p> * The returned result of the corresponding request. * </p> */ public class GetInvalidationResult { /** * The invalidation's information. */ private Invalidation invalidation; /** * The invalidation's information. * * @return The invalidation's information. */ public Invalidation getInvalidation() { return invalidation; } /** * The invalidation's information. * * @param invalidation The invalidation's information. */ public void setInvalidation(Invalidation invalidation) { this.invalidation = invalidation; } /** * The invalidation's information. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param invalidation The invalidation's information. * * @return A reference to this updated object so that method calls can be chained * together. */ public GetInvalidationResult withInvalidation(Invalidation invalidation) { this.invalidation = invalidation; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (invalidation != null) sb.append("Invalidation: " + invalidation + ", "); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getInvalidation() == null) ? 0 : getInvalidation().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetInvalidationResult == false) return false; GetInvalidationResult other = (GetInvalidationResult)obj; if (other.getInvalidation() == null ^ this.getInvalidation() == null) return false; if (other.getInvalidation() != null && other.getInvalidation().equals(this.getInvalidation()) == false) return false; return true; } }
vromero/aws-sdk-java
aws-java-sdk-cloudfront/src/main/java/com/amazonaws/services/cloudfront_2012_03_15/model/GetInvalidationResult.java
Java
apache-2.0
3,062
/* * Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.s3.internal; import java.util.HashMap; import java.util.Map; import com.amazonaws.AmazonServiceException.ErrorType; import com.amazonaws.services.s3.model.AmazonS3Exception; /** * Builder class that builds the <code>AmazonS3Exception</code> */ public class AmazonS3ExceptionBuilder { /** * The unique AWS identifier for the service request the caller made. The * AWS request ID can uniquely identify the AWS request, and is used for * reporting an error to AWS support team. */ private String requestId; /** * The AWS error code represented by this exception (ex: * InvalidParameterValue). */ private String errorCode; /** * The error message as returned by the service. */ private String errorMessage; /** The HTTP status code that was returned with this error */ private int statusCode; /** * An S3 specific request ID that provides additional debugging information. */ private String extendedRequestId; /** * Additional information on the exception. */ private Map<String, String> additionalDetails; /** * Returns the error XML received in the HTTP Response or null if the * exception is constructed from the headers. */ private String errorResponseXml; /** * Returns the AWS request ID that uniquely identifies the service request * the caller made. * * @return The AWS request ID that uniquely identifies the service request * the caller made. */ public String getRequestId() { return requestId; } /** * Sets the AWS requestId for this exception. * * @param requestId * The unique identifier for the service request the caller made. */ public void setRequestId(String requestId) { this.requestId = requestId; } /** * Sets the AWS error code represented by this exception. * * @param errorCode * The AWS error code represented by this exception. */ public void setErrorCode(String errorCode) { this.errorCode = errorCode; } /** * Returns the AWS error code represented by this exception. * * @return The AWS error code represented by this exception. */ public String getErrorCode() { return errorCode; } /** * Returns the human-readable error message provided by the service */ public String getErrorMessage() { return errorMessage; } /** * Sets the human-readable error message provided by the service */ public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } /** * Sets the HTTP status code that was returned with this service exception. * * @param statusCode * The HTTP status code that was returned with this service * exception. */ public void setStatusCode(int statusCode) { this.statusCode = statusCode; } /** * Returns the HTTP status code that was returned with this service * exception. * * @return The HTTP status code that was returned with this service * exception. */ public int getStatusCode() { return statusCode; } /** * Gets Amazon S3's extended request ID. This ID is required debugging * information in the case the user needs to contact Amazon about an issue * where Amazon S3 is incorrectly handling a request. * * @return Amazon S3's extended request ID. * * @see AmazonS3Exception#setExtendedRequestId(String) * @see AmazonS3Exception#getExtendedRequestId() */ public String getExtendedRequestId() { return extendedRequestId; } /** * Sets Amazon S3's extended request ID. * * @param extendedRequestId * S3's extended request ID. * * @see AmazonS3Exception#setExtendedRequestId(String) * @see AmazonS3Exception#getExtendedRequestId() */ public void setExtendedRequestId(String extendedRequestId) { this.extendedRequestId = extendedRequestId; } /** * Returns any additional information retrieved in the error response. */ public Map<String, String> getAdditionalDetails() { return additionalDetails; } /** * Sets additional information about the response. */ public void setAdditionalDetails(Map<String, String> additionalDetails) { this.additionalDetails = additionalDetails; } /** * Adds an entry to the additional information map. */ public void addAdditionalDetail(String key, String detail) { if (detail == null || detail.trim().isEmpty()) return; if (this.additionalDetails == null) { this.additionalDetails = new HashMap<String, String>(); } String additionalContent = this.additionalDetails.get(key); if (additionalContent != null && !additionalContent.trim().isEmpty()) detail = additionalContent + "-" + detail; if (!detail.isEmpty()) additionalDetails.put(key, detail); } /** * Returns the original error response XML received from Amazon S3 */ public String getErrorResponseXml() { return errorResponseXml; } /** * Sets the error response XML received from Amazon S3 */ public void setErrorResponseXml(String errorResponseXml) { this.errorResponseXml = errorResponseXml; } /** * Creates a new AmazonS3Exception object with the values set. */ public AmazonS3Exception build() { AmazonS3Exception s3Exception = errorResponseXml == null ? new AmazonS3Exception( errorMessage) : new AmazonS3Exception(errorMessage, errorResponseXml); s3Exception.setErrorCode(errorCode); s3Exception.setExtendedRequestId(extendedRequestId); s3Exception.setStatusCode(statusCode); s3Exception.setRequestId(requestId); s3Exception.setAdditionalDetails(additionalDetails); s3Exception.setErrorType(errorTypeOf(statusCode)); return s3Exception; } /** * Returns the AWS error type information by looking at the HTTP status code * in the error response. S3 error responses don't explicitly declare a * sender or client fault like other AWS services, so we have to use the * HTTP status code to infer this information. * * @param httpResponse * The HTTP error response to use to determine the right error * type to set. */ private ErrorType errorTypeOf(int statusCode) { return statusCode >= 500 ? ErrorType.Service : ErrorType.Client; } }
xuzha/aws-sdk-java
aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/AmazonS3ExceptionBuilder.java
Java
apache-2.0
7,445
/* * 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.psi.impl.source.javadoc; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiReference; import com.intellij.psi.PsiType; import com.intellij.psi.javadoc.JavadocTagInfo; import com.intellij.psi.javadoc.PsiDocTagValue; /** * @author mike */ class ReturnDocTagInfo implements JavadocTagInfo { @Override public String getName() { return "return"; } @Override public boolean isInline() { return false; } @Override public boolean isValidInContext(PsiElement element) { if (!(element instanceof PsiMethod)) return false; PsiMethod method = (PsiMethod)element; final PsiType type = method.getReturnType(); if (type == null) return false; return !PsiType.VOID.equals(type); } @Override public String checkTagValue(PsiDocTagValue value) { return null; } @Override public PsiReference getReference(PsiDocTagValue value) { return null; } }
idea4bsd/idea4bsd
java/java-psi-impl/src/com/intellij/psi/impl/source/javadoc/ReturnDocTagInfo.java
Java
apache-2.0
1,569
/* * Copyright 2008-2009 Katholieke Universiteit Leuven * * Use of this software is governed by the MIT license * * Written by Sven Verdoolaege, K.U.Leuven, Departement * Computerwetenschappen, Celestijnenlaan 200A, B-3001 Leuven, Belgium */ #ifndef ISL_LP_H #define ISL_LP_H #include <isl/aff.h> #include <isl/val_type.h> #include <isl/set_type.h> enum isl_lp_result { isl_lp_error = -1, isl_lp_ok = 0, isl_lp_unbounded, isl_lp_empty }; #if defined(__cplusplus) extern "C" { #endif __isl_give isl_val *isl_basic_set_min_lp_val(__isl_keep isl_basic_set *bset, __isl_keep isl_aff *obj); __isl_give isl_val *isl_basic_set_max_lp_val(__isl_keep isl_basic_set *bset, __isl_keep isl_aff *obj); #if defined(__cplusplus) } #endif #endif
endlessm/chromium-browser
third_party/llvm/polly/lib/External/isl/include/isl/lp.h
C
bsd-3-clause
750
import createHyphenator, { HyphenationFunctionSync } from 'hyphen'; import hyphenationPatternsDe1996 from 'hyphen/patterns/de-1996'; import hyphenationPatternsHu from 'hyphen/patterns/hu'; import hyphenationPatternsEnGb from 'hyphen/patterns/en-gb'; import { hyphenate as hyphenateEnGbAsync } from 'hyphen/en-gb'; // Test with HTML const hyphenateDe1996 = createHyphenator(hyphenationPatternsDe1996, { hyphenChar: '-', html: true, }) as HyphenationFunctionSync; if (hyphenateDe1996('<section>Silbentrennung</section>') !== '<section>Sil-ben-tren-nung</section>') { throw new Error('Test failed'); } // Test with debug output const hyphenateHu = createHyphenator(hyphenationPatternsHu, { debug: true }) as HyphenationFunctionSync; if (hyphenateHu('szóelválasztás', { hyphenChar: '|' }) !== 'szó|el|vá|lasz|tás') { throw new Error('Test failed'); } // Test with async function returning a Promise hyphenateEnGbAsync('hyphenation', { hyphenChar: '#' }).then(result => { if (result !== 'hy#phen#a#tion') { throw new Error('Test failed'); } }); // Test with minWordLength (new option in version 1.6) const hyphenateEnUsSyncWithMinWordLength = createHyphenator(hyphenationPatternsEnGb, { hyphenChar: '-', minWordLength: 11, }) as HyphenationFunctionSync; if (hyphenateEnUsSyncWithMinWordLength('hyphenation') !== 'hy-phen-a-tion') { // hyphenation has 11 chars => hyphenate throw new Error('Test failed'); } if (hyphenateEnUsSyncWithMinWordLength('sabotaging') !== 'sabotaging') { // sabotaging has 10 chars => don't hyphenate throw new Error('Test failed'); }
markogresak/DefinitelyTyped
types/hyphen/hyphen-tests.ts
TypeScript
mit
1,621
/* Cubic Bezier Transition */ /*********** Page Header ***********/ /* Header search bar, toggler button & top menu */ .page-header.navbar { background-color: #2b3643; /* Top notification menu/bar */ /* Header seaech box */ /* Toggler button for sidebar expand/collapse and responsive sidebar menu */ } .page-header.navbar .top-menu .navbar-nav { /* Extended Dropdowns */ /* Notification */ /* Inbox */ /* Tasks */ /* User */ /* Language */ /* Dark version */ } .page-header.navbar .top-menu .navbar-nav > li.dropdown .dropdown-toggle > i { color: #79869a; } .page-header.navbar .top-menu .navbar-nav > li.dropdown .dropdown-toggle .badge.badge-default { background-color: #36c6d3; color: #ffffff; } .page-header.navbar .top-menu .navbar-nav > li.dropdown .dropdown-toggle:hover { background-color: #3f4f62; } .page-header.navbar .top-menu .navbar-nav > li.dropdown .dropdown-toggle:hover > i { color: #a4aebb; } .page-header.navbar .top-menu .navbar-nav > li.dropdown.open .dropdown-toggle { background-color: #3f4f62; } .page-header.navbar .top-menu .navbar-nav > li.dropdown.open .dropdown-toggle > i { color: #a4aebb; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-extended .dropdown-menu { border-color: #e7eaf0; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-extended .dropdown-menu:after { border-bottom-color: #eaedf2; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-extended .dropdown-menu > li.external { background: #eaedf2; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-extended .dropdown-menu > li.external > h3 { color: #62878f; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-extended .dropdown-menu > li.external > a { color: #337ab7; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-extended .dropdown-menu > li.external > a:hover { color: #23527c; text-decoration: none; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-extended .dropdown-menu .dropdown-menu-list > li > a { border-bottom: 1px solid #EFF2F6 !important; color: #888888; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-extended .dropdown-menu .dropdown-menu-list > li > a:hover { background: #f8f9fa; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-notification .dropdown-menu .dropdown-menu-list > li > a .time { background: #f1f1f1; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-notification .dropdown-menu .dropdown-menu-list > li > a:hover .time { background: #e4e4e4; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-inbox > .dropdown-toggle > .circle { background-color: #36c6d3; color: #ffffff; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-inbox > .dropdown-toggle > .corner { border-color: transparent transparent transparent #36c6d3; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-inbox .dropdown-menu .dropdown-menu-list .subject .from { color: #5b9bd1; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-tasks .dropdown-menu .dropdown-menu-list .progress { background-color: #dfe2e9; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-user > .dropdown-toggle > .username { color: #c6cfda; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-user > .dropdown-toggle > i { color: #c6cfda; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-user > .dropdown-menu { width: 195px; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-language > .dropdown-toggle > .langname { color: #c6cfda; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu { background: #3f4f62; border: 0; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu:after { border-bottom-color: #3f4f62; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu > li.external { background: #2f3b49; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu > li.external > h3 { color: #adbaca; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu > li.external > a:hover { color: #5496cf; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu.dropdown-menu-default > li a, .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu .dropdown-menu-list > li a { color: #bcc7d4; border-bottom: 1px solid #4b5e75 !important; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu.dropdown-menu-default > li a > i, .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu .dropdown-menu-list > li a > i { color: #9dadc0; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu.dropdown-menu-default > li a:hover, .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu .dropdown-menu-list > li a:hover { background: #47596e; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu.dropdown-menu-default > li a { border-bottom: 0 !important; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu.dropdown-menu-default > li.divider { background: #4b5e75; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-notification.dropdown-dark .dropdown-menu .dropdown-menu-list > li > a .time { background: #354353; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-notification.dropdown-dark .dropdown-menu .dropdown-menu-list > li > a:hover .time { background: #2b3643; } .page-header.navbar .search-form { background: #232c37; } .page-header.navbar .search-form:hover { background: #3f4f62; } .page-header.navbar .search-form .input-group .form-control { color: #959fad; } .page-header.navbar .search-form .input-group .form-control::-moz-placeholder { color: #929cab; opacity: 1; } .page-header.navbar .search-form .input-group .form-control:-ms-input-placeholder { color: #929cab; } .page-header.navbar .search-form .input-group .form-control::-webkit-input-placeholder { color: #929cab; } .page-header.navbar .search-form .input-group .input-group-btn .btn.submit > i { color: #959fad; } .page-header.navbar .search-form.open { background: #3f4f62; } .page-header.navbar .menu-toggler { background-image: url(../../img/sidebar_toggler_icon_darkblue.png); } /* Default Horizontal Menu */ .page-header.navbar { /* Default Mega Menu */ /* Light Mega Menu */ } .page-header.navbar .hor-menu .navbar-nav { /* Mega menu content */ /* Classic menu */ } .page-header.navbar .hor-menu .navbar-nav > li.mega-menu-dropdown > .dropdown-menu { box-shadow: 5px 5px rgba(63, 79, 98, 0.2); } .page-header.navbar .hor-menu .navbar-nav > li.mega-menu-dropdown > .dropdown-menu .mega-menu-content .mega-menu-submenu li > h3 { color: #c6cfda; } .page-header.navbar .hor-menu .navbar-nav > li > a { color: #c6cfda; } .page-header.navbar .hor-menu .navbar-nav > li > a > i { color: #788ea8; } .page-header.navbar .hor-menu .navbar-nav > li:hover > a, .page-header.navbar .hor-menu .navbar-nav > li.open > a, .page-header.navbar .hor-menu .navbar-nav > li > a:hover { color: #d5dce4; background: #3f4f62 !important; } .page-header.navbar .hor-menu .navbar-nav > li:hover > a > i, .page-header.navbar .hor-menu .navbar-nav > li.open > a > i, .page-header.navbar .hor-menu .navbar-nav > li > a:hover > i { color: #889bb2; } .page-header.navbar .hor-menu .navbar-nav > li.active > a, .page-header.navbar .hor-menu .navbar-nav > li.active > a, .page-header.navbar .hor-menu .navbar-nav > li.current > a, .page-header.navbar .hor-menu .navbar-nav > li.current > a { color: white; background: #36c6d3 !important; } .page-header.navbar .hor-menu .navbar-nav > li.active > a > i, .page-header.navbar .hor-menu .navbar-nav > li.active > a > i, .page-header.navbar .hor-menu .navbar-nav > li.current > a > i, .page-header.navbar .hor-menu .navbar-nav > li.current > a > i { color: #788ea8; } .page-header.navbar .hor-menu .navbar-nav > li.active .selected, .page-header.navbar .hor-menu .navbar-nav > li.current .selected { border-top: 6px solid #36c6d3; } .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu { box-shadow: 5px 5px rgba(63, 79, 98, 0.2); background: #3f4f62; } .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li > a { color: #c6cfda; } .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li > a > i { color: #c6cfda; } .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li:hover > a { color: #f1f3f6; background: #47596e; } .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li:hover > a > i { color: #f1f3f6; } .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li.active > a, .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li.active > a:hover, .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li.current > a, .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li.current > a:hover { color: #f1f3f6; background: #47596e; } .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li.active > a > i, .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li.active > a:hover > i, .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li.current > a > i, .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li.current > a:hover > i { color: #f1f3f6; } .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li.divider { background-color: #495c72; } .page-header.navbar .hor-menu .navbar-nav > li .dropdown-submenu > a:after { color: #c6cfda; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav { /* Mega menu content */ /* Classic menu */ } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.mega-menu-dropdown > .dropdown-menu { box-shadow: 5px 5px rgba(102, 102, 102, 0.1); } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.mega-menu-dropdown > .dropdown-menu .mega-menu-content .mega-menu-submenu li > h3 { color: #666; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li > a { color: #c6cfda; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li > a > i { color: #788ea8; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li:hover > a, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li > a:hover { color: #d5dce4; background: #3f4f62; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li:hover > a > i, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li > a:hover > i { color: #889bb2; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.open > a { color: #333 !important; background: white !important; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.open > a > i { color: #333 !important; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.active > a, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.active > a:hover, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.current > a, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.current > a:hover { color: white; background: #36c6d3; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.active > a > i, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.active > a:hover > i, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.current > a > i, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.current > a:hover > i { color: #788ea8; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu { box-shadow: 5px 5px rgba(102, 102, 102, 0.1); background: white; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li > a { color: #000; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li > a > i { color: #888; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li:hover > a { color: #000; background: whitesmoke; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li:hover > a > i { color: #666; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li.active > a, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li.active > a:hover, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li.current > a, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li.current > a:hover { color: #000; background: whitesmoke; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li.active > a > i, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li.active > a:hover > i, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li.current > a > i, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li.current > a:hover > i { color: #666; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li.divider { background-color: whitesmoke; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu { border: 1px solid #f2f2f2; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li > .dropdown-menu { border-top: 0; } /* Page sidebar */ .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover, .page-sidebar { background-color: #364150; /* Default sidebar */ /* light sidebar */ /* Sidebar search */ } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu, .page-sidebar .page-sidebar-menu { /* 1st level links */ /* All links */ } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li > a, .page-sidebar .page-sidebar-menu > li > a { border-top: 1px solid #3d4957; color: #b4bcc8; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li > a > i, .page-sidebar .page-sidebar-menu > li > a > i { color: #606C7D; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li > a > i[class^="icon-"], .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li > a > i[class*="icon-"], .page-sidebar .page-sidebar-menu > li > a > i[class^="icon-"], .page-sidebar .page-sidebar-menu > li > a > i[class*="icon-"] { color: #6b788b; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li > a > .arrow.open:before, .page-sidebar .page-sidebar-menu > li > a > .arrow:before, .page-sidebar .page-sidebar-menu > li > a > .arrow.open:before { color: #606C7D; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.heading > h3, .page-sidebar .page-sidebar-menu > li.heading > h3 { color: #708096; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li:hover > a, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.open > a, .page-sidebar .page-sidebar-menu > li:hover > a, .page-sidebar .page-sidebar-menu > li.open > a { background: #2C3542; color: #b4bcc8; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li:hover > a > i, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.open > a > i, .page-sidebar .page-sidebar-menu > li:hover > a > i, .page-sidebar .page-sidebar-menu > li.open > a > i { color: #606C7D; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li:hover > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li:hover > a > .arrow.open:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.open > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.open > a > .arrow.open:before, .page-sidebar .page-sidebar-menu > li:hover > a > .arrow:before, .page-sidebar .page-sidebar-menu > li:hover > a > .arrow.open:before, .page-sidebar .page-sidebar-menu > li.open > a > .arrow:before, .page-sidebar .page-sidebar-menu > li.open > a > .arrow.open:before { color: #606C7D; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active > a, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active.open > a, .page-sidebar .page-sidebar-menu > li.active > a, .page-sidebar .page-sidebar-menu > li.active.open > a { background: #36c6d3; border-top-color: transparent; color: #ffffff; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active > a:hover, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active.open > a:hover, .page-sidebar .page-sidebar-menu > li.active > a:hover, .page-sidebar .page-sidebar-menu > li.active.open > a:hover { background: #36c6d3; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active > a > i, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active.open > a > i, .page-sidebar .page-sidebar-menu > li.active > a > i, .page-sidebar .page-sidebar-menu > li.active.open > a > i { color: #ffffff; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active > a > .arrow.open:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active.open > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active.open > a > .arrow.open:before, .page-sidebar .page-sidebar-menu > li.active > a > .arrow:before, .page-sidebar .page-sidebar-menu > li.active > a > .arrow.open:before, .page-sidebar .page-sidebar-menu > li.active.open > a > .arrow:before, .page-sidebar .page-sidebar-menu > li.active.open > a > .arrow.open:before { color: #ffffff; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active + li > a, .page-sidebar .page-sidebar-menu > li.active + li > a { border-top-color: transparent; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active.open + li > a, .page-sidebar .page-sidebar-menu > li.active.open + li > a { border-top-color: #3d4957; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li:last-child > a, .page-sidebar .page-sidebar-menu > li:last-child > a { border-bottom: 1px solid transparent !important; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu li > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu li > a > .arrow.open:before, .page-sidebar .page-sidebar-menu li > a > .arrow:before, .page-sidebar .page-sidebar-menu li > a > .arrow.open:before { color: #606C7D; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu li:hover > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu li:hover > a > .arrow.open:before, .page-sidebar .page-sidebar-menu li:hover > a > .arrow:before, .page-sidebar .page-sidebar-menu li:hover > a > .arrow.open:before { color: #606C7D; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu li.active > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu li.active > a > .arrow.open:before, .page-sidebar .page-sidebar-menu li.active > a > .arrow:before, .page-sidebar .page-sidebar-menu li.active > a > .arrow.open:before { color: #ffffff; } .page-sidebar-closed .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu:hover .sub-menu, .page-sidebar-closed .page-sidebar .page-sidebar-menu:hover .sub-menu { background-color: #364150; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li > a, .page-sidebar .page-sidebar-menu .sub-menu > li > a { color: #b4bcc8; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li > a > i, .page-sidebar .page-sidebar-menu .sub-menu > li > a > i { color: #606C7D; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li > a > i[class^="icon-"], .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li > a > i[class*="icon-"], .page-sidebar .page-sidebar-menu .sub-menu > li > a > i[class^="icon-"], .page-sidebar .page-sidebar-menu .sub-menu > li > a > i[class*="icon-"] { color: #6b788b; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li > a > .arrow.open:before, .page-sidebar .page-sidebar-menu .sub-menu > li > a > .arrow:before, .page-sidebar .page-sidebar-menu .sub-menu > li > a > .arrow.open:before { color: #606C7D; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li:hover > a, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li.open > a, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li.active > a, .page-sidebar .page-sidebar-menu .sub-menu > li:hover > a, .page-sidebar .page-sidebar-menu .sub-menu > li.open > a, .page-sidebar .page-sidebar-menu .sub-menu > li.active > a { background: #3e4b5c !important; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li:hover > a > i, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li.open > a > i, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li.active > a > i, .page-sidebar .page-sidebar-menu .sub-menu > li:hover > a > i, .page-sidebar .page-sidebar-menu .sub-menu > li.open > a > i, .page-sidebar .page-sidebar-menu .sub-menu > li.active > a > i { color: #606C7D; color: #959fae; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li:hover > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li:hover > a > .arrow.open:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li.open > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li.open > a > .arrow.open:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li.active > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li.active > a > .arrow.open:before, .page-sidebar .page-sidebar-menu .sub-menu > li:hover > a > .arrow:before, .page-sidebar .page-sidebar-menu .sub-menu > li:hover > a > .arrow.open:before, .page-sidebar .page-sidebar-menu .sub-menu > li.open > a > .arrow:before, .page-sidebar .page-sidebar-menu .sub-menu > li.open > a > .arrow.open:before, .page-sidebar .page-sidebar-menu .sub-menu > li.active > a > .arrow:before, .page-sidebar .page-sidebar-menu .sub-menu > li.active > a > .arrow.open:before { color: #606C7D; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light { /* 1st level links */ } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li:hover > a, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.open > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li:hover > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.open > a { background: #3a4656; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active > a, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a { background: #3e4b5c; border-left: 4px solid #36c6d3; color: #f1f1f1; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active > a:hover, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a:hover, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active > a:hover, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a:hover { border-left: 4px solid #36c6d3; background: #3a4656; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active > a > i, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a > i, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active > a > i, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a > i { color: #eeeeee; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active > a > .arrow.open:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a > .arrow.open:before, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active > a > .arrow:before, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active > a > .arrow.open:before, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a > .arrow:before, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a > .arrow.open:before { color: #eeeeee; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu { background: #3a4656; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu > li:hover > a, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu > li.open > a, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu > li.active > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu > li:hover > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu > li.open > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu > li.active > a { background: #3e4b5c !important; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-toggler, .page-sidebar .sidebar-toggler { background: url(../../img/sidebar_inline_toggler_icon_darkblue.jpg); } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search .input-group, .page-sidebar .sidebar-search .input-group { border-bottom: 1px solid #435060; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search .input-group .form-control, .page-sidebar .sidebar-search .input-group .form-control { background-color: #364150; color: #4e5c6f; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search .input-group .form-control::-moz-placeholder, .page-sidebar .sidebar-search .input-group .form-control::-moz-placeholder { color: #4e5c6f; opacity: 1; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search .input-group .form-control:-ms-input-placeholder, .page-sidebar .sidebar-search .input-group .form-control:-ms-input-placeholder { color: #4e5c6f; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search .input-group .form-control::-webkit-input-placeholder, .page-sidebar .sidebar-search .input-group .form-control::-webkit-input-placeholder { color: #4e5c6f; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search .input-group .input-group-btn .btn > i, .page-sidebar .sidebar-search .input-group .input-group-btn .btn > i { color: #4e5c6f; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search.sidebar-search-bordered .input-group, .page-sidebar .sidebar-search.sidebar-search-bordered .input-group { border: 1px solid #435060; } .page-sidebar-closed .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search.open .input-group, .page-sidebar-closed .page-sidebar .sidebar-search.open .input-group { background-color: #364150; } .page-sidebar-closed .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search.open .remove > i, .page-sidebar-closed .page-sidebar .sidebar-search.open .remove > i { color: #4e5c6f; } .page-sidebar-closed .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search.sidebar-search-solid .input-group, .page-sidebar-closed .page-sidebar .sidebar-search.sidebar-search-solid .input-group { background: none; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search.sidebar-search-solid .input-group, .page-sidebar .sidebar-search.sidebar-search-solid .input-group { border: 1px solid #2c3541; background: #2c3541; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search.sidebar-search-solid .input-group .form-control, .page-sidebar .sidebar-search.sidebar-search-solid .input-group .form-control { background: #2c3541; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search.sidebar-search-solid.open .input-group, .page-sidebar .sidebar-search.sidebar-search-solid.open .input-group { border: 1px solid #364150; background: #364150; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search.sidebar-search-solid.open .input-group .form-control, .page-sidebar .sidebar-search.sidebar-search-solid.open .input-group .form-control { background: #364150; } .page-sidebar-reversed .page-sidebar-menu.page-sidebar-menu-light { /* 1st level links */ } .page-sidebar-reversed .page-sidebar-menu.page-sidebar-menu-light > li.active > a, .page-sidebar-reversed .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a { border-left: 0; border-right: 4px solid #36c6d3; } .page-sidebar-reversed .page-sidebar-menu.page-sidebar-menu-light > li.active > a:hover, .page-sidebar-reversed .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a:hover { border-left: 0; border-right: 4px solid #36c6d3; } /****** Page Footer ******/ .page-footer .page-footer-inner { color: #98a6ba; } .page-footer-fixed .page-footer { background-color: #28303b; } @media (min-width: 992px) { /* 992px */ /* Sidebar menu closed */ .page-sidebar-menu.page-sidebar-menu-hover-submenu > li:hover > .sub-menu { box-shadow: 5px 5px rgba(44, 53, 66, 0.2); } .page-sidebar-menu.page-sidebar-menu-hover-submenu > li:hover > .sub-menu.sidebar-toggler-wrapper, .page-sidebar-menu.page-sidebar-menu-hover-submenu > li:hover > .sub-menu.sidebar-search-wrapper { box-shadow: none; } .page-sidebar-menu.page-sidebar-menu-closed > li:hover { box-shadow: 5px 5px rgba(44, 53, 66, 0.2); } .page-sidebar-menu.page-sidebar-menu-closed > li:hover.sidebar-toggler-wrapper, .page-sidebar-menu.page-sidebar-menu-closed > li:hover.sidebar-search-wrapper { box-shadow: none; } .page-sidebar-menu.page-sidebar-menu-closed > li:hover > .sub-menu { box-shadow: 5px 5px rgba(44, 53, 66, 0.2); } .page-sidebar-menu.page-sidebar-menu-closed > li:hover > .sub-menu.sidebar-toggler-wrapper, .page-sidebar-menu.page-sidebar-menu-closed > li:hover > .sub-menu.sidebar-search-wrapper { box-shadow: none; } /* Light sidebar menu */ .page-sidebar-menu.page-sidebar-menu-light.page-sidebar-menu-closed > li.heading { padding: 0; margin-top: 15px; margin-bottom: 15px; border-top: 1px solid #3d4957 !important; } /* Fixed Sidebar */ .page-sidebar-fixed:not(.page-footer-fixed) .page-content { border-bottom: 0; } .page-sidebar-fixed:not(.page-footer-fixed) .page-footer { background-color: #fff; } .page-sidebar-fixed:not(.page-footer-fixed) .page-footer .page-footer-inner { color: #333; } /* Boxed Layout */ .page-boxed { background-color: #303a47 !important; /* Page container */ /* Page sidebar */ /* Page footer */ } .page-boxed .page-container { background-color: #364150; border-left: 1px solid #3d4957; border-bottom: 1px solid #3d4957; } .page-boxed.page-sidebar-reversed .page-container { border-left: 0; border-right: 1px solid #3d4957; } .page-boxed.page-sidebar-fixed .page-container { border-left: 0; border-bottom: 0; } .page-boxed.page-sidebar-reversed.page-sidebar-fixed .page-container { border-left: 0; border-right: 0; border-bottom: 0; } .page-boxed.page-sidebar-fixed .page-sidebar { border-left: 1px solid #3d4957; } .page-boxed.page-sidebar-reversed.page-sidebar-fixed .page-sidebar { border-right: 1px solid #3d4957; border-left: 0; } .page-boxed.page-sidebar-fixed.page-footer-fixed .page-footer { background-color: #303a47 !important; } .page-boxed.page-sidebar-fixed.page-footer-fixed .page-footer .page-footer-inner { color: #98a6ba; } /* Sidebar Menu Wirh Hoverable Submenu */ .page-sidebar-menu-hover-submenu li:hover a > .arrow { border-right: 8px solid #323c4b; } .page-sidebar-reversed .page-sidebar-menu-hover-submenu li:hover a > .arrow { border-left: 8px solid #323c4b; } .page-sidebar-menu-hover-submenu li:hover > .sub-menu { background: #323c4b !important; } } @media (max-width: 991px) { /* 991px */ /* Page sidebar */ .page-sidebar { background-color: #28303b; /* light sidebar */ } .page-sidebar .page-sidebar-menu > li > a { border-top: 1px solid #364150; } .page-sidebar .page-sidebar-menu > li:hover > a, .page-sidebar .page-sidebar-menu > li.open > a { background: #2e3744; } .page-sidebar .page-sidebar-menu > li:last-child > a { border-bottom: 0 !important; } .page-sidebar .page-sidebar-menu > li .sub-menu { background-color: #28303b !important; } .page-sidebar .page-sidebar-menu .sidebar-search input { background-color: #28303b !important; } .page-sidebar .page-sidebar-menu.page-sidebar-menu-light { /* 1st level links */ } .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li:hover > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.open > a { background: #2e3744; } .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a { background: #2e3744; } .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active > a:hover, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a:hover { background: #2e3744; } .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu { background: #28303b !important; } .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu > li:hover > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu > li.open > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu > li.active > a { background: #2e3744 !important; } } @media (max-width: 480px) { /* 480px */ .page-header.navbar { /* Top menu */ } .page-header.navbar .top-menu { background-color: #364150; } .page-header-fixed-mobile .page-header.navbar .top-menu { background-color: #2b3643; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-user .dropdown-toggle { background-color: #415265; } .page-header-fixed-mobile .page-header.navbar .top-menu .navbar-nav > li.dropdown-user .dropdown-toggle { background: none; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-user .dropdown-toggle:hover { background-color: #3f4f62; } } /**** Boby ****/ body { background-color: #364150; } /**** CSS3 Spinner Bar ****/ .page-spinner-bar > div, .block-spinner-bar > div { background: #4bccd8; }
asdlugo/encuesta
web/metronic/layouts/layout/css/themes/darkblue.css
CSS
mit
39,462
const express = require('express') const resorts = require('./resort-names.json') const { port=3333, delay=0 } = require('minimist')(process.argv) const cors = require('cors') const byName = name => resort => name.toLowerCase() === resort.substr(0, name.length).toLowerCase() const logger = (req, res, next) => { console.log(`${req.method} request for ${req.url}`) next() } const app = express() .use(logger) .use(cors()) .use('/', express.static('./dist/img')) .get('/resorts', (req, res) => res.status(200).json(resorts) ) .get('/resorts/:name', (req, res) => setTimeout(() => res.status(200).json( resorts.filter(byName(req.params.name)) ), delay ) ) app.listen(port, () => console.log('Ski resort app running on port ' + port + ' with a ' + delay/1000 + ' second delay'))
MoonTahoe/ski-day-counter-redux
server/index.js
JavaScript
mit
907
'use strict'; /* eslint import/no-extraneous-dependencies: off, global-require: off */ const $ = require('jquery'); const stripAnsi = require('strip-ansi'); const socket = require('./socket'); require('./style.css'); let hot = false; let currentHash = ''; $(function ready() { $('body').html(require('./page.pug')()); const status = $('#status'); const okness = $('#okness'); const $errors = $('#errors'); const iframe = $('#iframe'); const header = $('.header'); const contentPage = window.location.pathname.substr('/webpack-dev-server'.length) + window.location.search; status.text('Connecting to sockjs server...'); $errors.hide(); iframe.hide(); header.css({ borderColor: '#96b5b4' }); const onSocketMsg = { hot: function msgHot() { hot = true; iframe.attr('src', contentPage + window.location.hash); }, invalid: function msgInvalid() { okness.text(''); status.text('App updated. Recompiling...'); header.css({ borderColor: '#96b5b4' }); $errors.hide(); if (!hot) iframe.hide(); }, hash: function msgHash(hash) { currentHash = hash; }, 'still-ok': function stillOk() { okness.text(''); status.text('App ready.'); header.css({ borderColor: '' }); $errors.hide(); if (!hot) iframe.show(); }, ok: function msgOk() { okness.text(''); $errors.hide(); reloadApp(); }, warnings: function msgWarnings() { okness.text('Warnings while compiling.'); $errors.hide(); reloadApp(); }, errors: function msgErrors(errors) { status.text('App updated with errors. No reload!'); okness.text('Errors while compiling.'); $errors.text('\n' + stripAnsi(errors.join('\n\n\n')) + '\n\n'); header.css({ borderColor: '#ebcb8b' }); $errors.show(); iframe.hide(); }, close: function msgClose() { status.text(''); okness.text('Disconnected.'); $errors.text('\n\n\n Lost connection to webpack-dev-server.\n Please restart the server to reestablish connection...\n\n\n\n'); header.css({ borderColor: '#ebcb8b' }); $errors.show(); iframe.hide(); } }; socket('/sockjs-node', onSocketMsg); iframe.on('load', function load() { status.text('App ready.'); header.css({ borderColor: '' }); iframe.show(); }); function reloadApp() { if (hot) { status.text('App hot update.'); try { iframe[0].contentWindow.postMessage('webpackHotUpdate' + currentHash, '*'); } catch (e) { console.warn(e); // eslint-disable-line } iframe.show(); } else { status.text('App updated. Reloading app...'); header.css({ borderColor: '#96b5b4' }); try { let old = iframe[0].contentWindow.location + ''; if (old.indexOf('about') === 0) old = null; iframe.attr('src', old || (contentPage + window.location.hash)); if (old) { iframe[0].contentWindow.location.reload(); } } catch (e) { iframe.attr('src', contentPage + window.location.hash); } } } });
jotamaggi/react-calendar-app
node_modules/webpack-dev-server/client/live.js
JavaScript
mit
3,230
/*! * Sizzle CSS Selector Engine v2.2.1 * http://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2015-10-17 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // http://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, nidselect, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // ID selector if ( (m = match[1]) ) { // Document context if ( nodeType === 9 ) { if ( (elem = context.getElementById( m )) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && (elem = newContext.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !compilerCache[ selector + " " ] && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { if ( nodeType !== 1 ) { newContext = context; newSelector = selector; // qSA looks outside Element context, which is not what we want // Thanks to Andrew Dupont for this workaround technique // Support: IE <=8 // Exclude object elements } else if ( context.nodeName.toLowerCase() !== "object" ) { // Capture the context ID, setting it first if necessary if ( (nid = context.getAttribute( "id" )) ) { nid = nid.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", (nid = expando) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']"; while ( i-- ) { groups[i] = nidselect + " " + toSelector( groups[i] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, parent, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) if ( (parent = document.defaultView) && parent.top !== parent ) { // Support: IE 11 if ( parent.addEventListener ) { parent.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", unloadHandler ); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( document.createComment("") ); return !div.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var m = context.getElementById( id ); return m ? [ m ] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibing-combinator selector` fails if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && !compilerCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); uniqueCache[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); if ( (oldCache = uniqueCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context === document || context || outermost; } // Add elements passing elementMatchers directly to results // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; if ( !context && elem.ownerDocument !== document ) { setDocument( elem ); xml = !documentIsHTML; } while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context || document, xml) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // `i` is now the count of elements visited above, and adding it to `matchedCount` // makes the latter nonnegative. matchedCount += i; // Apply set filters to unmatched elements // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` // equals `i`), unless we didn't visit _any_ elements in the above loop because we have // no element matchers and no seed. // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that // case, which will result in a "00" `matchedCount` that differs from `i` but is also // numerically zero. if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is only one selector in the list and no seed // (the latter of which guarantees us context) if ( match.length === 1 ) { // Reduce context if the leading compound selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, !context || rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } // EXPOSE if ( typeof define === "function" && define.amd ) { define(function() { return Sizzle; }); // Sizzle requires that there be a global window in Common-JS like environments } else if ( typeof module !== "undefined" && module.exports ) { module.exports = Sizzle; } else { window.Sizzle = Sizzle; } // EXPOSE })( window );
arevaloarboled/multimedia
webrtc/src/callApp/client/public/bower_components/jquery/external/sizzle/dist/sizzle.js
JavaScript
mit
63,431
/* * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ /** * @test * @bug 8022718 * @summary Runtime accessibility checking: protected class, if extended, should be accessible from another package * * @compile -XDignore.symbol.file BogoLoader.java MethodInvoker.java Test.java anotherpkg/MethodSupplierOuter.java * @run main/othervm Test */ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.HashSet; import jdk.internal.org.objectweb.asm.ClassWriter; import jdk.internal.org.objectweb.asm.MethodVisitor; import jdk.internal.org.objectweb.asm.ClassVisitor; import jdk.internal.org.objectweb.asm.Opcodes; interface MyFunctionalInterface { void invokeMethodReference(); } class MakeProtected implements BogoLoader.VisitorMaker, Opcodes { final boolean whenVisitInner; MakeProtected(boolean when_visit_inner) { super(); whenVisitInner = when_visit_inner; } public ClassVisitor make(ClassVisitor cv) { return new ClassVisitor(Opcodes.ASM5, cv) { @Override public void visitInnerClass(String name, String outerName, String innerName, int access) { if (whenVisitInner) { int access_ = (ACC_PROTECTED | access) & ~(ACC_PRIVATE | ACC_PUBLIC); System.out.println("visitInnerClass: name = " + name + ", outerName = " + outerName + ", innerName = " + innerName + ", access original = 0x" + Integer.toHexString(access) + ", access modified to 0x" + Integer.toHexString(access_)); access = access_; } super.visitInnerClass(name, outerName, innerName, access); } }; } }; public class Test { public static void main(String argv[]) throws Exception, Throwable { BogoLoader.VisitorMaker makeProtectedNop = new MakeProtected(false); BogoLoader.VisitorMaker makeProtectedMod = new MakeProtected(true); int errors = 0; errors += tryModifiedInvocation(makeProtectedNop); errors += tryModifiedInvocation(makeProtectedMod); if (errors > 0) { throw new Error("FAIL; there were errors"); } } private static int tryModifiedInvocation(BogoLoader.VisitorMaker makeProtected) throws Throwable, ClassNotFoundException { HashMap<String, BogoLoader.VisitorMaker> replace = new HashMap<String, BogoLoader.VisitorMaker>(); replace.put("anotherpkg.MethodSupplierOuter$MethodSupplier", makeProtected); HashSet<String> in_bogus = new HashSet<String>(); in_bogus.add("MethodInvoker"); in_bogus.add("MyFunctionalInterface"); in_bogus.add("anotherpkg.MethodSupplierOuter"); // seems to be never loaded in_bogus.add("anotherpkg.MethodSupplierOuter$MethodSupplier"); BogoLoader bl = new BogoLoader(in_bogus, replace); try { Class<?> isw = bl.loadClass("MethodInvoker"); Method meth = isw.getMethod("invoke"); Object result = meth.invoke(null); } catch (Throwable th) { System.out.flush(); Thread.sleep(250); // Let Netbeans get its I/O sorted out. th.printStackTrace(); System.err.flush(); Thread.sleep(250); // Let Netbeans get its I/O sorted out. return 1; } return 0; } }
rokn/Count_Words_2015
testing/openjdk2/jdk/test/java/lang/invoke/accessProtectedSuper/Test.java
Java
mit
4,579
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Reflection.Emit.Tests { public class TypeBuilderDefineConstructor { public static IEnumerable<object[]> TestData() { yield return new object[] { MethodAttributes.Public, new Type[] { typeof(int), typeof(int) }, CallingConventions.HasThis }; yield return new object[] { MethodAttributes.Family, new Type[] { typeof(int), typeof(int) }, CallingConventions.HasThis }; yield return new object[] { MethodAttributes.Assembly, new Type[] { typeof(int), typeof(int) }, CallingConventions.HasThis }; yield return new object[] { MethodAttributes.Private, new Type[] { typeof(int), typeof(int) }, CallingConventions.HasThis }; yield return new object[] { MethodAttributes.PrivateScope, new Type[] { typeof(int), typeof(int) }, CallingConventions.HasThis }; yield return new object[] { MethodAttributes.FamORAssem, new Type[] { typeof(int), typeof(int) }, CallingConventions.HasThis }; yield return new object[] { MethodAttributes.FamANDAssem, new Type[] { typeof(int), typeof(int) }, CallingConventions.HasThis }; yield return new object[] { MethodAttributes.Final | MethodAttributes.Public, new Type[] { typeof(int), typeof(int) }, CallingConventions.HasThis }; yield return new object[] { MethodAttributes.Final | MethodAttributes.Family, new Type[] { typeof(int), typeof(int) }, CallingConventions.HasThis }; yield return new object[] { MethodAttributes.SpecialName | MethodAttributes.Family, new Type[] { typeof(int), typeof(int) }, CallingConventions.HasThis }; yield return new object[] { MethodAttributes.UnmanagedExport | MethodAttributes.Family, new Type[] { typeof(int), typeof(int) }, CallingConventions.HasThis }; yield return new object[] { MethodAttributes.RTSpecialName | MethodAttributes.Family, new Type[] { typeof(int), typeof(int) }, CallingConventions.HasThis }; yield return new object[] { MethodAttributes.HideBySig | MethodAttributes.Family, new Type[] { typeof(int), typeof(int) }, CallingConventions.HasThis }; yield return new object[] { MethodAttributes.Static, new Type[0], CallingConventions.Standard }; // Ignores any CallingConventions, sets to CallingConventions.Standard yield return new object[] { MethodAttributes.Public, new Type[0], CallingConventions.Any }; yield return new object[] { MethodAttributes.Public, new Type[0], CallingConventions.ExplicitThis }; yield return new object[] { MethodAttributes.Public, new Type[0], CallingConventions.HasThis }; yield return new object[] { MethodAttributes.Public, new Type[0], CallingConventions.Standard }; yield return new object[] { MethodAttributes.Public, new Type[0], CallingConventions.VarArgs }; } [Theory] [MemberData(nameof(TestData))] public void DefineConstructor(MethodAttributes attributes, Type[] parameterTypes, CallingConventions callingConvention) { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Class | TypeAttributes.Public); FieldBuilder fieldBuilderA = type.DefineField("TestField", typeof(int), FieldAttributes.Private); FieldBuilder fieldBuilderB = type.DefineField("TestField", typeof(int), FieldAttributes.Private); ConstructorBuilder constructor = type.DefineConstructor(attributes, callingConvention, parameterTypes); ILGenerator ctorIlGenerator = constructor.GetILGenerator(); if (parameterTypes.Length != 0) { // Calling base class constructor ctorIlGenerator.Emit(OpCodes.Ldarg_0); ctorIlGenerator.Emit(OpCodes.Call, typeof(object).GetConstructor(new Type[0])); ctorIlGenerator.Emit(OpCodes.Ldarg_0); ctorIlGenerator.Emit(OpCodes.Ldarg_1); ctorIlGenerator.Emit(OpCodes.Stfld, fieldBuilderA); ctorIlGenerator.Emit(OpCodes.Ldarg_0); ctorIlGenerator.Emit(OpCodes.Ldarg_2); ctorIlGenerator.Emit(OpCodes.Stfld, fieldBuilderB); } ctorIlGenerator.Emit(OpCodes.Ret); Helpers.VerifyConstructor(constructor, type, attributes, callingConvention, parameterTypes); } [Theory] [MemberData(nameof(TestData))] public void DefineConstructor_NullRequiredAndOptionalCustomModifiers(MethodAttributes attributes, Type[] parameterTypes, CallingConventions callingConvention) { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Class | TypeAttributes.Public); ConstructorBuilder constructor = type.DefineConstructor(attributes, callingConvention, parameterTypes); constructor.GetILGenerator().Emit(OpCodes.Ret); Helpers.VerifyConstructor(constructor, type, attributes, callingConvention, parameterTypes); } [Fact] public void DefineConstructor_StaticConstructorOnInterface() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public | TypeAttributes.Interface | TypeAttributes.Abstract); ConstructorBuilder constructor = type.DefineConstructor(MethodAttributes.Static, CallingConventions.Standard, new Type[0]); constructor.GetILGenerator().Emit(OpCodes.Ret); Type createdType = type.CreateTypeInfo().AsType(); Assert.Equal(1, createdType.GetConstructors(BindingFlags.Static | BindingFlags.NonPublic).Length); } [Fact] public void DefineConstructor_CalledTwice_Works() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public); type.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[0]).GetILGenerator().Emit(OpCodes.Ret); type.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[0]).GetILGenerator().Emit(OpCodes.Ret); Type createdType = type.CreateTypeInfo().AsType(); ConstructorInfo[] constructors = createdType.GetConstructors(); Assert.Equal(2, constructors.Length); Assert.Equal(constructors[0].GetParameters(), constructors[1].GetParameters()); } [Fact] public void DefineConstructor_TypeAlreadyCreated_ThrowsInvalidOperationException() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public); type.CreateTypeInfo().AsType(); Assert.Throws<InvalidOperationException>(() => type.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[0])); } [Fact] public void DefineConstructor_InstanceOnInterface_ThrowsInvalidOperationException() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public | TypeAttributes.Interface | TypeAttributes.Abstract); Assert.Throws<InvalidOperationException>(() => type.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[0])); } [Fact] public void DefineConstructor_ConstructorNotCreated_ThrowsInvalidOperationExceptionOnCreation() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public); type.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[0]); Assert.Throws<InvalidOperationException>(() => type.CreateTypeInfo()); } [Theory] [InlineData(CallingConventions.Any)] [InlineData(CallingConventions.VarArgs)] [InlineData(CallingConventions.HasThis)] [InlineData(CallingConventions.ExplicitThis | CallingConventions.HasThis)] public void DefineConstructor_HasThisCallingConventionsForStaticMethod_ThrowsTypeLoadExceptionOnCreation(CallingConventions conventions) { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public); ConstructorBuilder constructor = type.DefineConstructor(MethodAttributes.Static, conventions, new Type[0]); constructor.GetILGenerator().Emit(OpCodes.Ret); Assert.Throws<TypeLoadException>(() => type.CreateTypeInfo()); } [Fact] public void GetConstructor_TypeNotCreated_ThrowsNotSupportedException() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public); Assert.Throws<NotSupportedException>(() => type.AsType().GetConstructor(new Type[0])); } [Fact] public void GetConstructors_TypeNotCreated_ThrowsNotSupportedException() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public); Assert.Throws<NotSupportedException>(() => type.AsType().GetConstructors()); } } }
shimingsg/corefx
src/System.Reflection.Emit/tests/TypeBuilder/TypeBuilderDefineConstructor.cs
C#
mit
9,095
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Collections; using System.Diagnostics.Tracing; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace System.Diagnostics.TraceSourceTests { public class CorrelationManagerTests { [Fact] public void CorrelationManager_CheckStack() { Trace.CorrelationManager.StartLogicalOperation("one"); Trace.CorrelationManager.StartLogicalOperation("two"); // 2 operations in progress ValidateStack(Trace.CorrelationManager.LogicalOperationStack, "two", "one"); Trace.CorrelationManager.StopLogicalOperation(); // 1 operation in progress ValidateStack(Trace.CorrelationManager.LogicalOperationStack, "one"); Trace.CorrelationManager.StopLogicalOperation(); // 0 operation in progress ValidateStack(Trace.CorrelationManager.LogicalOperationStack, Array.Empty<object>()); } [Fact] public void CorrelationManager_NullOperationId() { AssertExtensions.Throws<ArgumentNullException>("operationId", () => Trace.CorrelationManager.StartLogicalOperation(null)); } [Fact] public void CorrelationManager_EmptyStack() { Assert.Throws<InvalidOperationException>(() => Trace.CorrelationManager.StopLogicalOperation()); } [Fact] public void CorrelationManager_ActivityId() { Guid id = Guid.NewGuid(); Trace.CorrelationManager.ActivityId = id; Assert.Equal(id, Trace.CorrelationManager.ActivityId); } [Fact] public async Task CorrelationManager_MutateStackPush() { Guid id = Guid.NewGuid(); Trace.CorrelationManager.ActivityId = id; Trace.CorrelationManager.StartLogicalOperation(1); await Task.Yield(); Trace.CorrelationManager.LogicalOperationStack.Push(2); ValidateStack(Trace.CorrelationManager.LogicalOperationStack, 2, 1); } [Fact] public async Task CorrelationManager_MutateStackPop() { Guid id = Guid.NewGuid(); Trace.CorrelationManager.ActivityId = id; Trace.CorrelationManager.StartLogicalOperation(1); await Task.Yield(); Assert.Equal(1,Trace.CorrelationManager.LogicalOperationStack.Pop()); ValidateStack(Trace.CorrelationManager.LogicalOperationStack, Array.Empty<object>()); } [Fact] public async Task CorrelationManager_ActivityIdAcrossAwait() { Guid g = Guid.NewGuid(); Trace.CorrelationManager.ActivityId = g; Assert.Equal(g, Trace.CorrelationManager.ActivityId); await Task.Yield(); Assert.Equal(g, Trace.CorrelationManager.ActivityId); await Task.Delay(1); Assert.Equal(g, Trace.CorrelationManager.ActivityId); } [Fact] public async Task CorrelationManager_CorrelationAcrossAwait() { Guid g = Guid.NewGuid(); Trace.CorrelationManager.ActivityId = g; Assert.Equal(g, Trace.CorrelationManager.ActivityId); Trace.CorrelationManager.StartLogicalOperation("one"); // 1 operation in progress ValidateStack(Trace.CorrelationManager.LogicalOperationStack, "one"); Trace.CorrelationManager.StartLogicalOperation("two"); await Task.Yield(); // 2 operations in progress ValidateStack(Trace.CorrelationManager.LogicalOperationStack, "two", "one"); Trace.CorrelationManager.StopLogicalOperation(); ValidateStack(Trace.CorrelationManager.LogicalOperationStack, "one"); await Task.Delay(1); Trace.CorrelationManager.StopLogicalOperation(); ValidateStack(Trace.CorrelationManager.LogicalOperationStack); } private static void ValidateStack(Stack input, params object[] expectedContents) { Assert.Equal(expectedContents.Length, input.Count); // Note: this reverts the stack Stack currentStack = new Stack(input); // The expected values are passed in the order they are supposed to be in the original stack // so we need to match them from the end of the array since the stack is also reversed for (int i = expectedContents.Length - 1; i >= 0; i--) { Assert.Equal(expectedContents[i], currentStack.Pop()); } } } }
shimingsg/corefx
src/System.Diagnostics.TraceSource/tests/CorrelationManagerTests.cs
C#
mit
4,875
// Polyfills for SSR var isSSR = typeof window === 'undefined'; var HTMLElement = isSSR ? Object : window.HTMLElement; var File = isSSR ? Object : window.File; export { File as F, HTMLElement as H };
cdnjs/cdnjs
ajax/libs/buefy/0.9.9/esm/chunk-b9bdb0e4.js
JavaScript
mit
201
// { dg-options "-std=gnu++0x" } // 2008-05-20 Paolo Carlini <[email protected]> // // Copyright (C) 2008, 2009 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <type_traits> #include <testsuite_hooks.h> #include <testsuite_tr1.h> void test01() { bool test __attribute__((unused)) = true; using std::is_integral; using namespace __gnu_test; VERIFY( (test_category<is_integral, void>(false)) ); VERIFY( (test_category<is_integral, char>(true)) ); VERIFY( (test_category<is_integral, signed char>(true)) ); VERIFY( (test_category<is_integral, unsigned char>(true)) ); #ifdef _GLIBCXX_USE_WCHAR_T VERIFY( (test_category<is_integral, wchar_t>(true)) ); #endif VERIFY( (test_category<is_integral, char16_t>(true)) ); VERIFY( (test_category<is_integral, char32_t>(true)) ); VERIFY( (test_category<is_integral, short>(true)) ); VERIFY( (test_category<is_integral, unsigned short>(true)) ); VERIFY( (test_category<is_integral, int>(true)) ); VERIFY( (test_category<is_integral, unsigned int>(true)) ); VERIFY( (test_category<is_integral, long>(true)) ); VERIFY( (test_category<is_integral, unsigned long>(true)) ); VERIFY( (test_category<is_integral, long long>(true)) ); VERIFY( (test_category<is_integral, unsigned long long>(true)) ); VERIFY( (test_category<is_integral, float>(false)) ); VERIFY( (test_category<is_integral, double>(false)) ); VERIFY( (test_category<is_integral, long double>(false)) ); // Sanity check. VERIFY( (test_category<is_integral, ClassType>(false)) ); } int main() { test01(); return 0; }
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/libstdc++-v3/testsuite/20_util/is_integral/value.cc
C++
gpl-2.0
2,281
/* * Bluestone board support * * Copyright (c) 2010, Applied Micro Circuits Corporation * Author: Tirumala R Marri <[email protected]> * * SPDX-License-Identifier: GPL-2.0+ */ #include <common.h> #include <asm/apm821xx.h> #include <libfdt.h> #include <fdt_support.h> #include <i2c.h> #include <asm/processor.h> #include <asm/io.h> #include <asm/mmu.h> #include <asm/ppc4xx-gpio.h> int board_early_init_f(void) { /* * Setup the interrupt controller polarities, triggers, etc. */ mtdcr(UIC0SR, 0xffffffff); /* clear all */ mtdcr(UIC0ER, 0x00000000); /* disable all */ mtdcr(UIC0CR, 0x00000005); /* ATI & UIC1 crit are critical */ mtdcr(UIC0PR, 0xffffffff); /* per ref-board manual */ mtdcr(UIC0TR, 0x00000000); /* per ref-board manual */ mtdcr(UIC0VR, 0x00000000); /* int31 highest, base=0x000 */ mtdcr(UIC0SR, 0xffffffff); /* clear all */ mtdcr(UIC1SR, 0xffffffff); /* clear all */ mtdcr(UIC1ER, 0x00000000); /* disable all */ mtdcr(UIC1CR, 0x00000000); /* all non-critical */ mtdcr(UIC1PR, 0xffffffff); /* per ref-board manual */ mtdcr(UIC1TR, 0x00000000); /* per ref-board manual */ mtdcr(UIC1VR, 0x00000000); /* int31 highest, base=0x000 */ mtdcr(UIC1SR, 0xffffffff); /* clear all */ mtdcr(UIC2SR, 0xffffffff); /* clear all */ mtdcr(UIC2ER, 0x00000000); /* disable all */ mtdcr(UIC2CR, 0x00000000); /* all non-critical */ mtdcr(UIC2PR, 0xffffffff); /* per ref-board manual */ mtdcr(UIC2TR, 0x00000000); /* per ref-board manual */ mtdcr(UIC2VR, 0x00000000); /* int31 highest, base=0x000 */ mtdcr(UIC2SR, 0xffffffff); /* clear all */ mtdcr(UIC3SR, 0xffffffff); /* clear all */ mtdcr(UIC3ER, 0x00000000); /* disable all */ mtdcr(UIC3CR, 0x00000000); /* all non-critical */ mtdcr(UIC3PR, 0xffffffff); /* per ref-board manual */ mtdcr(UIC3TR, 0x00000000); /* per ref-board manual */ mtdcr(UIC3VR, 0x00000000); /* int31 highest, base=0x000 */ mtdcr(UIC3SR, 0xffffffff); /* clear all */ /* * Configure PFC (Pin Function Control) registers * UART0: 2 pins */ mtsdr(SDR0_PFC1, 0x0000000); return 0; } int checkboard(void) { char buf[64]; int i = getenv_f("serial#", buf, sizeof(buf)); puts("Board: Bluestone Evaluation Board"); if (i > 0) { puts(", serial# "); puts(buf); } putc('\n'); return 0; } int misc_init_r(void) { u32 sdr0_srst1 = 0; /* Setup PLB4-AHB bridge based on the system address map */ mtdcr(AHB_TOP, 0x8000004B); mtdcr(AHB_BOT, 0x8000004B); /* * The AHB Bridge core is held in reset after power-on or reset * so enable it now */ mfsdr(SDR0_SRST1, sdr0_srst1); sdr0_srst1 &= ~SDR0_SRST1_AHB; mtsdr(SDR0_SRST1, sdr0_srst1); return 0; }
r2t2sdr/r2t2
u-boot/board/amcc/bluestone/bluestone.c
C
gpl-3.0
2,631
/* * Copyright (c) 2016 Intel Corporation * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that copyright * notice and this permission notice appear in supporting documentation, and * that the name of the copyright holders not be used in advertising or * publicity pertaining to distribution of the software without specific, * written prior permission. The copyright holders make no representations * about the suitability of this software for any purpose. It is provided "as * is" without express or implied warranty. * * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include <drm/drmP.h> #include <drm/drm_crtc.h> #include <drm/drm_color_mgmt.h> #include "drm_crtc_internal.h" /** * DOC: overview * * Color management or color space adjustments is supported through a set of 5 * properties on the &drm_crtc object. They are set up by calling * drm_crtc_enable_color_mgmt(). * * "DEGAMMA_LUT”: * Blob property to set the degamma lookup table (LUT) mapping pixel data * from the framebuffer before it is given to the transformation matrix. * The data is interpreted as an array of &struct drm_color_lut elements. * Hardware might choose not to use the full precision of the LUT elements * nor use all the elements of the LUT (for example the hardware might * choose to interpolate between LUT[0] and LUT[4]). * * Setting this to NULL (blob property value set to 0) means a * linear/pass-thru gamma table should be used. This is generally the * driver boot-up state too. * * “DEGAMMA_LUT_SIZE”: * Unsinged range property to give the size of the lookup table to be set * on the DEGAMMA_LUT property (the size depends on the underlying * hardware). If drivers support multiple LUT sizes then they should * publish the largest size, and sub-sample smaller sized LUTs (e.g. for * split-gamma modes) appropriately. * * “CTM”: * Blob property to set the current transformation matrix (CTM) apply to * pixel data after the lookup through the degamma LUT and before the * lookup through the gamma LUT. The data is interpreted as a struct * &drm_color_ctm. * * Setting this to NULL (blob property value set to 0) means a * unit/pass-thru matrix should be used. This is generally the driver * boot-up state too. * * “GAMMA_LUT”: * Blob property to set the gamma lookup table (LUT) mapping pixel data * after the transformation matrix to data sent to the connector. The * data is interpreted as an array of &struct drm_color_lut elements. * Hardware might choose not to use the full precision of the LUT elements * nor use all the elements of the LUT (for example the hardware might * choose to interpolate between LUT[0] and LUT[4]). * * Setting this to NULL (blob property value set to 0) means a * linear/pass-thru gamma table should be used. This is generally the * driver boot-up state too. * * “GAMMA_LUT_SIZE”: * Unsigned range property to give the size of the lookup table to be set * on the GAMMA_LUT property (the size depends on the underlying hardware). * If drivers support multiple LUT sizes then they should publish the * largest size, and sub-sample smaller sized LUTs (e.g. for split-gamma * modes) appropriately. * * There is also support for a legacy gamma table, which is set up by calling * drm_mode_crtc_set_gamma_size(). Drivers which support both should use * drm_atomic_helper_legacy_gamma_set() to alias the legacy gamma ramp with the * "GAMMA_LUT" property above. */ /** * drm_color_lut_extract - clamp and round LUT entries * @user_input: input value * @bit_precision: number of bits the hw LUT supports * * Extract a degamma/gamma LUT value provided by user (in the form of * &drm_color_lut entries) and round it to the precision supported by the * hardware. */ uint32_t drm_color_lut_extract(uint32_t user_input, uint32_t bit_precision) { uint32_t val = user_input; uint32_t max = 0xffff >> (16 - bit_precision); /* Round only if we're not using full precision. */ if (bit_precision < 16) { val += 1UL << (16 - bit_precision - 1); val >>= 16 - bit_precision; } return clamp_val(val, 0, max); } EXPORT_SYMBOL(drm_color_lut_extract); /** * drm_crtc_enable_color_mgmt - enable color management properties * @crtc: DRM CRTC * @degamma_lut_size: the size of the degamma lut (before CSC) * @has_ctm: whether to attach ctm_property for CSC matrix * @gamma_lut_size: the size of the gamma lut (after CSC) * * This function lets the driver enable the color correction * properties on a CRTC. This includes 3 degamma, csc and gamma * properties that userspace can set and 2 size properties to inform * the userspace of the lut sizes. Each of the properties are * optional. The gamma and degamma properties are only attached if * their size is not 0 and ctm_property is only attached if has_ctm is * true. */ void drm_crtc_enable_color_mgmt(struct drm_crtc *crtc, uint degamma_lut_size, bool has_ctm, uint gamma_lut_size) { struct drm_device *dev = crtc->dev; struct drm_mode_config *config = &dev->mode_config; if (degamma_lut_size) { drm_object_attach_property(&crtc->base, config->degamma_lut_property, 0); drm_object_attach_property(&crtc->base, config->degamma_lut_size_property, degamma_lut_size); } if (has_ctm) drm_object_attach_property(&crtc->base, config->ctm_property, 0); if (gamma_lut_size) { drm_object_attach_property(&crtc->base, config->gamma_lut_property, 0); drm_object_attach_property(&crtc->base, config->gamma_lut_size_property, gamma_lut_size); } } EXPORT_SYMBOL(drm_crtc_enable_color_mgmt); /** * drm_mode_crtc_set_gamma_size - set the gamma table size * @crtc: CRTC to set the gamma table size for * @gamma_size: size of the gamma table * * Drivers which support gamma tables should set this to the supported gamma * table size when initializing the CRTC. Currently the drm core only supports a * fixed gamma table size. * * Returns: * Zero on success, negative errno on failure. */ int drm_mode_crtc_set_gamma_size(struct drm_crtc *crtc, int gamma_size) { uint16_t *r_base, *g_base, *b_base; int i; crtc->gamma_size = gamma_size; crtc->gamma_store = kcalloc(gamma_size, sizeof(uint16_t) * 3, GFP_KERNEL); if (!crtc->gamma_store) { crtc->gamma_size = 0; return -ENOMEM; } r_base = crtc->gamma_store; g_base = r_base + gamma_size; b_base = g_base + gamma_size; for (i = 0; i < gamma_size; i++) { r_base[i] = i << 8; g_base[i] = i << 8; b_base[i] = i << 8; } return 0; } EXPORT_SYMBOL(drm_mode_crtc_set_gamma_size); /** * drm_mode_gamma_set_ioctl - set the gamma table * @dev: DRM device * @data: ioctl data * @file_priv: DRM file info * * Set the gamma table of a CRTC to the one passed in by the user. Userspace can * inquire the required gamma table size through drm_mode_gamma_get_ioctl. * * Called by the user via ioctl. * * Returns: * Zero on success, negative errno on failure. */ int drm_mode_gamma_set_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_mode_crtc_lut *crtc_lut = data; struct drm_crtc *crtc; void *r_base, *g_base, *b_base; int size; struct drm_modeset_acquire_ctx ctx; int ret = 0; if (!drm_core_check_feature(dev, DRIVER_MODESET)) return -EINVAL; crtc = drm_crtc_find(dev, crtc_lut->crtc_id); if (!crtc) return -ENOENT; if (crtc->funcs->gamma_set == NULL) return -ENOSYS; /* memcpy into gamma store */ if (crtc_lut->gamma_size != crtc->gamma_size) return -EINVAL; drm_modeset_acquire_init(&ctx, 0); retry: ret = drm_modeset_lock_all_ctx(dev, &ctx); if (ret) goto out; size = crtc_lut->gamma_size * (sizeof(uint16_t)); r_base = crtc->gamma_store; if (copy_from_user(r_base, (void __user *)(unsigned long)crtc_lut->red, size)) { ret = -EFAULT; goto out; } g_base = r_base + size; if (copy_from_user(g_base, (void __user *)(unsigned long)crtc_lut->green, size)) { ret = -EFAULT; goto out; } b_base = g_base + size; if (copy_from_user(b_base, (void __user *)(unsigned long)crtc_lut->blue, size)) { ret = -EFAULT; goto out; } ret = crtc->funcs->gamma_set(crtc, r_base, g_base, b_base, crtc->gamma_size, &ctx); out: if (ret == -EDEADLK) { drm_modeset_backoff(&ctx); goto retry; } drm_modeset_drop_locks(&ctx); drm_modeset_acquire_fini(&ctx); return ret; } /** * drm_mode_gamma_get_ioctl - get the gamma table * @dev: DRM device * @data: ioctl data * @file_priv: DRM file info * * Copy the current gamma table into the storage provided. This also provides * the gamma table size the driver expects, which can be used to size the * allocated storage. * * Called by the user via ioctl. * * Returns: * Zero on success, negative errno on failure. */ int drm_mode_gamma_get_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_mode_crtc_lut *crtc_lut = data; struct drm_crtc *crtc; void *r_base, *g_base, *b_base; int size; int ret = 0; if (!drm_core_check_feature(dev, DRIVER_MODESET)) return -EINVAL; crtc = drm_crtc_find(dev, crtc_lut->crtc_id); if (!crtc) return -ENOENT; /* memcpy into gamma store */ if (crtc_lut->gamma_size != crtc->gamma_size) return -EINVAL; drm_modeset_lock(&crtc->mutex, NULL); size = crtc_lut->gamma_size * (sizeof(uint16_t)); r_base = crtc->gamma_store; if (copy_to_user((void __user *)(unsigned long)crtc_lut->red, r_base, size)) { ret = -EFAULT; goto out; } g_base = r_base + size; if (copy_to_user((void __user *)(unsigned long)crtc_lut->green, g_base, size)) { ret = -EFAULT; goto out; } b_base = g_base + size; if (copy_to_user((void __user *)(unsigned long)crtc_lut->blue, b_base, size)) { ret = -EFAULT; goto out; } out: drm_modeset_unlock(&crtc->mutex); return ret; }
mkvdv/au-linux-kernel-autumn-2017
linux/drivers/gpu/drm/drm_color_mgmt.c
C
gpl-3.0
10,467
<?php /** * @package Grav\Framework\Collection * * @copyright Copyright (C) 2014 - 2017 RocketTheme, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Collection; use Doctrine\Common\Collections\AbstractLazyCollection as BaseAbstractLazyCollection; /** * General JSON serializable collection. * * @package Grav\Framework\Collection */ abstract class AbstractLazyCollection extends BaseAbstractLazyCollection implements CollectionInterface { /** * The backed collection to use * * @var ArrayCollection */ protected $collection; /** * {@inheritDoc} */ public function reverse() { $this->initialize(); return $this->collection->reverse(); } /** * {@inheritDoc} */ public function shuffle() { $this->initialize(); return $this->collection->shuffle(); } /** * {@inheritDoc} */ public function jsonSerialize() { $this->initialize(); return $this->collection->jsonSerialize(); } }
bkostrowiecki/devnote
www/system/src/Grav/Framework/Collection/AbstractLazyCollection.php
PHP
gpl-3.0
1,108
/** * jQuery EasyUI 1.4.4 * * Copyright (c) 2009-2015 www.jeasyui.com. All rights reserved. * * Licensed under the freeware license: http://www.jeasyui.com/license_freeware.php * To use it on other terms please contact us: [email protected] * */ (function($){ $.fn._remove=function(){ return this.each(function(){ $(this).remove(); try{ this.outerHTML=""; } catch(err){ } }); }; function _1(_2){ _2._remove(); }; function _3(_4,_5){ var _6=$.data(_4,"panel"); var _7=_6.options; var _8=_6.panel; var _9=_8.children(".panel-header"); var _a=_8.children(".panel-body"); var _b=_8.children(".panel-footer"); if(_5){ $.extend(_7,{width:_5.width,height:_5.height,minWidth:_5.minWidth,maxWidth:_5.maxWidth,minHeight:_5.minHeight,maxHeight:_5.maxHeight,left:_5.left,top:_5.top}); } _8._size(_7); _9.add(_a)._outerWidth(_8.width()); if(!isNaN(parseInt(_7.height))){ _a._outerHeight(_8.height()-_9._outerHeight()-_b._outerHeight()); }else{ _a.css("height",""); var _c=$.parser.parseValue("minHeight",_7.minHeight,_8.parent()); var _d=$.parser.parseValue("maxHeight",_7.maxHeight,_8.parent()); var _e=_9._outerHeight()+_b._outerHeight()+_8._outerHeight()-_8.height(); _a._size("minHeight",_c?(_c-_e):""); _a._size("maxHeight",_d?(_d-_e):""); } _8.css({height:"",minHeight:"",maxHeight:"",left:_7.left,top:_7.top}); _7.onResize.apply(_4,[_7.width,_7.height]); $(_4).panel("doLayout"); }; function _f(_10,_11){ var _12=$.data(_10,"panel").options; var _13=$.data(_10,"panel").panel; if(_11){ if(_11.left!=null){ _12.left=_11.left; } if(_11.top!=null){ _12.top=_11.top; } } _13.css({left:_12.left,top:_12.top}); _12.onMove.apply(_10,[_12.left,_12.top]); }; function _14(_15){ $(_15).addClass("panel-body")._size("clear"); var _16=$("<div class=\"panel\"></div>").insertBefore(_15); _16[0].appendChild(_15); _16.bind("_resize",function(e,_17){ if($(this).hasClass("easyui-fluid")||_17){ _3(_15); } return false; }); return _16; }; function _18(_19){ var _1a=$.data(_19,"panel"); var _1b=_1a.options; var _1c=_1a.panel; _1c.css(_1b.style); _1c.addClass(_1b.cls); _1d(); _1e(); var _1f=$(_19).panel("header"); var _20=$(_19).panel("body"); var _21=$(_19).siblings(".panel-footer"); if(_1b.border){ _1f.removeClass("panel-header-noborder"); _20.removeClass("panel-body-noborder"); _21.removeClass("panel-footer-noborder"); }else{ _1f.addClass("panel-header-noborder"); _20.addClass("panel-body-noborder"); _21.addClass("panel-footer-noborder"); } _1f.addClass(_1b.headerCls); _20.addClass(_1b.bodyCls); $(_19).attr("id",_1b.id||""); if(_1b.content){ $(_19).panel("clear"); $(_19).html(_1b.content); $.parser.parse($(_19)); } function _1d(){ if(_1b.noheader||(!_1b.title&&!_1b.header)){ _1(_1c.children(".panel-header")); _1c.children(".panel-body").addClass("panel-body-noheader"); }else{ if(_1b.header){ $(_1b.header).addClass("panel-header").prependTo(_1c); }else{ var _22=_1c.children(".panel-header"); if(!_22.length){ _22=$("<div class=\"panel-header\"></div>").prependTo(_1c); } if(!$.isArray(_1b.tools)){ _22.find("div.panel-tool .panel-tool-a").appendTo(_1b.tools); } _22.empty(); var _23=$("<div class=\"panel-title\"></div>").html(_1b.title).appendTo(_22); if(_1b.iconCls){ _23.addClass("panel-with-icon"); $("<div class=\"panel-icon\"></div>").addClass(_1b.iconCls).appendTo(_22); } var _24=$("<div class=\"panel-tool\"></div>").appendTo(_22); _24.bind("click",function(e){ e.stopPropagation(); }); if(_1b.tools){ if($.isArray(_1b.tools)){ $.map(_1b.tools,function(t){ _25(_24,t.iconCls,eval(t.handler)); }); }else{ $(_1b.tools).children().each(function(){ $(this).addClass($(this).attr("iconCls")).addClass("panel-tool-a").appendTo(_24); }); } } if(_1b.collapsible){ _25(_24,"panel-tool-collapse",function(){ if(_1b.collapsed==true){ _4d(_19,true); }else{ _3b(_19,true); } }); } if(_1b.minimizable){ _25(_24,"panel-tool-min",function(){ _58(_19); }); } if(_1b.maximizable){ _25(_24,"panel-tool-max",function(){ if(_1b.maximized==true){ _5c(_19); }else{ _3a(_19); } }); } if(_1b.closable){ _25(_24,"panel-tool-close",function(){ _3c(_19); }); } } _1c.children("div.panel-body").removeClass("panel-body-noheader"); } }; function _25(c,_26,_27){ var a=$("<a href=\"javascript:void(0)\"></a>").addClass(_26).appendTo(c); a.bind("click",_27); }; function _1e(){ if(_1b.footer){ $(_1b.footer).addClass("panel-footer").appendTo(_1c); $(_19).addClass("panel-body-nobottom"); }else{ _1c.children(".panel-footer").remove(); $(_19).removeClass("panel-body-nobottom"); } }; }; function _28(_29,_2a){ var _2b=$.data(_29,"panel"); var _2c=_2b.options; if(_2d){ _2c.queryParams=_2a; } if(!_2c.href){ return; } if(!_2b.isLoaded||!_2c.cache){ var _2d=$.extend({},_2c.queryParams); if(_2c.onBeforeLoad.call(_29,_2d)==false){ return; } _2b.isLoaded=false; $(_29).panel("clear"); if(_2c.loadingMessage){ $(_29).html($("<div class=\"panel-loading\"></div>").html(_2c.loadingMessage)); } _2c.loader.call(_29,_2d,function(_2e){ var _2f=_2c.extractor.call(_29,_2e); $(_29).html(_2f); $.parser.parse($(_29)); _2c.onLoad.apply(_29,arguments); _2b.isLoaded=true; },function(){ _2c.onLoadError.apply(_29,arguments); }); } }; function _30(_31){ var t=$(_31); t.find(".combo-f").each(function(){ $(this).combo("destroy"); }); t.find(".m-btn").each(function(){ $(this).menubutton("destroy"); }); t.find(".s-btn").each(function(){ $(this).splitbutton("destroy"); }); t.find(".tooltip-f").each(function(){ $(this).tooltip("destroy"); }); t.children("div").each(function(){ $(this)._size("unfit"); }); t.empty(); }; function _32(_33){ $(_33).panel("doLayout",true); }; function _34(_35,_36){ var _37=$.data(_35,"panel").options; var _38=$.data(_35,"panel").panel; if(_36!=true){ if(_37.onBeforeOpen.call(_35)==false){ return; } } _38.stop(true,true); if($.isFunction(_37.openAnimation)){ _37.openAnimation.call(_35,cb); }else{ switch(_37.openAnimation){ case "slide": _38.slideDown(_37.openDuration,cb); break; case "fade": _38.fadeIn(_37.openDuration,cb); break; case "show": _38.show(_37.openDuration,cb); break; default: _38.show(); cb(); } } function cb(){ _37.closed=false; _37.minimized=false; var _39=_38.children(".panel-header").find("a.panel-tool-restore"); if(_39.length){ _37.maximized=true; } _37.onOpen.call(_35); if(_37.maximized==true){ _37.maximized=false; _3a(_35); } if(_37.collapsed==true){ _37.collapsed=false; _3b(_35); } if(!_37.collapsed){ _28(_35); _32(_35); } }; }; function _3c(_3d,_3e){ var _3f=$.data(_3d,"panel").options; var _40=$.data(_3d,"panel").panel; if(_3e!=true){ if(_3f.onBeforeClose.call(_3d)==false){ return; } } _40.stop(true,true); _40._size("unfit"); if($.isFunction(_3f.closeAnimation)){ _3f.closeAnimation.call(_3d,cb); }else{ switch(_3f.closeAnimation){ case "slide": _40.slideUp(_3f.closeDuration,cb); break; case "fade": _40.fadeOut(_3f.closeDuration,cb); break; case "hide": _40.hide(_3f.closeDuration,cb); break; default: _40.hide(); cb(); } } function cb(){ _3f.closed=true; _3f.onClose.call(_3d); }; }; function _41(_42,_43){ var _44=$.data(_42,"panel"); var _45=_44.options; var _46=_44.panel; if(_43!=true){ if(_45.onBeforeDestroy.call(_42)==false){ return; } } $(_42).panel("clear").panel("clear","footer"); _1(_46); _45.onDestroy.call(_42); }; function _3b(_47,_48){ var _49=$.data(_47,"panel").options; var _4a=$.data(_47,"panel").panel; var _4b=_4a.children(".panel-body"); var _4c=_4a.children(".panel-header").find("a.panel-tool-collapse"); if(_49.collapsed==true){ return; } _4b.stop(true,true); if(_49.onBeforeCollapse.call(_47)==false){ return; } _4c.addClass("panel-tool-expand"); if(_48==true){ _4b.slideUp("normal",function(){ _49.collapsed=true; _49.onCollapse.call(_47); }); }else{ _4b.hide(); _49.collapsed=true; _49.onCollapse.call(_47); } }; function _4d(_4e,_4f){ var _50=$.data(_4e,"panel").options; var _51=$.data(_4e,"panel").panel; var _52=_51.children(".panel-body"); var _53=_51.children(".panel-header").find("a.panel-tool-collapse"); if(_50.collapsed==false){ return; } _52.stop(true,true); if(_50.onBeforeExpand.call(_4e)==false){ return; } _53.removeClass("panel-tool-expand"); if(_4f==true){ _52.slideDown("normal",function(){ _50.collapsed=false; _50.onExpand.call(_4e); _28(_4e); _32(_4e); }); }else{ _52.show(); _50.collapsed=false; _50.onExpand.call(_4e); _28(_4e); _32(_4e); } }; function _3a(_54){ var _55=$.data(_54,"panel").options; var _56=$.data(_54,"panel").panel; var _57=_56.children(".panel-header").find("a.panel-tool-max"); if(_55.maximized==true){ return; } _57.addClass("panel-tool-restore"); if(!$.data(_54,"panel").original){ $.data(_54,"panel").original={width:_55.width,height:_55.height,left:_55.left,top:_55.top,fit:_55.fit}; } _55.left=0; _55.top=0; _55.fit=true; _3(_54); _55.minimized=false; _55.maximized=true; _55.onMaximize.call(_54); }; function _58(_59){ var _5a=$.data(_59,"panel").options; var _5b=$.data(_59,"panel").panel; _5b._size("unfit"); _5b.hide(); _5a.minimized=true; _5a.maximized=false; _5a.onMinimize.call(_59); }; function _5c(_5d){ var _5e=$.data(_5d,"panel").options; var _5f=$.data(_5d,"panel").panel; var _60=_5f.children(".panel-header").find("a.panel-tool-max"); if(_5e.maximized==false){ return; } _5f.show(); _60.removeClass("panel-tool-restore"); $.extend(_5e,$.data(_5d,"panel").original); _3(_5d); _5e.minimized=false; _5e.maximized=false; $.data(_5d,"panel").original=null; _5e.onRestore.call(_5d); }; function _61(_62,_63){ $.data(_62,"panel").options.title=_63; $(_62).panel("header").find("div.panel-title").html(_63); }; var _64=null; $(window).unbind(".panel").bind("resize.panel",function(){ if(_64){ clearTimeout(_64); } _64=setTimeout(function(){ var _65=$("body.layout"); if(_65.length){ _65.layout("resize"); $("body").children(".easyui-fluid:visible").each(function(){ $(this).triggerHandler("_resize"); }); }else{ $("body").panel("doLayout"); } _64=null; },100); }); $.fn.panel=function(_66,_67){ if(typeof _66=="string"){ return $.fn.panel.methods[_66](this,_67); } _66=_66||{}; return this.each(function(){ var _68=$.data(this,"panel"); var _69; if(_68){ _69=$.extend(_68.options,_66); _68.isLoaded=false; }else{ _69=$.extend({},$.fn.panel.defaults,$.fn.panel.parseOptions(this),_66); $(this).attr("title",""); _68=$.data(this,"panel",{options:_69,panel:_14(this),isLoaded:false}); } _18(this); if(_69.doSize==true){ _68.panel.css("display","block"); _3(this); } if(_69.closed==true||_69.minimized==true){ _68.panel.hide(); }else{ _34(this); } }); }; $.fn.panel.methods={options:function(jq){ return $.data(jq[0],"panel").options; },panel:function(jq){ return $.data(jq[0],"panel").panel; },header:function(jq){ return $.data(jq[0],"panel").panel.children(".panel-header"); },footer:function(jq){ return jq.panel("panel").children(".panel-footer"); },body:function(jq){ return $.data(jq[0],"panel").panel.children(".panel-body"); },setTitle:function(jq,_6a){ return jq.each(function(){ _61(this,_6a); }); },open:function(jq,_6b){ return jq.each(function(){ _34(this,_6b); }); },close:function(jq,_6c){ return jq.each(function(){ _3c(this,_6c); }); },destroy:function(jq,_6d){ return jq.each(function(){ _41(this,_6d); }); },clear:function(jq,_6e){ return jq.each(function(){ _30(_6e=="footer"?$(this).panel("footer"):this); }); },refresh:function(jq,_6f){ return jq.each(function(){ var _70=$.data(this,"panel"); _70.isLoaded=false; if(_6f){ if(typeof _6f=="string"){ _70.options.href=_6f; }else{ _70.options.queryParams=_6f; } } _28(this); }); },resize:function(jq,_71){ return jq.each(function(){ _3(this,_71); }); },doLayout:function(jq,all){ return jq.each(function(){ _72(this,"body"); _72($(this).siblings(".panel-footer")[0],"footer"); function _72(_73,_74){ if(!_73){ return; } var _75=_73==$("body")[0]; var s=$(_73).find("div.panel:visible,div.accordion:visible,div.tabs-container:visible,div.layout:visible,.easyui-fluid:visible").filter(function(_76,el){ var p=$(el).parents(".panel-"+_74+":first"); return _75?p.length==0:p[0]==_73; }); s.each(function(){ $(this).triggerHandler("_resize",[all||false]); }); }; }); },move:function(jq,_77){ return jq.each(function(){ _f(this,_77); }); },maximize:function(jq){ return jq.each(function(){ _3a(this); }); },minimize:function(jq){ return jq.each(function(){ _58(this); }); },restore:function(jq){ return jq.each(function(){ _5c(this); }); },collapse:function(jq,_78){ return jq.each(function(){ _3b(this,_78); }); },expand:function(jq,_79){ return jq.each(function(){ _4d(this,_79); }); }}; $.fn.panel.parseOptions=function(_7a){ var t=$(_7a); var hh=t.children(".panel-header,header"); var ff=t.children(".panel-footer,footer"); return $.extend({},$.parser.parseOptions(_7a,["id","width","height","left","top","title","iconCls","cls","headerCls","bodyCls","tools","href","method","header","footer",{cache:"boolean",fit:"boolean",border:"boolean",noheader:"boolean"},{collapsible:"boolean",minimizable:"boolean",maximizable:"boolean"},{closable:"boolean",collapsed:"boolean",minimized:"boolean",maximized:"boolean",closed:"boolean"},"openAnimation","closeAnimation",{openDuration:"number",closeDuration:"number"},]),{loadingMessage:(t.attr("loadingMessage")!=undefined?t.attr("loadingMessage"):undefined),header:(hh.length?hh.removeClass("panel-header"):undefined),footer:(ff.length?ff.removeClass("panel-footer"):undefined)}); }; $.fn.panel.defaults={id:null,title:null,iconCls:null,width:"auto",height:"auto",left:null,top:null,cls:null,headerCls:null,bodyCls:null,style:{},href:null,cache:true,fit:false,border:true,doSize:true,noheader:false,content:null,collapsible:false,minimizable:false,maximizable:false,closable:false,collapsed:false,minimized:false,maximized:false,closed:false,openAnimation:false,openDuration:400,closeAnimation:false,closeDuration:400,tools:null,footer:null,header:null,queryParams:{},method:"get",href:null,loadingMessage:"Loading...",loader:function(_7b,_7c,_7d){ var _7e=$(this).panel("options"); if(!_7e.href){ return false; } $.ajax({type:_7e.method,url:_7e.href,cache:false,data:_7b,dataType:"html",success:function(_7f){ _7c(_7f); },error:function(){ _7d.apply(this,arguments); }}); },extractor:function(_80){ var _81=/<body[^>]*>((.|[\n\r])*)<\/body>/im; var _82=_81.exec(_80); if(_82){ return _82[1]; }else{ return _80; } },onBeforeLoad:function(_83){ },onLoad:function(){ },onLoadError:function(){ },onBeforeOpen:function(){ },onOpen:function(){ },onBeforeClose:function(){ },onClose:function(){ },onBeforeDestroy:function(){ },onDestroy:function(){ },onResize:function(_84,_85){ },onMove:function(_86,top){ },onMaximize:function(){ },onRestore:function(){ },onMinimize:function(){ },onBeforeCollapse:function(){ },onBeforeExpand:function(){ },onCollapse:function(){ },onExpand:function(){ }}; })(jQuery);
czhevaz/gtm
web-app/js/jquery-easyui/plugins/jquery.panel.js
JavaScript
gpl-3.0
14,632
<?php final class FundInitiativeIndexer extends PhabricatorSearchDocumentIndexer { public function getIndexableObject() { return new FundInitiative(); } protected function loadDocumentByPHID($phid) { $object = id(new FundInitiativeQuery()) ->setViewer($this->getViewer()) ->withPHIDs(array($phid)) ->executeOne(); if (!$object) { throw new Exception( pht( "Unable to load object by PHID '%s'!", $phid)); } return $object; } protected function buildAbstractDocumentByPHID($phid) { $initiative = $this->loadDocumentByPHID($phid); $doc = id(new PhabricatorSearchAbstractDocument()) ->setPHID($initiative->getPHID()) ->setDocumentType(FundInitiativePHIDType::TYPECONST) ->setDocumentTitle($initiative->getName()) ->setDocumentCreated($initiative->getDateCreated()) ->setDocumentModified($initiative->getDateModified()); $doc->addRelationship( PhabricatorSearchRelationship::RELATIONSHIP_AUTHOR, $initiative->getOwnerPHID(), PhabricatorPeopleUserPHIDType::TYPECONST, $initiative->getDateCreated()); $doc->addRelationship( PhabricatorSearchRelationship::RELATIONSHIP_OWNER, $initiative->getOwnerPHID(), PhabricatorPeopleUserPHIDType::TYPECONST, $initiative->getDateCreated()); $doc->addRelationship( $initiative->isClosed() ? PhabricatorSearchRelationship::RELATIONSHIP_CLOSED : PhabricatorSearchRelationship::RELATIONSHIP_OPEN, $initiative->getPHID(), FundInitiativePHIDType::TYPECONST, time()); $this->indexTransactions( $doc, new FundInitiativeTransactionQuery(), array($initiative->getPHID())); return $doc; } }
codevlabs/phabricator
src/applications/fund/search/FundInitiativeIndexer.php
PHP
apache-2.0
1,770
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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 io.druid.query; public interface PrioritizedRunnable extends Runnable { int getPriority(); }
tubemogul/druid
processing/src/main/java/io/druid/query/PrioritizedRunnable.java
Java
apache-2.0
911
<?php /** * @version V4.66 28 Sept 2005 (c) 2000-2005 John Lim ([email protected]). All rights reserved. * Released under both BSD license and Lesser GPL library license. * Whenever there is any discrepancy between the two licenses, * the BSD license will take precedence. * * Set tabs to 4 for best viewing. * * Latest version is available at http://php.weblogs.com * */ // added Claudio Bustos clbustos#entelchile.net if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR); if (!defined('ADODB_ERROR_HANDLER')) define('ADODB_ERROR_HANDLER','ADODB_Error_Handler'); /** * Default Error Handler. This will be called with the following params * * @param $dbms the RDBMS you are connecting to * @param $fn the name of the calling function (in uppercase) * @param $errno the native error number from the database * @param $errmsg the native error msg from the database * @param $p1 $fn specific parameter - see below * @param $p2 $fn specific parameter - see below * @param $thisConn $current connection object - can be false if no connection object created */ function ADODB_Error_Handler($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection) { if (error_reporting() == 0) return; // obey @ protocol switch($fn) { case 'EXECUTE': $sql = $p1; $inputparams = $p2; $s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")\n"; break; case 'PCONNECT': case 'CONNECT': $host = $p1; $database = $p2; $s = "$dbms error: [$errno: $errmsg] in $fn($host, '****', '****', $database)\n"; break; default: $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n"; break; } /* * Log connection error somewhere * 0 message is sent to PHP's system logger, using the Operating System's system * logging mechanism or a file, depending on what the error_log configuration * directive is set to. * 1 message is sent by email to the address in the destination parameter. * This is the only message type where the fourth parameter, extra_headers is used. * This message type uses the same internal function as mail() does. * 2 message is sent through the PHP debugging connection. * This option is only available if remote debugging has been enabled. * In this case, the destination parameter specifies the host name or IP address * and optionally, port number, of the socket receiving the debug information. * 3 message is appended to the file destination */ if (defined('ADODB_ERROR_LOG_TYPE')) { $t = date('Y-m-d H:i:s'); if (defined('ADODB_ERROR_LOG_DEST')) error_log("($t) $s", ADODB_ERROR_LOG_TYPE, ADODB_ERROR_LOG_DEST); else error_log("($t) $s", ADODB_ERROR_LOG_TYPE); } //print "<p>$s</p>"; trigger_error($s, ADODB_ERROR_HANDLER_TYPE); } ?>
takkkken/open_task
webapp/lib/adodb_lite/adodb-errorhandler.inc.php
PHP
bsd-2-clause
2,766
/* GNULookAndFeel.java -- An example of using the javax.swing UI. Copyright (C) 2005 Free Software Foundation, Inc. This file is part of GNU Classpath examples. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package gnu.javax.swing.plaf.gnu; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JRadioButton; import javax.swing.UIDefaults; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.IconUIResource; import javax.swing.plaf.basic.BasicLookAndFeel; public class GNULookAndFeel extends BasicLookAndFeel { static Color blueGray = new Color(0xdc, 0xda, 0xd5); public boolean isNativeLookAndFeel() { return true; } public boolean isSupportedLookAndFeel() { return true; } public String getDescription() { return "GNU Look and Feel"; } public String getID() { return "GNULookAndFeel"; } public String getName() { return "GNU"; } static UIDefaults LAF_defaults; private final static String iconspath = "/gnu/javax/swing/plaf/gtk/icons/"; public UIDefaults getDefaults() { if (LAF_defaults == null) { LAF_defaults = super.getDefaults(); Object[] myDefaults = new Object[] { "Button.background", new ColorUIResource(blueGray), "CheckBox.background", new ColorUIResource(blueGray), "CheckBoxMenuItem.background", new ColorUIResource(blueGray), "ToolBar.background", new ColorUIResource(blueGray), "Panel.background", new ColorUIResource(blueGray), "Slider.background", new ColorUIResource(blueGray), "OptionPane.background", new ColorUIResource(blueGray), "ProgressBar.background", new ColorUIResource(blueGray), "TabbedPane.background", new ColorUIResource(blueGray), "Label.background", new ColorUIResource(blueGray), "Menu.background", new ColorUIResource(blueGray), "MenuBar.background", new ColorUIResource(blueGray), "MenuItem.background", new ColorUIResource(blueGray), "ScrollBar.background", new ColorUIResource(blueGray), "CheckBox.icon", new CheckBoxIcon(), "RadioButton.icon", new RadioButtonIcon(), "Tree.hash", new ColorUIResource(Color.black), "Tree.closedIcon", new IconUIResource(new ImageIcon (getClass().getResource (iconspath + "TreeClosed.png"))), "Tree.leafIcon", new IconUIResource(new ImageIcon (getClass().getResource (iconspath + "TreeLeaf.png"))), "Tree.openIcon", new IconUIResource(new ImageIcon (getClass().getResource (iconspath + "TreeOpen.png"))), }; LAF_defaults.putDefaults(myDefaults); } return LAF_defaults; } /** * The icon used for CheckBoxes in the BasicLookAndFeel. This is an empty * icon with a size of 13x13 pixels. */ static class CheckBoxIcon implements Icon { /** * Returns the height of the icon. The BasicLookAndFeel CheckBox icon * has a height of 13 pixels. * * @return the height of the icon */ public int getIconHeight() { return 13; } /** * Returns the width of the icon. The BasicLookAndFeel CheckBox icon * has a width of 13 pixels. * * @return the height of the icon */ public int getIconWidth() { return 13; } /** * Paints the icon. The BasicLookAndFeel CheckBox icon is empty and does * not need to be painted. * * @param c the component to be painted * @param g the Graphics context to be painted with * @param x the x position of the icon * @param y the y position of the icon */ public void paintIcon(Component c, Graphics g, int x, int y) { Color save = g.getColor(); g.setColor(c.getForeground()); g.drawRect(x, y, getIconWidth(), getIconHeight()); JCheckBox item = (JCheckBox) c; if (item.isSelected()) { g.drawLine(3 + x, 5 + y, 3 + x, 9 + y); g.drawLine(4 + x, 5 + y, 4 + x, 9 + y); g.drawLine(5 + x, 7 + y, 9 + x, 3 + y); g.drawLine(5 + x, 8 + y, 9 + x, 4 + y); } g.setColor(save); } } /** * The icon used for RadioButtons in the GNULookAndFeel. This is an empty * icon with a size of 13x13 pixels. */ static class RadioButtonIcon implements Icon { /** * Returns the height of the icon. The GNULookAndFeel RadioButton icon * has a height of 13 pixels. * * @return the height of the icon */ public int getIconHeight() { return 13; } /** * Returns the width of the icon. The GNULookAndFeel RadioButton icon * has a width of 13 pixels. * * @return the height of the icon */ public int getIconWidth() { return 13; } /** * Paints the icon. The GNULookAndFeel RadioButton icon is empty and does * not need to be painted. * * @param c the component to be painted * @param g the Graphics context to be painted with * @param x the x position of the icon * @param y the y position of the icon */ public void paintIcon(Component c, Graphics g, int x, int y) { Color savedColor = g.getColor(); JRadioButton b = (JRadioButton) c; // draw outer circle if (b.isEnabled()) g.setColor(Color.GRAY); else g.setColor(Color.GRAY); g.drawLine(x + 2, y + 1, x + 3, y + 1); g.drawLine(x + 4, y, x + 7, y); g.drawLine(x + 8, y + 1, x + 9, y + 1); g.drawLine(x + 10, y + 2, x + 10, y + 3); g.drawLine(x + 11, y + 4, x + 11, y + 7); g.drawLine(x + 10, y + 8, x + 10, y + 9); g.drawLine(x + 8, y + 10, x + 9, y + 10); g.drawLine(x + 4, y + 11, x + 7, y + 11); g.drawLine(x + 2, y + 10, x + 3, y + 10); g.drawLine(x + 1, y + 9, x + 1, y + 8); g.drawLine(x, y + 7, x, y + 4); g.drawLine(x + 1, y + 2, x + 1, y + 3); if (b.getModel().isArmed()) { g.setColor(Color.GRAY); g.drawLine(x + 4, y + 1, x + 7, y + 1); g.drawLine(x + 4, y + 10, x + 7, y + 10); g.drawLine(x + 1, y + 4, x + 1, y + 7); g.drawLine(x + 10, y + 4, x + 10, y + 7); g.fillRect(x + 2, y + 2, 8, 8); } else { // only draw inner highlight if not filled if (b.isEnabled()) { g.setColor(Color.WHITE); g.drawLine(x + 2, y + 8, x + 2, y + 9); g.drawLine(x + 1, y + 4, x + 1, y + 7); g.drawLine(x + 2, y + 2, x + 2, y + 3); g.drawLine(x + 3, y + 2, x + 3, y + 2); g.drawLine(x + 4, y + 1, x + 7, y + 1); g.drawLine(x + 8, y + 2, x + 9, y + 2); } } // draw outer highlight if (b.isEnabled()) { g.setColor(Color.WHITE); // outer g.drawLine(x + 10, y + 1, x + 10, y + 1); g.drawLine(x + 11, y + 2, x + 11, y + 3); g.drawLine(x + 12, y + 4, x + 12, y + 7); g.drawLine(x + 11, y + 8, x + 11, y + 9); g.drawLine(x + 10, y + 10, x + 10, y + 10); g.drawLine(x + 8, y + 11, x + 9, y + 11); g.drawLine(x + 4, y + 12, x + 7, y + 12); g.drawLine(x + 2, y + 11, x + 3, y + 11); } if (b.isSelected()) { if (b.isEnabled()) g.setColor(Color.BLACK); else g.setColor(Color.GRAY); g.drawLine(x + 4, y + 3, x + 7, y + 3); g.fillRect(x + 3, y + 4, 6, 4); g.drawLine(x + 4, y + 8, x + 7, y + 8); } g.setColor(savedColor); } } }
shaotuanchen/sunflower_exp
tools/source/gcc-4.2.4/libjava/classpath/gnu/javax/swing/plaf/gnu/GNULookAndFeel.java
Java
bsd-3-clause
8,563
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2012, Jim Richardson <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: pushover version_added: "2.0" short_description: Send notifications via U(https://pushover.net) description: - Send notifications via pushover, to subscriber list of devices, and email addresses. Requires pushover app on devices. notes: - You will require a pushover.net account to use this module. But no account is required to receive messages. options: msg: description: - What message you wish to send. required: true app_token: description: - Pushover issued token identifying your pushover app. required: true user_key: description: - Pushover issued authentication key for your user. required: true pri: description: - Message priority (see U(https://pushover.net) for details.) required: false author: "Jim Richardson (@weaselkeeper)" ''' EXAMPLES = ''' - pushover: msg: '{{ inventory_hostname }} has exploded in flames, It is now time to panic' app_token: wxfdksl user_key: baa5fe97f2c5ab3ca8f0bb59 delegate_to: localhost ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six.moves.urllib.parse import urlencode from ansible.module_utils.urls import fetch_url class Pushover(object): ''' Instantiates a pushover object, use it to send notifications ''' base_uri = 'https://api.pushover.net' def __init__(self, module, user, token): self.module = module self.user = user self.token = token def run(self, priority, msg): ''' Do, whatever it is, we do. ''' url = '%s/1/messages.json' % (self.base_uri) # parse config options = dict(user=self.user, token=self.token, priority=priority, message=msg) data = urlencode(options) headers = { "Content-type": "application/x-www-form-urlencoded"} r, info = fetch_url(self.module, url, method='POST', data=data, headers=headers) if info['status'] != 200: raise Exception(info) return r.read() def main(): module = AnsibleModule( argument_spec=dict( msg=dict(required=True), app_token=dict(required=True, no_log=True), user_key=dict(required=True, no_log=True), pri=dict(required=False, default='0', choices=['-2','-1','0','1','2']), ), ) msg_object = Pushover(module, module.params['user_key'], module.params['app_token']) try: response = msg_object.run(module.params['pri'], module.params['msg']) except: module.fail_json(msg='Unable to send msg via pushover') module.exit_json(msg='message sent successfully: %s' % response, changed=False) if __name__ == '__main__': main()
e-gob/plataforma-kioscos-autoatencion
scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/notification/pushover.py
Python
bsd-3-clause
3,207
#!/usr/bin/python from mod_pywebsocket import msgutil def web_socket_do_extra_handshake(request): pass def web_socket_transfer_data(request): while True: msgutil.send_message(request, request.unparsed_uri.split('?')[1] or '') return
chromium/chromium
third_party/wpt_tools/wpt/websockets/handlers/echo-query_v13_wsh.py
Python
bsd-3-clause
260
package ipmi_sensor import ( "fmt" "os/exec" "strings" "time" "github.com/influxdata/telegraf/internal" ) type CommandRunner struct{} func (t CommandRunner) cmd(conn *Connection, args ...string) *exec.Cmd { path := conn.Path opts := append(conn.options(), args...) if path == "" { path = "ipmitool" } return exec.Command(path, opts...) } func (t CommandRunner) Run(conn *Connection, args ...string) (string, error) { cmd := t.cmd(conn, args...) output, err := internal.CombinedOutputTimeout(cmd, time.Second*5) if err != nil { return "", fmt.Errorf("run %s %s: %s (%s)", cmd.Path, strings.Join(cmd.Args, " "), string(output), err) } return string(output), err }
allen13/telegraf
plugins/inputs/ipmi_sensor/command.go
GO
mit
693
package im.actor.server.db import scala.util.Try import com.github.kxbmap.configs._ import com.typesafe.config._ import slick.driver.PostgresDriver.api.Database import slick.jdbc.{ HikariCPJdbcDataSource, JdbcDataSource } trait DbInit { def initDs(sqlConfig: Config): Try[HikariCPJdbcDataSource] = { for { host ← sqlConfig.get[Try[String]]("host") port ← sqlConfig.get[Try[Int]]("port") db ← sqlConfig.get[Try[String]]("db") _ ← sqlConfig.get[Try[String]]("user") _ ← sqlConfig.get[Try[String]]("password") } yield { val conf = sqlConfig.withFallback(ConfigFactory.parseString( s""" |{ | url: "jdbc:postgresql://${host}:${port}/${db}" |} """.stripMargin )) HikariCPJdbcDataSource.forConfig(conf, null, "") } } def initDb(source: JdbcDataSource) = Database.forSource(source) }
boneyao/actor-platform
actor-server/actor-persist/src/main/scala/im/actor/server/db/DbInit.scala
Scala
mit
908
class AddRememberMeTokenToUsers < ActiveRecord::Migration def self.up add_column :users, :remember_me_token, :string, :default => nil add_column :users, :remember_me_token_expires_at, :datetime, :default => nil add_index :users, :remember_me_token end def self.down remove_index :users, :remember_me_token remove_column :users, :remember_me_token_expires_at remove_column :users, :remember_me_token end end
ralzate/Nuevo-Aerosanidad
vendor/bundle/ruby/2.2.0/gems/sorcery-0.9.1/spec/rails_app/db/migrate/remember_me/20101224223623_add_remember_me_token_to_users.rb
Ruby
mit
449
/* * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.misc; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.LongBuffer; import java.security.AccessController; /** * Performance counter support for internal JRE classes. * This class defines a fixed list of counters for the platform * to use as an interim solution until RFE# 6209222 is implemented. * The perf counters will be created in the jvmstat perf buffer * that the HotSpot VM creates. The default size is 32K and thus * the number of counters is bounded. You can alter the size * with -XX:PerfDataMemorySize=<bytes> option. If there is * insufficient memory in the jvmstat perf buffer, the C heap memory * will be used and thus the application will continue to run if * the counters added exceeds the buffer size but the counters * will be missing. * * See HotSpot jvmstat implementation for certain circumstances * that the jvmstat perf buffer is not supported. * */ public class PerfCounter { private static final Perf perf = AccessController.doPrivileged(new Perf.GetPerfAction()); // Must match values defined in hotspot/src/share/vm/runtime/perfdata.hpp private final static int V_Constant = 1; private final static int V_Monotonic = 2; private final static int V_Variable = 3; private final static int U_None = 1; private final String name; private final LongBuffer lb; private PerfCounter(String name, int type) { this.name = name; ByteBuffer bb = perf.createLong(name, type, U_None, 0L); bb.order(ByteOrder.nativeOrder()); this.lb = bb.asLongBuffer(); } static PerfCounter newPerfCounter(String name) { return new PerfCounter(name, V_Variable); } static PerfCounter newConstantPerfCounter(String name) { PerfCounter c = new PerfCounter(name, V_Constant); return c; } /** * Returns the current value of the perf counter. */ public synchronized long get() { return lb.get(0); } /** * Sets the value of the perf counter to the given newValue. */ public synchronized void set(long newValue) { lb.put(0, newValue); } /** * Adds the given value to the perf counter. */ public synchronized void add(long value) { long res = get() + value; lb.put(0, res); } /** * Increments the perf counter with 1. */ public void increment() { add(1); } /** * Adds the given interval to the perf counter. */ public void addTime(long interval) { add(interval); } /** * Adds the elapsed time from the given start time (ns) to the perf counter. */ public void addElapsedTimeFrom(long startTime) { add(System.nanoTime() - startTime); } @Override public String toString() { return name + " = " + get(); } static class CoreCounters { static final PerfCounter pdt = newPerfCounter("sun.classloader.parentDelegationTime"); static final PerfCounter lc = newPerfCounter("sun.classloader.findClasses"); static final PerfCounter lct = newPerfCounter("sun.classloader.findClassTime"); static final PerfCounter rcbt = newPerfCounter("sun.urlClassLoader.readClassBytesTime"); static final PerfCounter zfc = newPerfCounter("sun.zip.zipFiles"); static final PerfCounter zfot = newPerfCounter("sun.zip.zipFile.openTime"); } static class WindowsClientCounters { static final PerfCounter d3dAvailable = newConstantPerfCounter("sun.java2d.d3d.available"); } /** * Number of findClass calls */ public static PerfCounter getFindClasses() { return CoreCounters.lc; } /** * Time (ns) spent in finding classes that includes * lookup and read class bytes and defineClass */ public static PerfCounter getFindClassTime() { return CoreCounters.lct; } /** * Time (ns) spent in finding classes */ public static PerfCounter getReadClassBytesTime() { return CoreCounters.rcbt; } /** * Time (ns) spent in the parent delegation to * the parent of the defining class loader */ public static PerfCounter getParentDelegationTime() { return CoreCounters.pdt; } /** * Number of zip files opened. */ public static PerfCounter getZipFileCount() { return CoreCounters.zfc; } /** * Time (ns) spent in opening the zip files that * includes building the entries hash table */ public static PerfCounter getZipFileOpenTime() { return CoreCounters.zfot; } /** * D3D graphic pipeline available */ public static PerfCounter getD3DAvailable() { return WindowsClientCounters.d3dAvailable; } }
rokn/Count_Words_2015
testing/openjdk2/jdk/src/share/classes/sun/misc/PerfCounter.java
Java
mit
6,060
YUI.add('anim-node-plugin', function (Y, NAME) { /** * Binds an Anim instance to a Node instance * @module anim * @class Plugin.NodeFX * @extends Anim * @submodule anim-node-plugin */ var NodeFX = function(config) { config = (config) ? Y.merge(config) : {}; config.node = config.host; NodeFX.superclass.constructor.apply(this, arguments); }; NodeFX.NAME = "nodefx"; NodeFX.NS = "fx"; Y.extend(NodeFX, Y.Anim); Y.namespace('Plugin'); Y.Plugin.NodeFX = NodeFX; }, '3.18.1', {"requires": ["node-pluginhost", "anim-base"]});
Badacadabra/Harmoneezer
node_modules/yuidocjs/node_modules/yui/anim-node-plugin/anim-node-plugin.js
JavaScript
mit
547
module.exports = SlideNumberViewModel; function SlideNumberViewModel (slide, slideshow) { var self = this; self.slide = slide; self.slideshow = slideshow; self.element = document.createElement('div'); self.element.className = 'remark-slide-number'; self.element.innerHTML = formatSlideNumber(self.slide, self.slideshow); } function formatSlideNumber (slide, slideshow) { var format = slideshow.getSlideNumberFormat() , slides = slideshow.getSlides() , current = getSlideNo(slide, slideshow) , total = getSlideNo(slides[slides.length - 1], slideshow) ; if (typeof format === 'function') { return format.call(slideshow, current, total); } return format .replace('%current%', current) .replace('%total%', total); } function getSlideNo (slide, slideshow) { var slides = slideshow.getSlides(), i, slideNo = 0; for (i = 0; i <= slide.getSlideIndex() && i < slides.length; ++i) { if (slides[i].properties.count !== 'false') { slideNo += 1; } } return Math.max(1, slideNo); }
JPry/remark
src/remark/components/slide-number/slide-number.js
JavaScript
mit
1,051
Puppet::Type.newtype(:osx_login_item) do @doc = "Manage OSX login items." ensurable do newvalue :present do provider.create end newvalue :absent do provider.destroy end defaultto :present end newparam :name do desc "The name of the login item." end newparam :path do desc "The path to the application to be run at login." end newproperty :hidden do desc "Should the application be hidden when launched." newvalues :true, :false defaultto :false end end
filipebarcos/puppet-filipebarcos
spec/fixtures/modules/osx/lib/puppet/type/osx_login_item.rb
Ruby
mit
529
/* * libfdt - Flat Device Tree manipulation * Testcase for fdt_get_alias() * Copyright (C) 2006 David Gibson, IBM Corporation. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdint.h> #include <fdt.h> #include <libfdt.h> #include "tests.h" #include "testdata.h" static void check_alias(void *fdt, const char *path, const char *alias) { const char *aliaspath; aliaspath = fdt_get_alias(fdt, alias); if (path && !aliaspath) FAIL("fdt_get_alias(%s) failed\n", alias); if (strcmp(aliaspath, path) != 0) FAIL("fdt_get_alias(%s) returned %s instead of %s\n", alias, aliaspath, path); } int main(int argc, char *argv[]) { void *fdt; test_init(argc, argv); fdt = load_blob_arg(argc, argv); check_alias(fdt, "/subnode@1", "s1"); check_alias(fdt, "/subnode@1/subsubnode", "ss1"); check_alias(fdt, "/subnode@1/subsubnode/subsubsubnode", "sss1"); PASS(); }
rpaleari/qtrace
src/dtc/tests/get_alias.c
C
gpl-2.0
1,645
<?php /* * Copyright 2013 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. */ /** * Http Streams based implementation of Google_IO. * * @author Stuart Langley <[email protected]> */ require_once realpath(dirname(__FILE__) . '/../../../autoload.php'); class Google_IO_Stream extends Google_IO_Abstract { const TIMEOUT = "timeout"; const ZLIB = "compress.zlib://"; private $options = array(); private $trappedErrorNumber; private $trappedErrorString; private static $DEFAULT_HTTP_CONTEXT = array( "follow_location" => 0, "ignore_errors" => 1, ); private static $DEFAULT_SSL_CONTEXT = array( "verify_peer" => true, ); public function __construct(Google_Client $client) { if (!ini_get('allow_url_fopen')) { $error = 'The stream IO handler requires the allow_url_fopen runtime ' . 'configuration to be enabled'; $client->getLogger()->critical($error); throw new Google_IO_Exception($error); } parent::__construct($client); } /** * Execute an HTTP Request * * @param Google_HttpRequest $request the http request to be executed * @return Google_HttpRequest http request with the response http code, * response headers and response body filled in * @throws Google_IO_Exception on curl or IO error */ public function executeRequest(Google_Http_Request $request) { $default_options = stream_context_get_options(stream_context_get_default()); $requestHttpContext = array_key_exists('http', $default_options) ? $default_options['http'] : array(); if ($request->getPostBody()) { $requestHttpContext["content"] = $request->getPostBody(); } $requestHeaders = $request->getRequestHeaders(); if ($requestHeaders && is_array($requestHeaders)) { $headers = ""; foreach ($requestHeaders as $k => $v) { $headers .= "$k: $v\r\n"; } $requestHttpContext["header"] = $headers; } $requestHttpContext["method"] = $request->getRequestMethod(); $requestHttpContext["user_agent"] = $request->getUserAgent(); $requestSslContext = array_key_exists('ssl', $default_options) ? $default_options['ssl'] : array(); if (!array_key_exists("cafile", $requestSslContext)) { $requestSslContext["cafile"] = dirname(__FILE__) . '/cacerts.pem'; } $options = array( "http" => array_merge( self::$DEFAULT_HTTP_CONTEXT, $requestHttpContext ), "ssl" => array_merge( self::$DEFAULT_SSL_CONTEXT, $requestSslContext ) ); $context = stream_context_create($options); $url = $request->getUrl(); if ($request->canGzip()) { $url = self::ZLIB . $url; } $this->client->getLogger()->debug( 'Stream request', array( 'url' => $url, 'method' => $request->getRequestMethod(), 'headers' => $requestHeaders, 'body' => $request->getPostBody() ) ); // We are trapping any thrown errors in this method only and // throwing an exception. $this->trappedErrorNumber = null; $this->trappedErrorString = null; // START - error trap. set_error_handler(array($this, 'trapError')); $fh = fopen($url, 'r', false, $context); restore_error_handler(); // END - error trap. if ($this->trappedErrorNumber) { $error = sprintf( "HTTP Error: Unable to connect: '%s'", $this->trappedErrorString ); $this->client->getLogger()->error('Stream ' . $error); throw new Google_IO_Exception($error, $this->trappedErrorNumber); } $response_data = false; $respHttpCode = self::UNKNOWN_CODE; if ($fh) { if (isset($this->options[self::TIMEOUT])) { stream_set_timeout($fh, $this->options[self::TIMEOUT]); } $response_data = stream_get_contents($fh); fclose($fh); $respHttpCode = $this->getHttpResponseCode($http_response_header); } if (false === $response_data) { $error = sprintf( "HTTP Error: Unable to connect: '%s'", $respHttpCode ); $this->client->getLogger()->error('Stream ' . $error); throw new Google_IO_Exception($error, $respHttpCode); } $responseHeaders = $this->getHttpResponseHeaders($http_response_header); $this->client->getLogger()->debug( 'Stream response', array( 'code' => $respHttpCode, 'headers' => $responseHeaders, 'body' => $response_data, ) ); return array($response_data, $responseHeaders, $respHttpCode); } /** * Set options that update the transport implementation's behavior. * @param $options */ public function setOptions($options) { $this->options = $options + $this->options; } /** * Method to handle errors, used for error handling around * stream connection methods. */ public function trapError($errno, $errstr) { $this->trappedErrorNumber = $errno; $this->trappedErrorString = $errstr; } /** * Set the maximum request time in seconds. * @param $timeout in seconds */ public function setTimeout($timeout) { $this->options[self::TIMEOUT] = $timeout; } /** * Get the maximum request time in seconds. * @return timeout in seconds */ public function getTimeout() { return $this->options[self::TIMEOUT]; } /** * Test for the presence of a cURL header processing bug * * {@inheritDoc} * * @return boolean */ protected function needsQuirk() { return false; } protected function getHttpResponseCode($response_headers) { $header_count = count($response_headers); for ($i = 0; $i < $header_count; $i++) { $header = $response_headers[$i]; if (strncasecmp("HTTP", $header, strlen("HTTP")) == 0) { $response = explode(' ', $header); return $response[1]; } } return self::UNKNOWN_CODE; } }
jveraguth/Crifip
wp-content/plugins/yakadanda-google-hangout-events/src/Google/IO/Stream.php
PHP
gpl-2.0
6,532
/* * 8-bit raw data * * Source: DialTone.ulaw * * Copyright (C) 1999, Mark Spencer * * Distributed under the terms of the GNU General Public License * */ /*! \file * \brief * 8-bit raw data */ static unsigned char DialTone[] = { 0xff, 0xab, 0x9d, 0x96, 0x91, 0x90, 0x91, 0x96, 0x9c, 0xaa, 0xd9, 0x2f, 0x1f, 0x19, 0x15, 0x14, 0x15, 0x19, 0x1f, 0x2c, 0x4e, 0xb9, 0xa7, 0x9f, 0x9c, 0x9b, 0x9c, 0x9f, 0xa7, 0xb3, 0xcf, 0x47, 0x34, 0x2d, 0x2a, 0x2a, 0x2c, 0x31, 0x3a, 0x47, 0x5f, 0xe4, 0xd8, 0xd9, 0xe9, 0x64, 0x4f, 0x49, 0x46, 0x49, 0x58, 0xde, 0xc2, 0xb5, 0xad, 0xa8, 0xa6, 0xa6, 0xa9, 0xaf, 0xbf, 0x56, 0x32, 0x26, 0x1e, 0x1b, 0x19, 0x1a, 0x1d, 0x24, 0x33, 0xdd, 0xad, 0x9f, 0x98, 0x94, 0x92, 0x93, 0x97, 0x9e, 0xac, 0xf8, 0x2c, 0x1d, 0x16, 0x11, 0xf, 0x10, 0x15, 0x1b, 0x29, 0x55, 0xae, 0x9e, 0x97, 0x92, 0x90, 0x91, 0x95, 0x9c, 0xa8, 0xca, 0x35, 0x22, 0x1a, 0x16, 0x15, 0x16, 0x19, 0x1f, 0x2b, 0x47, 0xbe, 0xab, 0xa2, 0x9e, 0x9d, 0x9e, 0xa2, 0xa9, 0xb4, 0xcc, 0x4f, 0x3a, 0x32, 0x2f, 0x2f, 0x32, 0x39, 0x41, 0x4f, 0x67, 0xf5, 0xf5, 0x67, 0x51, 0x46, 0x3e, 0x3b, 0x3b, 0x3f, 0x4d, 0xe2, 0xbe, 0xb0, 0xa9, 0xa4, 0xa1, 0xa1, 0xa5, 0xab, 0xba, 0x64, 0x33, 0x25, 0x1d, 0x19, 0x17, 0x18, 0x1b, 0x20, 0x2e, 0x72, 0xae, 0x9f, 0x98, 0x94, 0x91, 0x92, 0x96, 0x9c, 0xa9, 0xd4, 0x2f, 0x1e, 0x17, 0x11, 0xf, 0x10, 0x14, 0x1a, 0x26, 0x48, 0xb2, 0x9f, 0x98, 0x93, 0x91, 0x92, 0x95, 0x9b, 0xa7, 0xc1, 0x3a, 0x25, 0x1c, 0x18, 0x16, 0x17, 0x1a, 0x1f, 0x2b, 0x42, 0xc6, 0xae, 0xa6, 0xa0, 0x9f, 0xa0, 0xa5, 0xab, 0xb6, 0xcb, 0x5a, 0x40, 0x39, 0x36, 0x37, 0x3b, 0x43, 0x4e, 0x60, 0x7b, 0x7c, 0x60, 0x4e, 0x41, 0x3a, 0x34, 0x32, 0x33, 0x39, 0x45, 0xed, 0xbd, 0xae, 0xa6, 0xa0, 0x9e, 0x9e, 0xa0, 0xa8, 0xb4, 0xef, 0x34, 0x24, 0x1c, 0x18, 0x16, 0x16, 0x19, 0x1e, 0x2b, 0x54, 0xb1, 0x9f, 0x98, 0x93, 0x91, 0x91, 0x95, 0x9b, 0xa6, 0xc6, 0x33, 0x1f, 0x17, 0x12, 0xf, 0x10, 0x13, 0x1a, 0x24, 0x3e, 0xb8, 0xa2, 0x99, 0x94, 0x92, 0x92, 0x96, 0x9b, 0xa6, 0xbc, 0x40, 0x29, 0x1e, 0x1a, 0x18, 0x19, 0x1b, 0x20, 0x2b, 0x3f, 0xcf, 0xb3, 0xa9, 0xa5, 0xa3, 0xa4, 0xa8, 0xae, 0xb9, 0xcc, 0x67, 0x49, 0x40, 0x3f, 0x42, 0x4a, 0x59, 0x79, 0xe5, 0xe4, 0x7a, 0x54, 0x43, 0x39, 0x31, 0x2d, 0x2c, 0x2d, 0x32, 0x3e, 0x71, 0xbd, 0xad, 0xa4, 0x9e, 0x9c, 0x9c, 0x9e, 0xa4, 0xaf, 0xd7, 0x36, 0x24, 0x1c, 0x17, 0x15, 0x15, 0x17, 0x1d, 0x28, 0x47, 0xb5, 0xa1, 0x98, 0x93, 0x90, 0x90, 0x93, 0x99, 0xa4, 0xbd, 0x38, 0x21, 0x18, 0x13, 0x10, 0x10, 0x13, 0x19, 0x22, 0x39, 0xbe, 0xa5, 0x9b, 0x96, 0x93, 0x93, 0x96, 0x9b, 0xa5, 0xb9, 0x4a, 0x2c, 0x20, 0x1c, 0x1a, 0x1a, 0x1d, 0x22, 0x2c, 0x3d, 0xdc, 0xb8, 0xad, 0xa9, 0xa8, 0xa9, 0xac, 0xb2, 0xbd, 0xce, 0x78, 0x54, 0x4d, 0x4f, 0x5a, 0xff, 0xda, 0xcf, 0xcd, 0xd4, 0xf8, 0x4e, 0x3d, 0x32, 0x2c, 0x29, 0x28, 0x29, 0x2d, 0x38, 0x5c, 0xbd, 0xac, 0xa2, 0x9d, 0x9a, 0x9a, 0x9c, 0xa0, 0xac, 0xca, 0x39, 0x25, 0x1b, 0x16, 0x13, 0x13, 0x16, 0x1b, 0x25, 0x3e, 0xb9, 0xa2, 0x99, 0x93, 0x90, 0x90, 0x93, 0x98, 0xa1, 0xb8, 0x3d, 0x24, 0x19, 0x13, 0x10, 0x10, 0x13, 0x18, 0x21, 0x35, 0xc7, 0xa8, 0x9d, 0x97, 0x95, 0x95, 0x97, 0x9c, 0xa4, 0xb6, 0x57, 0x2f, 0x24, 0x1e, 0x1c, 0x1c, 0x1e, 0x24, 0x2d, 0x3d, 0xf1, 0xbe, 0xb2, 0xad, 0xac, 0xad, 0xb1, 0xb9, 0xc3, 0xd4, 0xfa, 0x64, 0x65, 0xf9, 0xd9, 0xca, 0xc2, 0xbf, 0xc0, 0xc9, 0xe7, 0x4c, 0x39, 0x2e, 0x28, 0x24, 0x23, 0x25, 0x29, 0x33, 0x4f, 0xbf, 0xab, 0xa0, 0x9b, 0x99, 0x98, 0x9a, 0x9e, 0xa9, 0xc0, 0x3c, 0x26, 0x1b, 0x16, 0x12, 0x12, 0x14, 0x19, 0x22, 0x38, 0xbe, 0xa4, 0x9a, 0x93, 0x90, 0x8f, 0x92, 0x97, 0x9f, 0xb3, 0x46, 0x26, 0x1b, 0x15, 0x11, 0x11, 0x13, 0x18, 0x1f, 0x31, 0xd4, 0xab, 0x9e, 0x99, 0x96, 0x96, 0x98, 0x9c, 0xa4, 0xb4, 0x6f, 0x34, 0x28, 0x20, 0x1e, 0x1e, 0x20, 0x26, 0x2e, 0x3d, 0x6d, 0xc5, 0xb9, 0xb3, 0xb2, 0xb4, 0xba, 0xc1, 0xcd, 0xe0, 0xfc, 0xfb, 0xe0, 0xce, 0xc3, 0xbb, 0xb7, 0xb6, 0xb9, 0xc0, 0xda, 0x4b, 0x36, 0x2b, 0x25, 0x20, 0x1f, 0x20, 0x26, 0x2e, 0x46, 0xc2, 0xab, 0x9f, 0x9a, 0x97, 0x96, 0x98, 0x9c, 0xa5, 0xba, 0x41, 0x27, 0x1b, 0x15, 0x12, 0x11, 0x13, 0x18, 0x1f, 0x32, 0xc8, 0xa6, 0x9a, 0x94, 0x90, 0x8f, 0x91, 0x97, 0x9e, 0xaf, 0x54, 0x29, 0x1c, 0x16, 0x12, 0x11, 0x14, 0x18, 0x1f, 0x2e, 0xf2, 0xae, 0xa0, 0x9b, 0x98, 0x97, 0x99, 0x9d, 0xa5, 0xb3, 0xe4, 0x3a, 0x2b, 0x25, 0x21, 0x21, 0x24, 0x29, 0x30, 0x3e, 0x62, 0xcd, 0xbf, 0xbb, 0xbb, 0xbe, 0xc6, 0xd1, 0xe7, 0x76, 0x75, 0xe7, 0xcf, 0xc1, 0xb9, 0xb2, 0xaf, 0xaf, 0xb2, 0xba, 0xcf, 0x4c, 0x34, 0x29, 0x22, 0x1e, 0x1d, 0x1e, 0x22, 0x2b, 0x3e, 0xc7, 0xab, 0x9f, 0x99, 0x96, 0x95, 0x96, 0x9a, 0xa2, 0xb5, 0x4a, 0x28, 0x1c, 0x15, 0x11, 0x10, 0x12, 0x17, 0x1e, 0x2e, 0xd5, 0xa9, 0x9b, 0x95, 0x90, 0x8f, 0x91, 0x96, 0x9d, 0xac, 0x78, 0x2c, 0x1e, 0x17, 0x13, 0x12, 0x14, 0x18, 0x1f, 0x2d, 0x5d, 0xb3, 0xa4, 0x9d, 0x9a, 0x99, 0x9b, 0x9e, 0xa6, 0xb2, 0xd6, 0x3f, 0x2f, 0x29, 0x26, 0x26, 0x28, 0x2d, 0x35, 0x42, 0x5e, 0xd8, 0xca, 0xc6, 0xc9, 0xcf, 0xe4, 0x69, 0x59, 0x58, 0x64, 0xdf, 0xc7, 0xba, 0xb1, 0xac, 0xaa, 0xaa, 0xad, 0xb4, 0xc7, 0x4f, 0x33, 0x27, 0x1f, 0x1c, 0x1b, 0x1c, 0x1f, 0x27, 0x39, 0xce, 0xac, 0x9f, 0x99, 0x95, 0x94, 0x95, 0x99, 0x9f, 0xaf, 0x59, 0x2a, 0x1c, 0x16, 0x11, 0x10, 0x11, 0x16, 0x1d, 0x2b, 0xff, 0xab, 0x9d, 0x96, 0x91, 0x90, 0x91, 0x96, 0x9c, 0xaa, 0xd9, 0x2f, 0x1f, 0x19, 0x15, 0x14, 0x15, 0x19, 0x1f, 0x2c, 0x4e, 0xb9, 0xa7, 0x9f, 0x9c, 0x9b, 0x9c, 0x9f, 0xa7, 0xb3, 0xcf, 0x47, 0x34, 0x2d, 0x2a, 0x2a, 0x2c, 0x31, 0x3a, 0x47, 0x5f, 0xe4, 0xd8, 0xd9, 0xe9, 0x64, 0x4f, 0x49, 0x46, 0x49, 0x58, 0xde, 0xc2, 0xb5, 0xad, 0xa8, 0xa6, 0xa6, 0xa9, 0xaf, 0xbf, 0x56, 0x32, 0x26, 0x1e, 0x1b, 0x19, 0x1a, 0x1d, 0x24, 0x33, 0xdd, 0xad, 0x9f, 0x98, 0x94, 0x92, 0x93, 0x97, 0x9e, 0xac, 0xf8, 0x2c, 0x1d, 0x16, 0x11, 0xf, 0x10, 0x15, 0x1b, 0x29, 0x55, 0xae, 0x9e, 0x97, 0x92, 0x90, 0x91, 0x95, 0x9c, 0xa8, 0xca, 0x35, 0x22, 0x1a, 0x16, 0x15, 0x16, 0x19, 0x1f, 0x2b, 0x47, 0xbe, 0xab, 0xa2, 0x9e, 0x9d, 0x9e, 0xa2, 0xa9, 0xb4, 0xcc, 0x4f, 0x3a, 0x32, 0x2f, 0x2f, 0x32, 0x39, 0x41, 0x4f, 0x67, 0xf5, 0xf5, 0x67, 0x51, 0x46, 0x3e, 0x3b, 0x3b, 0x3f, 0x4d, 0xe2, 0xbe, 0xb0, 0xa9, 0xa4, 0xa1, 0xa1, 0xa5, 0xab, 0xba, 0x64, 0x33, 0x25, 0x1d, 0x19, 0x17, 0x18, 0x1b, 0x20, 0x2e, 0x72, 0xae, 0x9f, 0x98, 0x94, 0x91, 0x92, 0x96, 0x9c, 0xa9, 0xd4, 0x2f, 0x1e, 0x17, 0x11, 0xf, 0x10, 0x14, 0x1a, 0x26, 0x48, 0xb2, 0x9f, 0x98, 0x93, 0x91, 0x92, 0x95, 0x9b, 0xa7, 0xc1, 0x3a, 0x25, 0x1c, 0x18, 0x16, 0x17, 0x1a, 0x1f, 0x2b, 0x42, 0xc6, 0xae, 0xa6, 0xa0, 0x9f, 0xa0, 0xa5, 0xab, 0xb6, 0xcb, 0x5a, 0x40, 0x39, 0x36, 0x37, 0x3b, 0x43, 0x4e, 0x60, 0x7b, 0x7c, 0x60, 0x4e, 0x41, 0x3a, 0x34, 0x32, 0x33, 0x39, 0x45, 0xed, 0xbd, 0xae, 0xa6, 0xa0, 0x9e, 0x9e, 0xa0, 0xa8, 0xb4, 0xef, 0x34, 0x24, 0x1c, 0x18, 0x16, 0x16, 0x19, 0x1e, 0x2b, 0x54, 0xb1, 0x9f, 0x98, 0x93, 0x91, 0x91, 0x95, 0x9b, 0xa6, 0xc6, 0x33, 0x1f, 0x17, 0x12, 0xf, 0x10, 0x13, 0x1a, 0x24, 0x3e, 0xb8, 0xa2, 0x99, 0x94, 0x92, 0x92, 0x96, 0x9b, 0xa6, 0xbc, 0x40, 0x29, 0x1e, 0x1a, 0x18, 0x19, 0x1b, 0x20, 0x2b, 0x3f, 0xcf, 0xb3, 0xa9, 0xa5, 0xa3, 0xa4, 0xa8, 0xae, 0xb9, 0xcc, 0x67, 0x49, 0x40, 0x3f, 0x42, 0x4a, 0x59, 0x79, 0xe5, 0xe4, 0x7a, 0x54, 0x43, 0x39, 0x31, 0x2d, 0x2c, 0x2d, 0x32, 0x3e, 0x71, 0xbd, 0xad, 0xa4, 0x9e, 0x9c, 0x9c, 0x9e, 0xa4, 0xaf, 0xd7, 0x36, 0x24, 0x1c, 0x17, 0x15, 0x15, 0x17, 0x1d, 0x28, 0x47, 0xb5, 0xa1, 0x98, 0x93, 0x90, 0x90, 0x93, 0x99, 0xa4, 0xbd, 0x38, 0x21, 0x18, 0x13, 0x10, 0x10, 0x13, 0x19, 0x22, 0x39, 0xbe, 0xa5, 0x9b, 0x96, 0x93, 0x93, 0x96, 0x9b, 0xa5, 0xb9, 0x4a, 0x2c, 0x20, 0x1c, 0x1a, 0x1a, 0x1d, 0x22, 0x2c, 0x3d, 0xdc, 0xb8, 0xad, 0xa9, 0xa8, 0xa9, 0xac, 0xb2, 0xbd, 0xce, 0x78, 0x54, 0x4d, 0x4f, 0x5a, 0xff, 0xda, 0xcf, 0xcd, 0xd4, 0xf8, 0x4e, 0x3d, 0x32, 0x2c, 0x29, 0x28, 0x29, 0x2d, 0x38, 0x5c, 0xbd, 0xac, 0xa2, 0x9d, 0x9a, 0x9a, 0x9c, 0xa0, 0xac, 0xca, 0x39, 0x25, 0x1b, 0x16, 0x13, 0x13, 0x16, 0x1b, 0x25, 0x3e, 0xb9, 0xa2, 0x99, 0x93, 0x90, 0x90, 0x93, 0x98, 0xa1, 0xb8, 0x3d, 0x24, 0x19, 0x13, 0x10, 0x10, 0x13, 0x18, 0x21, 0x35, 0xc7, 0xa8, 0x9d, 0x97, 0x95, 0x95, 0x97, 0x9c, 0xa4, 0xb6, 0x57, 0x2f, 0x24, 0x1e, 0x1c, 0x1c, 0x1e, 0x24, 0x2d, 0x3d, 0xf1, 0xbe, 0xb2, 0xad, 0xac, 0xad, 0xb1, 0xb9, 0xc3, 0xd4, 0xfa, 0x64, 0x65, 0xf9, 0xd9, 0xca, 0xc2, 0xbf, 0xc0, 0xc9, 0xe7, 0x4c, 0x39, 0x2e, 0x28, 0x24, 0x23, 0x25, 0x29, 0x33, 0x4f, 0xbf, 0xab, 0xa0, 0x9b, 0x99, 0x98, 0x9a, 0x9e, 0xa9, 0xc0, 0x3c, 0x26, 0x1b, 0x16, 0x12, 0x12, 0x14, 0x19, 0x22, 0x38, 0xbe, 0xa4, 0x9a, 0x93, 0x90, 0x8f, 0x92, 0x97, 0x9f, 0xb3, 0x46, 0x26, 0x1b, 0x15, 0x11, 0x11, 0x13, 0x18, 0x1f, 0x31, 0xd4, 0xab, 0x9e, 0x99, 0x96, 0x96, 0x98, 0x9c, 0xa4, 0xb4, 0x6f, 0x34, 0x28, 0x20, 0x1e, 0x1e, 0x20, 0x26, 0x2e, 0x3d, 0x6d, 0xc5, 0xb9, 0xb3, 0xb2, 0xb4, 0xba, 0xc1, 0xcd, 0xe0, 0xfc, 0xfb, 0xe0, 0xce, 0xc3, 0xbb, 0xb7, 0xb6, 0xb9, 0xc0, 0xda, 0x4b, 0x36, 0x2b, 0x25, 0x20, 0x1f, 0x20, 0x26, 0x2e, 0x46, 0xc2, 0xab, 0x9f, 0x9a, 0x97, 0x96, 0x98, 0x9c, 0xa5, 0xba, 0x41, 0x27, 0x1b, 0x15, 0x12, 0x11, 0x13, 0x18, 0x1f, 0x32, 0xc8, 0xa6, 0x9a, 0x94, 0x90, 0x8f, 0x91, 0x97, 0x9e, 0xaf, 0x54, 0x29, 0x1c, 0x16, 0x12, 0x11, 0x14, 0x18, 0x1f, 0x2e, 0xf2, 0xae, 0xa0, 0x9b, 0x98, 0x97, 0x99, 0x9d, 0xa5, 0xb3, 0xe4, 0x3a, 0x2b, 0x25, 0x21, 0x21, 0x24, 0x29, 0x30, 0x3e, 0x62, 0xcd, 0xbf, 0xbb, 0xbb, 0xbe, 0xc6, 0xd1, 0xe7, 0x76, 0x75, 0xe7, 0xcf, 0xc1, 0xb9, 0xb2, 0xaf, 0xaf, 0xb2, 0xba, 0xcf, 0x4c, 0x34, 0x29, 0x22, 0x1e, 0x1d, 0x1e, 0x22, 0x2b, 0x3e, 0xc7, 0xab, 0x9f, 0x99, 0x96, 0x95, 0x96, 0x9a, 0xa2, 0xb5, 0x4a, 0x28, 0x1c, 0x15, 0x11, 0x10, 0x12, 0x17, 0x1e, 0x2e, 0xd5, 0xa9, 0x9b, 0x95, 0x90, 0x8f, 0x91, 0x96, 0x9d, 0xac, 0x78, 0x2c, 0x1e, 0x17, 0x13, 0x12, 0x14, 0x18, 0x1f, 0x2d, 0x5d, 0xb3, 0xa4, 0x9d, 0x9a, 0x99, 0x9b, 0x9e, 0xa6, 0xb2, 0xd6, 0x3f, 0x2f, 0x29, 0x26, 0x26, 0x28, 0x2d, 0x35, 0x42, 0x5e, 0xd8, 0xca, 0xc6, 0xc9, 0xcf, 0xe4, 0x69, 0x59, 0x58, 0x64, 0xdf, 0xc7, 0xba, 0xb1, 0xac, 0xaa, 0xaa, 0xad, 0xb4, 0xc7, 0x4f, 0x33, 0x27, 0x1f, 0x1c, 0x1b, 0x1c, 0x1f, 0x27, 0x39, 0xce, 0xac, 0x9f, 0x99, 0x95, 0x94, 0x95, 0x99, 0x9f, 0xaf, 0x59, 0x2a, 0x1c, 0x16, 0x11, 0x10, 0x11, 0x16, 0x1d, 0x2b, 0xff, 0xab, 0x9d, 0x96, 0x91, 0x90, 0x91, 0x96, 0x9c, 0xaa, 0xd9, 0x2f, 0x1f, 0x19, 0x15, 0x14, 0x15, 0x19, 0x1f, 0x2c, 0x4e, 0xb9, 0xa7, 0x9f, 0x9c, 0x9b, 0x9c, 0x9f, 0xa7, 0xb3, 0xcf, 0x47, 0x34, 0x2d, 0x2a, 0x2a, 0x2c, 0x31, 0x3a, 0x47, 0x5f, 0xe4, 0xd8, 0xd9, 0xe9, 0x64, 0x4f, 0x49, 0x46, 0x49, 0x58, 0xde, 0xc2, 0xb5, 0xad, 0xa8, 0xa6, 0xa6, 0xa9, 0xaf, 0xbf, 0x56, 0x32, 0x26, 0x1e, 0x1b, 0x19, 0x1a, 0x1d, 0x24, 0x33, 0xdd, 0xad, 0x9f, 0x98, 0x94, 0x92, 0x93, 0x97, 0x9e, 0xac, 0xf8, 0x2c, 0x1d, 0x16, 0x11, 0xf, 0x10, 0x15, 0x1b, 0x29, 0x55, 0xae, 0x9e, 0x97, 0x92, 0x90, 0x91, 0x95, 0x9c, 0xa8, 0xca, 0x35, 0x22, 0x1a, 0x16, 0x15, 0x16, 0x19, 0x1f, 0x2b, 0x47, 0xbe, 0xab, 0xa2, 0x9e, 0x9d, 0x9e, 0xa2, 0xa9, 0xb4, 0xcc, 0x4f, 0x3a, 0x32, 0x2f, 0x2f, 0x32, 0x39, 0x41, 0x4f, 0x67, 0xf5, 0xf5, 0x67, 0x51, 0x46, 0x3e, 0x3b, 0x3b, 0x3f, 0x4d, 0xe2, 0xbe, 0xb0, 0xa9, 0xa4, 0xa1, 0xa1, 0xa5, 0xab, 0xba, 0x64, 0x33, 0x25, 0x1d, 0x19, 0x17, 0x18, 0x1b, 0x20, 0x2e, 0x72, 0xae, 0x9f, 0x98, 0x94, 0x91, 0x92, 0x96, 0x9c, 0xa9, 0xd4, 0x2f, 0x1e, 0x17, 0x11, 0xf, 0x10, 0x14, 0x1a, 0x26, 0x48, 0xb2, 0x9f, 0x98, 0x93, 0x91, 0x92, 0x95, 0x9b, 0xa7, 0xc1, 0x3a, 0x25, 0x1c, 0x18, 0x16, 0x17, 0x1a, 0x1f, 0x2b, 0x42, 0xc6, 0xae, 0xa6, 0xa0, 0x9f, 0xa0, 0xa5, 0xab, 0xb6, 0xcb, 0x5a, 0x40, 0x39, 0x36, 0x37, 0x3b, 0x43, 0x4e, 0x60, 0x7b, 0x7c, 0x60, 0x4e, 0x41, 0x3a, 0x34, 0x32, 0x33, 0x39, 0x45, 0xed, 0xbd, 0xae, 0xa6, 0xa0, 0x9e, 0x9e, 0xa0, 0xa8, 0xb4, 0xef, 0x34, 0x24, 0x1c, 0x18, 0x16, 0x16, 0x19, 0x1e, 0x2b, 0x54, 0xb1, 0x9f, 0x98, 0x93, 0x91, 0x91, 0x95, 0x9b, 0xa6, 0xc6, 0x33, 0x1f, 0x17, 0x12, 0xf, 0x10, 0x13, 0x1a, 0x24, 0x3e, 0xb8, 0xa2, 0x99, 0x94, 0x92, 0x92, 0x96, 0x9b, 0xa6, 0xbc, 0x40, 0x29, 0x1e, 0x1a, 0x18, 0x19, 0x1b, 0x20, 0x2b, 0x3f, 0xcf, 0xb3, 0xa9, 0xa5, 0xa3, 0xa4, 0xa8, 0xae, 0xb9, 0xcc, 0x67, 0x49, 0x40, 0x3f, 0x42, 0x4a, 0x59, 0x79, 0xe5, 0xe4, 0x7a, 0x54, 0x43, 0x39, 0x31, 0x2d, 0x2c, 0x2d, 0x32, 0x3e, 0x71, 0xbd, 0xad, 0xa4, 0x9e, 0x9c, 0x9c, 0x9e, 0xa4, 0xaf, 0xd7, 0x36, 0x24, 0x1c, 0x17, 0x15, 0x15, 0x17, 0x1d, 0x28, 0x47, 0xb5, 0xa1, 0x98, 0x93, 0x90, 0x90, 0x93, 0x99, 0xa4, 0xbd, 0x38, 0x21, 0x18, 0x13, 0x10, 0x10, 0x13, 0x19, 0x22, 0x39, 0xbe, 0xa5, 0x9b, 0x96, 0x93, 0x93, 0x96, 0x9b, 0xa5, 0xb9, 0x4a, 0x2c, 0x20, 0x1c, 0x1a, 0x1a, 0x1d, 0x22, 0x2c, 0x3d, 0xdc, 0xb8, 0xad, 0xa9, 0xa8, 0xa9, 0xac, 0xb2, 0xbd, 0xce, 0x78, 0x54, 0x4d, 0x4f, 0x5a, 0xff, 0xda, 0xcf, 0xcd, 0xd4, 0xf8, 0x4e, 0x3d, 0x32, 0x2c, 0x29, 0x28, 0x29, 0x2d, 0x38, 0x5c, 0xbd, 0xac, 0xa2, 0x9d, 0x9a, 0x9a, 0x9c, 0xa0, 0xac, 0xca, 0x39, 0x25, 0x1b, 0x16, 0x13, 0x13, 0x16, 0x1b, 0x25, 0x3e, 0xb9, 0xa2, 0x99, 0x93, 0x90, 0x90, 0x93, 0x98, 0xa1, 0xb8, 0x3d, 0x24, 0x19, 0x13, 0x10, 0x10, 0x13, 0x18, 0x21, 0x35, 0xc7, 0xa8, 0x9d, 0x97, 0x95, 0x95, 0x97, 0x9c, 0xa4, 0xb6, 0x57, 0x2f, 0x24, 0x1e, 0x1c, 0x1c, 0x1e, 0x24, 0x2d, 0x3d, 0xf1, 0xbe, 0xb2, 0xad, 0xac, 0xad, 0xb1, 0xb9, 0xc3, 0xd4, 0xfa, 0x64, 0x65, 0xf9, 0xd9, 0xca, 0xc2, 0xbf, 0xc0, 0xc9, 0xe7, 0x4c, 0x39, 0x2e, 0x28, 0x24, 0x23, 0x25, 0x29, 0x33, 0x4f, 0xbf, 0xab, 0xa0, 0x9b, 0x99, 0x98, 0x9a, 0x9e, 0xa9, 0xc0, 0x3c, 0x26, 0x1b, 0x16, 0x12, 0x12, 0x14, 0x19, 0x22, 0x38, 0xbe, 0xa4, 0x9a, 0x93, 0x90, 0x8f, 0x92, 0x97, 0x9f, 0xb3, 0x46, 0x26, 0x1b, 0x15, 0x11, 0x11, 0x13, 0x18, 0x1f, 0x31, 0xd4, 0xab, 0x9e, 0x99, 0x96, 0x96, 0x98, 0x9c, 0xa4, 0xb4, 0x6f, 0x34, 0x28, 0x20, 0x1e, 0x1e, 0x20, 0x26, 0x2e, 0x3d, 0x6d, 0xc5, 0xb9, 0xb3, 0xb2, 0xb4, 0xba, 0xc1, 0xcd, 0xe0, 0xfc, 0xfb, 0xe0, 0xce, 0xc3, 0xbb, 0xb7, 0xb6, 0xb9, 0xc0, 0xda, 0x4b, 0x36, 0x2b, 0x25, 0x20, 0x1f, 0x20, 0x26, 0x2e, 0x46, 0xc2, 0xab, 0x9f, 0x9a, 0x97, 0x96, 0x98, 0x9c, 0xa5, 0xba, 0x41, 0x27, 0x1b, 0x15, 0x12, 0x11, 0x13, 0x18, 0x1f, 0x32, 0xc8, 0xa6, 0x9a, 0x94, 0x90, 0x8f, 0x91, 0x97, 0x9e, 0xaf, 0x54, 0x29, 0x1c, 0x16, 0x12, 0x11, 0x14, 0x18, 0x1f, 0x2e, 0xf2, 0xae, 0xa0, 0x9b, 0x98, 0x97, 0x99, 0x9d, 0xa5, 0xb3, 0xe4, 0x3a, 0x2b, 0x25, 0x21, 0x21, 0x24, 0x29, 0x30, 0x3e, 0x62, 0xcd, 0xbf, 0xbb, 0xbb, 0xbe, 0xc6, 0xd1, 0xe7, 0x76, 0x75, 0xe7, 0xcf, 0xc1, 0xb9, 0xb2, 0xaf, 0xaf, 0xb2, 0xba, 0xcf, 0x4c, 0x34, 0x29, 0x22, 0x1e, 0x1d, 0x1e, 0x22, 0x2b, 0x3e, 0xc7, 0xab, 0x9f, 0x99, 0x96, 0x95, 0x96, 0x9a, 0xa2, 0xb5, 0x4a, 0x28, 0x1c, 0x15, 0x11, 0x10, 0x12, 0x17, 0x1e, 0x2e, 0xd5, 0xa9, 0x9b, 0x95, 0x90, 0x8f, 0x91, 0x96, 0x9d, 0xac, 0x78, 0x2c, 0x1e, 0x17, 0x13, 0x12, 0x14, 0x18, 0x1f, 0x2d, 0x5d, 0xb3, 0xa4, 0x9d, 0x9a, 0x99, 0x9b, 0x9e, 0xa6, 0xb2, 0xd6, 0x3f, 0x2f, 0x29, 0x26, 0x26, 0x28, 0x2d, 0x35, 0x42, 0x5e, 0xd8, 0xca, 0xc6, 0xc9, 0xcf, 0xe4, 0x69, 0x59, 0x58, 0x64, 0xdf, 0xc7, 0xba, 0xb1, 0xac, 0xaa, 0xaa, 0xad, 0xb4, 0xc7, 0x4f, 0x33, 0x27, 0x1f, 0x1c, 0x1b, 0x1c, 0x1f, 0x27, 0x39, 0xce, 0xac, 0x9f, 0x99, 0x95, 0x94, 0x95, 0x99, 0x9f, 0xaf, 0x59, 0x2a, 0x1c, 0x16, 0x11, 0x10, 0x11, 0x16, 0x1d, 0x2b };
xrg/asterisk-xrg
channels/chan_phone.h
C
gpl-2.0
14,884
/* * QEMU SMBus device emulation. * * This code is a helper for SMBus device emulation. It implements an * I2C device inteface and runs the SMBus protocol from the device * point of view and maps those to simple calls to emulate. * * Copyright (c) 2007 CodeSourcery. * Written by Paul Brook * * This code is licensed under the LGPL. */ /* TODO: Implement PEC. */ #include "qemu/osdep.h" #include "hw/i2c/i2c.h" #include "hw/i2c/smbus_slave.h" #include "migration/vmstate.h" #include "qemu/module.h" //#define DEBUG_SMBUS 1 #ifdef DEBUG_SMBUS #define DPRINTF(fmt, ...) \ do { printf("smbus(%02x): " fmt , dev->i2c.address, ## __VA_ARGS__); } while (0) #define BADF(fmt, ...) \ do { fprintf(stderr, "smbus: error: " fmt , ## __VA_ARGS__); exit(1);} while (0) #else #define DPRINTF(fmt, ...) do {} while(0) #define BADF(fmt, ...) \ do { fprintf(stderr, "smbus: error: " fmt , ## __VA_ARGS__);} while (0) #endif enum { SMBUS_IDLE, SMBUS_WRITE_DATA, SMBUS_READ_DATA, SMBUS_DONE, SMBUS_CONFUSED = -1 }; static void smbus_do_quick_cmd(SMBusDevice *dev, int recv) { SMBusDeviceClass *sc = SMBUS_DEVICE_GET_CLASS(dev); DPRINTF("Quick Command %d\n", recv); if (sc->quick_cmd) { sc->quick_cmd(dev, recv); } } static void smbus_do_write(SMBusDevice *dev) { SMBusDeviceClass *sc = SMBUS_DEVICE_GET_CLASS(dev); DPRINTF("Command %d len %d\n", dev->data_buf[0], dev->data_len); if (sc->write_data) { sc->write_data(dev, dev->data_buf, dev->data_len); } } static int smbus_i2c_event(I2CSlave *s, enum i2c_event event) { SMBusDevice *dev = SMBUS_DEVICE(s); switch (event) { case I2C_START_SEND: switch (dev->mode) { case SMBUS_IDLE: DPRINTF("Incoming data\n"); dev->mode = SMBUS_WRITE_DATA; break; default: BADF("Unexpected send start condition in state %d\n", dev->mode); dev->mode = SMBUS_CONFUSED; break; } break; case I2C_START_RECV: switch (dev->mode) { case SMBUS_IDLE: DPRINTF("Read mode\n"); dev->mode = SMBUS_READ_DATA; break; case SMBUS_WRITE_DATA: if (dev->data_len == 0) { BADF("Read after write with no data\n"); dev->mode = SMBUS_CONFUSED; } else { smbus_do_write(dev); DPRINTF("Read mode\n"); dev->mode = SMBUS_READ_DATA; } break; default: BADF("Unexpected recv start condition in state %d\n", dev->mode); dev->mode = SMBUS_CONFUSED; break; } break; case I2C_FINISH: if (dev->data_len == 0) { if (dev->mode == SMBUS_WRITE_DATA || dev->mode == SMBUS_READ_DATA) { smbus_do_quick_cmd(dev, dev->mode == SMBUS_READ_DATA); } } else { switch (dev->mode) { case SMBUS_WRITE_DATA: smbus_do_write(dev); break; case SMBUS_READ_DATA: BADF("Unexpected stop during receive\n"); break; default: /* Nothing to do. */ break; } } dev->mode = SMBUS_IDLE; dev->data_len = 0; break; case I2C_NACK: switch (dev->mode) { case SMBUS_DONE: /* Nothing to do. */ break; case SMBUS_READ_DATA: dev->mode = SMBUS_DONE; break; default: BADF("Unexpected NACK in state %d\n", dev->mode); dev->mode = SMBUS_CONFUSED; break; } } return 0; } static uint8_t smbus_i2c_recv(I2CSlave *s) { SMBusDevice *dev = SMBUS_DEVICE(s); SMBusDeviceClass *sc = SMBUS_DEVICE_GET_CLASS(dev); uint8_t ret = 0xff; switch (dev->mode) { case SMBUS_READ_DATA: if (sc->receive_byte) { ret = sc->receive_byte(dev); } DPRINTF("Read data %02x\n", ret); break; default: BADF("Unexpected read in state %d\n", dev->mode); dev->mode = SMBUS_CONFUSED; break; } return ret; } static int smbus_i2c_send(I2CSlave *s, uint8_t data) { SMBusDevice *dev = SMBUS_DEVICE(s); switch (dev->mode) { case SMBUS_WRITE_DATA: DPRINTF("Write data %02x\n", data); if (dev->data_len >= sizeof(dev->data_buf)) { BADF("Too many bytes sent\n"); } else { dev->data_buf[dev->data_len++] = data; } break; default: BADF("Unexpected write in state %d\n", dev->mode); break; } return 0; } static void smbus_device_class_init(ObjectClass *klass, void *data) { I2CSlaveClass *sc = I2C_SLAVE_CLASS(klass); sc->event = smbus_i2c_event; sc->recv = smbus_i2c_recv; sc->send = smbus_i2c_send; } bool smbus_vmstate_needed(SMBusDevice *dev) { return dev->mode != SMBUS_IDLE; } const VMStateDescription vmstate_smbus_device = { .name = TYPE_SMBUS_DEVICE, .version_id = 1, .minimum_version_id = 1, .fields = (VMStateField[]) { VMSTATE_I2C_SLAVE(i2c, SMBusDevice), VMSTATE_INT32(mode, SMBusDevice), VMSTATE_INT32(data_len, SMBusDevice), VMSTATE_UINT8_ARRAY(data_buf, SMBusDevice, SMBUS_DATA_MAX_LEN), VMSTATE_END_OF_LIST() } }; static const TypeInfo smbus_device_type_info = { .name = TYPE_SMBUS_DEVICE, .parent = TYPE_I2C_SLAVE, .instance_size = sizeof(SMBusDevice), .abstract = true, .class_size = sizeof(SMBusDeviceClass), .class_init = smbus_device_class_init, }; static void smbus_device_register_types(void) { type_register_static(&smbus_device_type_info); } type_init(smbus_device_register_types)
dslutz/qemu
hw/i2c/smbus_slave.c
C
gpl-2.0
5,891
#!/usr/bin/env python # (c) 2012, Michael DeHaan <[email protected]> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # # this script is for testing modules without running through the # entire guts of ansible, and is very helpful for when developing # modules # # example: # ./hacking/test-module.py -m lib/ansible/modules/commands/command.py -a "/bin/sleep 3" # ./hacking/test-module.py -m lib/ansible/modules/commands/command.py -a "/bin/sleep 3" --debugger /usr/bin/pdb # ./hacking/test-module.py -m lib/ansible/modules/files/lineinfile.py -a "dest=/etc/exports line='/srv/home hostname1(rw,sync)'" --check # ./hacking/test-module.py -m lib/ansible/modules/commands/command.py -a "echo hello" -n -o "test_hello" import glob import optparse import os import subprocess import sys import traceback import shutil from ansible.release import __version__ import ansible.utils.vars as utils_vars from ansible.parsing.dataloader import DataLoader from ansible.parsing.utils.jsonify import jsonify from ansible.parsing.splitter import parse_kv import ansible.executor.module_common as module_common import ansible.constants as C from ansible.module_utils._text import to_native, to_text from ansible.template import Templar import json def parse(): """parse command line :return : (options, args)""" parser = optparse.OptionParser() parser.usage = "%prog -[options] (-h for help)" parser.add_option('-m', '--module-path', dest='module_path', help="REQUIRED: full path of module source to execute") parser.add_option('-a', '--args', dest='module_args', default="", help="module argument string") parser.add_option('-D', '--debugger', dest='debugger', help="path to python debugger (e.g. /usr/bin/pdb)") parser.add_option('-I', '--interpreter', dest='interpreter', help="path to interpreter to use for this module" " (e.g. ansible_python_interpreter=/usr/bin/python)", metavar='INTERPRETER_TYPE=INTERPRETER_PATH', default="ansible_python_interpreter=%s" % (sys.executable if sys.executable else '/usr/bin/python')) parser.add_option('-c', '--check', dest='check', action='store_true', help="run the module in check mode") parser.add_option('-n', '--noexecute', dest='execute', action='store_false', default=True, help="do not run the resulting module") parser.add_option('-o', '--output', dest='filename', help="Filename for resulting module", default="~/.ansible_module_generated") options, args = parser.parse_args() if not options.module_path: parser.print_help() sys.exit(1) else: return options, args def write_argsfile(argstring, json=False): """ Write args to a file for old-style module's use. """ argspath = os.path.expanduser("~/.ansible_test_module_arguments") argsfile = open(argspath, 'w') if json: args = parse_kv(argstring) argstring = jsonify(args) argsfile.write(argstring) argsfile.close() return argspath def get_interpreters(interpreter): result = dict() if interpreter: if '=' not in interpreter: print("interpreter must by in the form of ansible_python_interpreter=/usr/bin/python") sys.exit(1) interpreter_type, interpreter_path = interpreter.split('=') if not interpreter_type.startswith('ansible_'): interpreter_type = 'ansible_%s' % interpreter_type if not interpreter_type.endswith('_interpreter'): interpreter_type = '%s_interpreter' % interpreter_type result[interpreter_type] = interpreter_path return result def boilerplate_module(modfile, args, interpreters, check, destfile): """ simulate what ansible does with new style modules """ # module_fh = open(modfile) # module_data = module_fh.read() # module_fh.close() # replacer = module_common.ModuleReplacer() loader = DataLoader() # included_boilerplate = module_data.find(module_common.REPLACER) != -1 or module_data.find("import ansible.module_utils") != -1 complex_args = {} # default selinux fs list is pass in as _ansible_selinux_special_fs arg complex_args['_ansible_selinux_special_fs'] = C.DEFAULT_SELINUX_SPECIAL_FS complex_args['_ansible_tmpdir'] = C.DEFAULT_LOCAL_TMP complex_args['_ansible_keep_remote_files'] = C.DEFAULT_KEEP_REMOTE_FILES complex_args['_ansible_version'] = __version__ if args.startswith("@"): # Argument is a YAML file (JSON is a subset of YAML) complex_args = utils_vars.combine_vars(complex_args, loader.load_from_file(args[1:])) args = '' elif args.startswith("{"): # Argument is a YAML document (not a file) complex_args = utils_vars.combine_vars(complex_args, loader.load(args)) args = '' if args: parsed_args = parse_kv(args) complex_args = utils_vars.combine_vars(complex_args, parsed_args) task_vars = interpreters if check: complex_args['_ansible_check_mode'] = True modname = os.path.basename(modfile) modname = os.path.splitext(modname)[0] (module_data, module_style, shebang) = module_common.modify_module( modname, modfile, complex_args, Templar(loader=loader), task_vars=task_vars ) if module_style == 'new' and '_ANSIBALLZ_WRAPPER = True' in to_native(module_data): module_style = 'ansiballz' modfile2_path = os.path.expanduser(destfile) print("* including generated source, if any, saving to: %s" % modfile2_path) if module_style not in ('ansiballz', 'old'): print("* this may offset any line numbers in tracebacks/debuggers!") modfile2 = open(modfile2_path, 'wb') modfile2.write(module_data) modfile2.close() modfile = modfile2_path return (modfile2_path, modname, module_style) def ansiballz_setup(modfile, modname, interpreters): os.system("chmod +x %s" % modfile) if 'ansible_python_interpreter' in interpreters: command = [interpreters['ansible_python_interpreter']] else: command = [] command.extend([modfile, 'explode']) cmd = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = cmd.communicate() out, err = to_text(out, errors='surrogate_or_strict'), to_text(err) lines = out.splitlines() if len(lines) != 2 or 'Module expanded into' not in lines[0]: print("*" * 35) print("INVALID OUTPUT FROM ANSIBALLZ MODULE WRAPPER") print(out) sys.exit(err) debug_dir = lines[1].strip() # All the directories in an AnsiBallZ that modules can live core_dirs = glob.glob(os.path.join(debug_dir, 'ansible/modules')) collection_dirs = glob.glob(os.path.join(debug_dir, 'ansible_collections/*/*/plugins/modules')) # There's only one module in an AnsiBallZ payload so look for the first module and then exit for module_dir in core_dirs + collection_dirs: for dirname, directories, filenames in os.walk(module_dir): for filename in filenames: if filename == modname + '.py': modfile = os.path.join(dirname, filename) break argsfile = os.path.join(debug_dir, 'args') print("* ansiballz module detected; extracted module source to: %s" % debug_dir) return modfile, argsfile def runtest(modfile, argspath, modname, module_style, interpreters): """Test run a module, piping it's output for reporting.""" invoke = "" if module_style == 'ansiballz': modfile, argspath = ansiballz_setup(modfile, modname, interpreters) if 'ansible_python_interpreter' in interpreters: invoke = "%s " % interpreters['ansible_python_interpreter'] os.system("chmod +x %s" % modfile) invoke = "%s%s" % (invoke, modfile) if argspath is not None: invoke = "%s %s" % (invoke, argspath) cmd = subprocess.Popen(invoke, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = cmd.communicate() out, err = to_text(out), to_text(err) try: print("*" * 35) print("RAW OUTPUT") print(out) print(err) results = json.loads(out) except Exception: print("*" * 35) print("INVALID OUTPUT FORMAT") print(out) traceback.print_exc() sys.exit(1) print("*" * 35) print("PARSED OUTPUT") print(jsonify(results, format=True)) def rundebug(debugger, modfile, argspath, modname, module_style, interpreters): """Run interactively with console debugger.""" if module_style == 'ansiballz': modfile, argspath = ansiballz_setup(modfile, modname, interpreters) if argspath is not None: subprocess.call("%s %s %s" % (debugger, modfile, argspath), shell=True) else: subprocess.call("%s %s" % (debugger, modfile), shell=True) def main(): options, args = parse() interpreters = get_interpreters(options.interpreter) (modfile, modname, module_style) = boilerplate_module(options.module_path, options.module_args, interpreters, options.check, options.filename) argspath = None if module_style not in ('new', 'ansiballz'): if module_style in ('non_native_want_json', 'binary'): argspath = write_argsfile(options.module_args, json=True) elif module_style == 'old': argspath = write_argsfile(options.module_args, json=False) else: raise Exception("internal error, unexpected module style: %s" % module_style) if options.execute: if options.debugger: rundebug(options.debugger, modfile, argspath, modname, module_style, interpreters) else: runtest(modfile, argspath, modname, module_style, interpreters) if __name__ == "__main__": try: main() finally: shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
tumbl3w33d/ansible
hacking/test-module.py
Python
gpl-3.0
10,760
/****************************************************************************** * Copyright (c) 2004, 2008 IBM Corporation * All rights reserved. * This program and the accompanying materials * are made available under the terms of the BSD License * which accompanies this distribution, and is available at * http://www.opensource.org/licenses/bsd-license.php * * Contributors: * IBM Corporation - initial implementation *****************************************************************************/ #ifndef DEVICE_LIB_H #define DEVICE_LIB_H #include <stdint.h> #include <cpu.h> #include "of.h" #include <stdio.h> // a Expansion Header Struct as defined in Plug and Play BIOS Spec 1.0a Chapter 3.2 typedef struct { char signature[4]; // signature uint8_t structure_revision; uint8_t length; // in 16 byte blocks uint16_t next_header_offset; // offset to next Expansion Header as 16bit little-endian value, as offset from the start of the Expansion ROM uint8_t reserved; uint8_t checksum; // the sum of all bytes of the Expansion Header must be 0 uint32_t device_id; // PnP Device ID as 32bit little-endian value uint16_t p_manufacturer_string; //16bit little-endian offset from start of Expansion ROM uint16_t p_product_string; //16bit little-endian offset from start of Expansion ROM uint8_t device_base_type; uint8_t device_sub_type; uint8_t device_if_type; uint8_t device_indicators; // the following vectors are all 16bit little-endian offsets from start of Expansion ROM uint16_t bcv; // Boot Connection Vector uint16_t dv; // Disconnect Vector uint16_t bev; // Bootstrap Entry Vector uint16_t reserved_2; uint16_t sriv; // Static Resource Information Vector } __attribute__ ((__packed__)) exp_header_struct_t; // a PCI Data Struct as defined in PCI 2.3 Spec Chapter 6.3.1.2 typedef struct { uint8_t signature[4]; // signature, the String "PCIR" uint16_t vendor_id; uint16_t device_id; uint16_t reserved; uint16_t pci_ds_length; // PCI Data Structure Length, 16bit little-endian value uint8_t pci_ds_revision; uint8_t class_code[3]; uint16_t img_length; // length of the Exp.ROM Image, 16bit little-endian value in 512 bytes uint16_t img_revision; uint8_t code_type; uint8_t indicator; uint16_t reserved_2; } __attribute__ ((__packed__)) pci_data_struct_t; typedef struct { uint8_t bus; uint8_t devfn; uint64_t puid; phandle_t phandle; ihandle_t ihandle; // store the address of the BAR that is used to simulate // legacy VGA memory accesses uint64_t vmem_addr; uint64_t vmem_size; // used to buffer I/O Accesses, that do not access the I/O Range of the device... // 64k might be overkill, but we can buffer all I/O accesses... uint8_t io_buffer[64 * 1024]; uint16_t pci_vendor_id; uint16_t pci_device_id; // translated address of the "PC-Compatible" Expansion ROM Image for this device uint64_t img_addr; uint32_t img_size; // size of the Expansion ROM Image (read from the PCI Data Structure) } device_t; typedef struct { uint8_t info; uint8_t bus; uint8_t devfn; uint8_t cfg_space_offset; uint64_t address; uint64_t address_offset; uint64_t size; } __attribute__ ((__packed__)) translate_address_t; // array to store address translations for this // device. Needed for faster address translation, so // not every I/O or Memory Access needs to call translate_address_dev // and access the device tree // 6 BARs, 1 Exp. ROM, 1 Cfg.Space, and 3 Legacy // translations are supported... this should be enough for // most devices... for VGA it is enough anyways... translate_address_t translate_address_array[11]; // index of last translate_address_array entry // set by get_dev_addr_info function uint8_t taa_last_entry; device_t bios_device; uint8_t dev_init(char *device_name); // NOTE: for dev_check_exprom to work, dev_init MUST be called first! uint8_t dev_check_exprom(); uint8_t dev_translate_address(uint64_t * addr); /* endianness swap functions for 16 and 32 bit words * copied from axon_pciconfig.c */ static inline void out32le(void *addr, uint32_t val) { asm volatile ("stwbrx %0, 0, %1"::"r" (val), "r"(addr)); } static inline uint32_t in32le(void *addr) { uint32_t val; asm volatile ("lwbrx %0, 0, %1":"=r" (val):"r"(addr)); return val; } static inline void out16le(void *addr, uint16_t val) { asm volatile ("sthbrx %0, 0, %1"::"r" (val), "r"(addr)); } static inline uint16_t in16le(void *addr) { uint16_t val; asm volatile ("lhbrx %0, 0, %1":"=r" (val):"r"(addr)); return val; } /* debug function, dumps HID1 and HID4 to detect wether caches are on/off */ static inline void dumpHID() { uint64_t hid; //HID1 = 1009 __asm__ __volatile__("mfspr %0, 1009":"=r"(hid)); printf("HID1: %016llx\n", hid); //HID4 = 1012 __asm__ __volatile__("mfspr %0, 1012":"=r"(hid)); printf("HID4: %016llx\n", hid); } #endif
KernelAnalysisPlatform/KlareDbg
tracers/qemu/decaf/roms/SLOF/clients/net-snk/app/biosemu/device.h
C
gpl-3.0
4,832
require File.dirname(__FILE__) + '/test_helper' class MyHighlightingObject include Widgets::Highlightable end class HighlightableTest < Test::Unit::TestCase EXPECTED_INSTANCE_METHODS = %w{highlights highlights= highlighted? highlights_on} def setup @obj = MyHighlightingObject.new end def test_included_methods EXPECTED_INSTANCE_METHODS.each do |method| assert @obj.respond_to?(method), "An Highlightable object should respond to '#{method}'" end end def test_accessor assert_equal [], @obj.highlights, 'should return an empty array' end def test_highlights_on @obj.highlights=[ {:action => 'my_action'}, {:action => 'my_action2', :controller => 'my_controller'}] assert @obj.highlights.kind_of?(Array) assert_equal 2, @obj.highlights.size, '2 highlights were added so far' @obj.highlights.each {|hl| assert hl.kind_of?(Hash)} # sanity check assert_equal 'my_action',@obj.highlights[0][:action] end def test_highlights_on_proc @bonus_points = 0 @obj.highlights_on proc {@bonus_points > 5} assert [email protected]?, 'should not highlight until @bonus_points is greater than 5' @bonus_points = 10 assert @obj.highlighted?, 'should highlight because @bonus_points is greater than 5' end def test_highlight_on_string @obj.highlights_on "http://www.seesaw.it" end def test_highlighted? @obj.highlights_on :controller => 'pippo' #check that highlights on its own link assert @obj.highlighted?(:controller => 'pippo'), 'should highlight' assert @obj.highlighted?(:controller => 'pippo', :action => 'list'), 'should highlight' assert [email protected]?(:controller => 'pluto', :action => 'list'), 'should NOT highlight' end def test_more_highlighted? # add some other highlighting rules # and check again @obj.highlights=[{:controller => 'pluto'}] assert @obj.highlighted?(:controller => 'pluto'), 'should highlight' @obj.highlights << {:controller => 'granny', :action => 'oyster'} assert @obj.highlighted?(:controller => 'granny', :action => 'oyster'), 'should highlight' assert [email protected]?(:controller => 'granny', :action => 'daddy'), 'should NOT highlight' end def test_highlighted_with_slash @obj.highlights_on :controller => '/pippo' assert @obj.highlighted?({:controller => 'pippo'}) end end
kplawver/leihs
vendor/plugins/widgets/test/highlightable_test.rb
Ruby
gpl-3.0
2,516
// Copyright John Maddock 2006-15. // Copyright Paul A. Bristow 2007 // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "bindings.hpp" #include "../../test/test_binomial_coeff.hpp" #include <boost/math/special_functions/binomial.hpp> BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES(test_main, 10000); BOOST_AUTO_TEST_CASE(test_main) { BOOST_MATH_CONTROL_FP; error_stream_replacer rep; #ifdef TYPE_TO_TEST test_binomial(static_cast<TYPE_TO_TEST>(0), NAME_OF_TYPE_TO_TEST); #else bool test_float = false; bool test_double = false; bool test_long_double = false; if(std::numeric_limits<long double>::digits == std::numeric_limits<double>::digits) { // // Don't bother with long double, it's the same as double: // if(BOOST_MATH_PROMOTE_FLOAT_POLICY == false) test_float = true; test_double = true; } else { if(BOOST_MATH_PROMOTE_FLOAT_POLICY == false) test_float = true; if(BOOST_MATH_PROMOTE_DOUBLE_POLICY == false) test_double = true; test_long_double = true; } #ifdef ALWAYS_TEST_DOUBLE test_double = true; #endif if(test_float) test_binomial(0.0f, "float"); if(test_double) test_binomial(0.0, "double"); if(test_long_double) test_binomial(0.0L, "long double"); #ifdef BOOST_MATH_USE_FLOAT128 //test_binomial(0.0Q, "__float128"); #endif #endif }
gwq5210/litlib
thirdparty/sources/boost_1_60_0/libs/math/reporting/accuracy/test_binomial_coeff.cpp
C++
gpl-3.0
1,545
/* Provide a version vfprintf in terms of _doprnt. By Kaveh Ghazi ([email protected]) 3/29/98 Copyright (C) 1998 Free Software Foundation, Inc. */ #ifdef __STDC__ #include <stdarg.h> #else #include <varargs.h> #endif #include <stdio.h> #undef vfprintf int vfprintf (stream, format, ap) FILE * stream; const char * format; va_list ap; { return _doprnt (format, ap, stream); }
uhhpctools/openuh-openacc
osprey/libiberty/vfprintf.c
C
gpl-3.0
399
<?php return [ 710 => 94, 189 => 188, 190 => 179, 65 => 97, 170 => 97, 225 => 97, 193 => 97, 224 => 97, 192 => 97, 226 => 97, 194 => 97, 228 => 97, 196 => 97, 227 => 97, 195 => 97, 229 => 97, 197 => 97, 230 => 97, 198 => 97, 66 => 98, 67 => 99, 231 => 99, 199 => 99, 68 => 100, 240 => 100, 208 => 100, 69 => 101, 233 => 101, 201 => 101, 232 => 101, 200 => 101, 234 => 101, 202 => 101, 235 => 101, 203 => 101, 103 => 102, 70 => 102, 71 => 102, 402 => 102, 72 => 104, 73 => 105, 237 => 105, 205 => 105, 236 => 105, 204 => 105, 238 => 105, 206 => 105, 239 => 105, 207 => 105, 74 => 106, 75 => 107, 76 => 108, 77 => 109, 78 => 110, 241 => 110, 209 => 110, 79 => 111, 186 => 111, 243 => 111, 211 => 111, 242 => 111, 210 => 111, 244 => 111, 212 => 111, 246 => 111, 214 => 111, 245 => 111, 213 => 111, 248 => 111, 216 => 111, 339 => 111, 338 => 111, 80 => 112, 81 => 113, 82 => 114, 83 => 115, 353 => 115, 352 => 115, 223 => 115, 84 => 116, 222 => 254, 85 => 117, 250 => 117, 218 => 117, 249 => 117, 217 => 117, 251 => 117, 219 => 117, 252 => 117, 220 => 117, 86 => 118, 87 => 119, 88 => 120, 89 => 121, 253 => 121, 221 => 121, 255 => 121, 376 => 121, 90 => 122, 382 => 122, 381 => 122, ];
Motorui/ass-app
vendor/mpdf/mpdf/data/collations/Welsh_United_Kingdom.php
PHP
gpl-3.0
1,385
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code, released * March 31, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ gTestfile = '15-1.js'; /** File Name: 15.js ECMA Section: 15 Native ECMAScript Objects Description: Every built-in prototype object has the Object prototype object, which is the value of the expression Object.prototype (15.2.3.1) as the value of its internal [[Prototype]] property, except the Object prototype object itself. Every native object associated with a program-created function also has the Object prototype object as the value of its internal [[Prototype]] property. Author: [email protected] Date: 28 october 1997 */ var SECTION = "15-1"; var VERSION = "ECMA_1"; startTest(); var TITLE = "Native ECMAScript Objects"; writeHeaderToLog( SECTION + " "+ TITLE); /* new TestCase( SECTION, "Function.prototype.__proto__", Object.prototype, Function.prototype.__proto__ ); new TestCase( SECTION, "Array.prototype.__proto__", Object.prototype, Array.prototype.__proto__ ); new TestCase( SECTION, "String.prototype.__proto__", Object.prototype, String.prototype.__proto__ ); new TestCase( SECTION, "Boolean.prototype.__proto__", Object.prototype, Boolean.prototype.__proto__ ); new TestCase( SECTION, "Number.prototype.__proto__", Object.prototype, Number.prototype.__proto__ ); // new TestCase( SECTION, "Math.prototype.__proto__", Object.prototype, Math.prototype.__proto__ ); new TestCase( SECTION, "Date.prototype.__proto__", Object.prototype, Date.prototype.__proto__ ); new TestCase( SECTION, "TestCase.prototype.__proto__", Object.prototype, TestCase.prototype.__proto__ ); new TestCase( SECTION, "MyObject.prototype.__proto__", Object.prototype, MyObject.prototype.__proto__ ); */ new TestCase( SECTION, "Function.prototype.__proto__ == Object.prototype", true, Function.prototype.__proto__ == Object.prototype ); new TestCase( SECTION, "Array.prototype.__proto__ == Object.prototype", true, Array.prototype.__proto__ == Object.prototype ); new TestCase( SECTION, "String.prototype.__proto__ == Object.prototype", true, String.prototype.__proto__ == Object.prototype ); new TestCase( SECTION, "Boolean.prototype.__proto__ == Object.prototype", true, Boolean.prototype.__proto__ == Object.prototype ); new TestCase( SECTION, "Number.prototype.__proto__ == Object.prototype", true, Number.prototype.__proto__ == Object.prototype ); // new TestCase( SECTION, "Math.prototype.__proto__ == Object.prototype", true, Math.prototype.__proto__ == Object.prototype ); new TestCase( SECTION, "Date.prototype.__proto__ == Object.prototype", true, Date.prototype.__proto__ == Object.prototype ); new TestCase( SECTION, "TestCase.prototype.__proto__ == Object.prototype", true, TestCase.prototype.__proto__ == Object.prototype ); new TestCase( SECTION, "MyObject.prototype.__proto__ == Object.prototype", true, MyObject.prototype.__proto__ == Object.prototype ); test(); function MyObject( value ) { this.value = value; this.valueOf = new Function( "return this.value" ); }
igor-sfdc/qt-wk
tests/auto/qscriptjstestsuite/tests/ecma/extensions/15-1.js
JavaScript
lgpl-2.1
4,904
package codeInsight.completion.variables.locals; public class TestSource4 { int aaa = 0; public static void foo(){ final int abc = 0; class Inner1{ int sbe=abc<caret> } } }
smmribeiro/intellij-community
java/java-tests/testData/codeInsight/completion/variables/locals/TestResult4.java
Java
apache-2.0
221
var m1_a1 = 10; var m1_c1 = /** @class */ (function () { function m1_c1() { } return m1_c1; }()); var m1_instance1 = new m1_c1(); function m1_f1() { return m1_instance1; } var m2_a1 = 10; var m2_c1 = /** @class */ (function () { function m2_c1() { } return m2_c1; }()); var m2_instance1 = new m2_c1(); function m2_f1() { return m2_instance1; } /// <reference path='ref/m1.ts'/> /// <reference path='../outputdir_multifolder_ref/m2.ts'/> var a1 = 10; var c1 = /** @class */ (function () { function c1() { } return c1; }()); var instance1 = new c1(); function f1() { return instance1; } //# sourceMappingURL=/tests/cases/projects/outputdir_multifolder/mapFiles/test.js.map
domchen/typescript-plus
tests/baselines/reference/project/mapRootAbsolutePathMultifolderSpecifyOutputFile/node/bin/test.js
JavaScript
apache-2.0
750
package com.twitter.finagle.httpx.service import com.twitter.finagle.httpx.{Request, Status} import com.twitter.finagle.httpx.Method.{Get, Post} import com.twitter.finagle.httpx.path._ import com.twitter.finagle.httpx.path.{Path => FPath} import com.twitter.util.Await import org.junit.runner.RunWith import org.scalatest.FunSuite import org.scalatest.junit.JUnitRunner @RunWith(classOf[JUnitRunner]) class RoutingServiceTest extends FunSuite { test("RoutingService.byPath") { val service = RoutingService.byPath { case "/test.json" => NullService } assert(Await.result(service(Request("/test.json"))).status === Status.Ok) assert(Await.result(service(Request("/unknown"))).status === Status.NotFound) } test("RoutingService.byPathObject") { val service = RoutingService.byPathObject { case Root / "test" ~ "json" => NullService } assert(Await.result(service(Request("/test.json"))).status === Status.Ok) assert(Await.result(service(Request("/unknown"))).status === Status.NotFound) } test("RoutingService.byMethodAndPath") { val service = RoutingService.byMethodAndPath { case (Get, "/test.json") => NullService } assert(Await.result(service(Request("/test.json"))).status === Status.Ok) assert(Await.result(service(Request(Post, "/test.json"))).status === Status.NotFound) } test("RoutingService.byMethodAndPathObject") { val service = RoutingService.byMethodAndPathObject { case Get -> Root / "test.json" => NullService } assert(Await.result(service(Request("/test.json"))).status === Status.Ok) assert(Await.result(service(Request(Post, "/test.json"))).status === Status.NotFound) } }
travisbrown/finagle
finagle-httpx/src/test/scala/com/twitter/finagle/httpx/service/RoutingServiceTest.scala
Scala
apache-2.0
1,705
/** * 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.mapred; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import java.nio.charset.StandardCharsets; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.BZip2Codec; import org.apache.hadoop.io.compress.CodecPool; import org.apache.hadoop.io.compress.Decompressor; import org.junit.Test; public class TestLineRecordReader { private static Path workDir = new Path(new Path(System.getProperty( "test.build.data", "target"), "data"), "TestTextInputFormat"); private static Path inputDir = new Path(workDir, "input"); private void testSplitRecords(String testFileName, long firstSplitLength) throws IOException { URL testFileUrl = getClass().getClassLoader().getResource(testFileName); assertNotNull("Cannot find " + testFileName, testFileUrl); File testFile = new File(testFileUrl.getFile()); long testFileSize = testFile.length(); Path testFilePath = new Path(testFile.getAbsolutePath()); Configuration conf = new Configuration(); testSplitRecordsForFile(conf, firstSplitLength, testFileSize, testFilePath); } private void testSplitRecordsForFile(Configuration conf, long firstSplitLength, long testFileSize, Path testFilePath) throws IOException { conf.setInt(org.apache.hadoop.mapreduce.lib.input. LineRecordReader.MAX_LINE_LENGTH, Integer.MAX_VALUE); assertTrue("unexpected test data at " + testFilePath, testFileSize > firstSplitLength); String delimiter = conf.get("textinputformat.record.delimiter"); byte[] recordDelimiterBytes = null; if (null != delimiter) { recordDelimiterBytes = delimiter.getBytes(StandardCharsets.UTF_8); } // read the data without splitting to count the records FileSplit split = new FileSplit(testFilePath, 0, testFileSize, (String[])null); LineRecordReader reader = new LineRecordReader(conf, split, recordDelimiterBytes); LongWritable key = new LongWritable(); Text value = new Text(); int numRecordsNoSplits = 0; while (reader.next(key, value)) { ++numRecordsNoSplits; } reader.close(); // count the records in the first split split = new FileSplit(testFilePath, 0, firstSplitLength, (String[])null); reader = new LineRecordReader(conf, split, recordDelimiterBytes); int numRecordsFirstSplit = 0; while (reader.next(key, value)) { ++numRecordsFirstSplit; } reader.close(); // count the records in the second split split = new FileSplit(testFilePath, firstSplitLength, testFileSize - firstSplitLength, (String[])null); reader = new LineRecordReader(conf, split, recordDelimiterBytes); int numRecordsRemainingSplits = 0; while (reader.next(key, value)) { ++numRecordsRemainingSplits; } reader.close(); assertEquals("Unexpected number of records in split", numRecordsNoSplits, numRecordsFirstSplit + numRecordsRemainingSplits); } private void testLargeSplitRecordForFile(Configuration conf, long firstSplitLength, long testFileSize, Path testFilePath) throws IOException { conf.setInt(org.apache.hadoop.mapreduce.lib.input. LineRecordReader.MAX_LINE_LENGTH, Integer.MAX_VALUE); assertTrue("unexpected firstSplitLength:" + firstSplitLength, testFileSize < firstSplitLength); String delimiter = conf.get("textinputformat.record.delimiter"); byte[] recordDelimiterBytes = null; if (null != delimiter) { recordDelimiterBytes = delimiter.getBytes(StandardCharsets.UTF_8); } // read the data without splitting to count the records FileSplit split = new FileSplit(testFilePath, 0, testFileSize, (String[])null); LineRecordReader reader = new LineRecordReader(conf, split, recordDelimiterBytes); LongWritable key = new LongWritable(); Text value = new Text(); int numRecordsNoSplits = 0; while (reader.next(key, value)) { ++numRecordsNoSplits; } reader.close(); // count the records in the first split split = new FileSplit(testFilePath, 0, firstSplitLength, (String[])null); reader = new LineRecordReader(conf, split, recordDelimiterBytes); int numRecordsFirstSplit = 0; while (reader.next(key, value)) { ++numRecordsFirstSplit; } reader.close(); assertEquals("Unexpected number of records in split", numRecordsNoSplits, numRecordsFirstSplit); } @Test public void testBzip2SplitEndsAtCR() throws IOException { // the test data contains a carriage-return at the end of the first // split which ends at compressed offset 136498 and the next // character is not a linefeed testSplitRecords("blockEndingInCR.txt.bz2", 136498); } @Test public void testBzip2SplitEndsAtCRThenLF() throws IOException { // the test data contains a carriage-return at the end of the first // split which ends at compressed offset 136498 and the next // character is a linefeed testSplitRecords("blockEndingInCRThenLF.txt.bz2", 136498); } //This test ensures record reader doesn't lose records when it starts //exactly at the starting byte of a bz2 compressed block @Test public void testBzip2SplitStartAtBlockMarker() throws IOException { //136504 in blockEndingInCR.txt.bz2 is the byte at which the bz2 block ends //In the following test cases record readers should iterate over all the records //and should not miss any record. //Start next split at just the start of the block. testSplitRecords("blockEndingInCR.txt.bz2", 136504); //Start next split a byte forward in next block. testSplitRecords("blockEndingInCR.txt.bz2", 136505); //Start next split 3 bytes forward in next block. testSplitRecords("blockEndingInCR.txt.bz2", 136508); //Start next split 10 bytes from behind the end marker. testSplitRecords("blockEndingInCR.txt.bz2", 136494); } @Test(expected=IOException.class) public void testSafeguardSplittingUnsplittableFiles() throws IOException { // The LineRecordReader must fail when trying to read a file that // was compressed using an unsplittable file format testSplitRecords("TestSafeguardSplittingUnsplittableFiles.txt.gz", 2); } // Use the LineRecordReader to read records from the file public ArrayList<String> readRecords(URL testFileUrl, int splitSize) throws IOException { // Set up context File testFile = new File(testFileUrl.getFile()); long testFileSize = testFile.length(); Path testFilePath = new Path(testFile.getAbsolutePath()); Configuration conf = new Configuration(); conf.setInt("io.file.buffer.size", 1); // Gather the records returned by the record reader ArrayList<String> records = new ArrayList<String>(); long offset = 0; LongWritable key = new LongWritable(); Text value = new Text(); while (offset < testFileSize) { FileSplit split = new FileSplit(testFilePath, offset, splitSize, (String[]) null); LineRecordReader reader = new LineRecordReader(conf, split); while (reader.next(key, value)) { records.add(value.toString()); } offset += splitSize; } return records; } // Gather the records by just splitting on new lines public String[] readRecordsDirectly(URL testFileUrl, boolean bzip) throws IOException { int MAX_DATA_SIZE = 1024 * 1024; byte[] data = new byte[MAX_DATA_SIZE]; FileInputStream fis = new FileInputStream(testFileUrl.getFile()); int count; if (bzip) { BZip2CompressorInputStream bzIn = new BZip2CompressorInputStream(fis); count = bzIn.read(data); bzIn.close(); } else { count = fis.read(data); } fis.close(); assertTrue("Test file data too big for buffer", count < data.length); return new String(data, 0, count, "UTF-8").split("\n"); } public void checkRecordSpanningMultipleSplits(String testFile, int splitSize, boolean bzip) throws IOException { URL testFileUrl = getClass().getClassLoader().getResource(testFile); ArrayList<String> records = readRecords(testFileUrl, splitSize); String[] actuals = readRecordsDirectly(testFileUrl, bzip); assertEquals("Wrong number of records", actuals.length, records.size()); boolean hasLargeRecord = false; for (int i = 0; i < actuals.length; ++i) { assertEquals(actuals[i], records.get(i)); if (actuals[i].length() > 2 * splitSize) { hasLargeRecord = true; } } assertTrue("Invalid test data. Doesn't have a large enough record", hasLargeRecord); } @Test public void testRecordSpanningMultipleSplits() throws IOException { checkRecordSpanningMultipleSplits("recordSpanningMultipleSplits.txt", 10, false); } @Test public void testRecordSpanningMultipleSplitsCompressed() throws IOException { // The file is generated with bz2 block size of 100k. The split size // needs to be larger than that for the CompressedSplitLineReader to // work. checkRecordSpanningMultipleSplits("recordSpanningMultipleSplits.txt.bz2", 200 * 1000, true); } @Test public void testStripBOM() throws IOException { // the test data contains a BOM at the start of the file // confirm the BOM is skipped by LineRecordReader String UTF8_BOM = "\uFEFF"; URL testFileUrl = getClass().getClassLoader().getResource("testBOM.txt"); assertNotNull("Cannot find testBOM.txt", testFileUrl); File testFile = new File(testFileUrl.getFile()); Path testFilePath = new Path(testFile.getAbsolutePath()); long testFileSize = testFile.length(); Configuration conf = new Configuration(); conf.setInt(org.apache.hadoop.mapreduce.lib.input. LineRecordReader.MAX_LINE_LENGTH, Integer.MAX_VALUE); // read the data and check whether BOM is skipped FileSplit split = new FileSplit(testFilePath, 0, testFileSize, (String[])null); LineRecordReader reader = new LineRecordReader(conf, split); LongWritable key = new LongWritable(); Text value = new Text(); int numRecords = 0; boolean firstLine = true; boolean skipBOM = true; while (reader.next(key, value)) { if (firstLine) { firstLine = false; if (value.toString().startsWith(UTF8_BOM)) { skipBOM = false; } } ++numRecords; } reader.close(); assertTrue("BOM is not skipped", skipBOM); } @Test public void testMultipleClose() throws IOException { URL testFileUrl = getClass().getClassLoader(). getResource("recordSpanningMultipleSplits.txt.bz2"); assertNotNull("Cannot find recordSpanningMultipleSplits.txt.bz2", testFileUrl); File testFile = new File(testFileUrl.getFile()); Path testFilePath = new Path(testFile.getAbsolutePath()); long testFileSize = testFile.length(); Configuration conf = new Configuration(); conf.setInt(org.apache.hadoop.mapreduce.lib.input. LineRecordReader.MAX_LINE_LENGTH, Integer.MAX_VALUE); FileSplit split = new FileSplit(testFilePath, 0, testFileSize, (String[])null); LineRecordReader reader = new LineRecordReader(conf, split); LongWritable key = new LongWritable(); Text value = new Text(); //noinspection StatementWithEmptyBody while (reader.next(key, value)) ; reader.close(); reader.close(); BZip2Codec codec = new BZip2Codec(); codec.setConf(conf); Set<Decompressor> decompressors = new HashSet<Decompressor>(); for (int i = 0; i < 10; ++i) { decompressors.add(CodecPool.getDecompressor(codec)); } assertEquals(10, decompressors.size()); } /** * Writes the input test file * * @param conf * @return Path of the file created * @throws IOException */ private Path createInputFile(Configuration conf, String data) throws IOException { FileSystem localFs = FileSystem.getLocal(conf); Path file = new Path(inputDir, "test.txt"); Writer writer = new OutputStreamWriter(localFs.create(file)); try { writer.write(data); } finally { writer.close(); } return file; } @Test public void testUncompressedInputWithLargeSplitSize() throws Exception { Configuration conf = new Configuration(); // single char delimiter String inputData = "abcde +fghij+ klmno+pqrst+uvwxyz"; Path inputFile = createInputFile(conf, inputData); conf.set("textinputformat.record.delimiter", "+"); // split size over max value of integer long longSplitSize = (long)Integer.MAX_VALUE + 1; for (int bufferSize = 1; bufferSize <= inputData.length(); bufferSize++) { conf.setInt("io.file.buffer.size", bufferSize); testLargeSplitRecordForFile(conf, longSplitSize, inputData.length(), inputFile); } } @Test public void testUncompressedInput() throws Exception { Configuration conf = new Configuration(); // single char delimiter, best case String inputData = "abc+def+ghi+jkl+mno+pqr+stu+vw +xyz"; Path inputFile = createInputFile(conf, inputData); conf.set("textinputformat.record.delimiter", "+"); for (int bufferSize = 1; bufferSize <= inputData.length(); bufferSize++) { for (int splitSize = 1; splitSize < inputData.length(); splitSize++) { conf.setInt("io.file.buffer.size", bufferSize); testSplitRecordsForFile(conf, splitSize, inputData.length(), inputFile); } } // multi char delimiter, best case inputData = "abc|+|def|+|ghi|+|jkl|+|mno|+|pqr|+|stu|+|vw |+|xyz"; inputFile = createInputFile(conf, inputData); conf.set("textinputformat.record.delimiter", "|+|"); for (int bufferSize = 1; bufferSize <= inputData.length(); bufferSize++) { for (int splitSize = 1; splitSize < inputData.length(); splitSize++) { conf.setInt("io.file.buffer.size", bufferSize); testSplitRecordsForFile(conf, splitSize, inputData.length(), inputFile); } } // single char delimiter with empty records inputData = "abc+def++ghi+jkl++mno+pqr++stu+vw ++xyz"; inputFile = createInputFile(conf, inputData); conf.set("textinputformat.record.delimiter", "+"); for (int bufferSize = 1; bufferSize <= inputData.length(); bufferSize++) { for (int splitSize = 1; splitSize < inputData.length(); splitSize++) { conf.setInt("io.file.buffer.size", bufferSize); testSplitRecordsForFile(conf, splitSize, inputData.length(), inputFile); } } // multi char delimiter with empty records inputData = "abc|+||+|defghi|+|jkl|+||+|mno|+|pqr|+||+|stu|+|vw |+||+|xyz"; inputFile = createInputFile(conf, inputData); conf.set("textinputformat.record.delimiter", "|+|"); for (int bufferSize = 1; bufferSize <= inputData.length(); bufferSize++) { for (int splitSize = 1; splitSize < inputData.length(); splitSize++) { conf.setInt("io.file.buffer.size", bufferSize); testSplitRecordsForFile(conf, splitSize, inputData.length(), inputFile); } } // multi char delimiter with starting part of the delimiter in the data inputData = "abc+def+-ghi+jkl+-mno+pqr+-stu+vw +-xyz"; inputFile = createInputFile(conf, inputData); conf.set("textinputformat.record.delimiter", "+-"); for (int bufferSize = 1; bufferSize <= inputData.length(); bufferSize++) { for (int splitSize = 1; splitSize < inputData.length(); splitSize++) { conf.setInt("io.file.buffer.size", bufferSize); testSplitRecordsForFile(conf, splitSize, inputData.length(), inputFile); } } // multi char delimiter with newline as start of the delimiter inputData = "abc\n+def\n+ghi\n+jkl\n+mno"; inputFile = createInputFile(conf, inputData); conf.set("textinputformat.record.delimiter", "\n+"); for (int bufferSize = 1; bufferSize <= inputData.length(); bufferSize++) { for (int splitSize = 1; splitSize < inputData.length(); splitSize++) { conf.setInt("io.file.buffer.size", bufferSize); testSplitRecordsForFile(conf, splitSize, inputData.length(), inputFile); } } // multi char delimiter with newline in delimiter and in data inputData = "abc\ndef+\nghi+\njkl\nmno"; inputFile = createInputFile(conf, inputData); conf.set("textinputformat.record.delimiter", "+\n"); for (int bufferSize = 1; bufferSize <= inputData.length(); bufferSize++) { for (int splitSize = 1; splitSize < inputData.length(); splitSize++) { conf.setInt("io.file.buffer.size", bufferSize); testSplitRecordsForFile(conf, splitSize, inputData.length(), inputFile); } } } @Test public void testUncompressedInputContainingCRLF() throws Exception { Configuration conf = new Configuration(); String inputData = "a\r\nb\rc\nd\r\n"; Path inputFile = createInputFile(conf, inputData); for(int bufferSize = 1; bufferSize <= inputData.length(); bufferSize++) { for(int splitSize = 1; splitSize < inputData.length(); splitSize++) { conf.setInt("io.file.buffer.size", bufferSize); testSplitRecordsForFile(conf, splitSize, inputData.length(), inputFile); } } } @Test public void testUncompressedInputCustomDelimiterPosValue() throws Exception { Configuration conf = new Configuration(); conf.setInt("io.file.buffer.size", 10); conf.setInt(org.apache.hadoop.mapreduce.lib.input. LineRecordReader.MAX_LINE_LENGTH, Integer.MAX_VALUE); String inputData = "abcdefghij++kl++mno"; Path inputFile = createInputFile(conf, inputData); String delimiter = "++"; byte[] recordDelimiterBytes = delimiter.getBytes(StandardCharsets.UTF_8); // the first split must contain two records to make sure that it also pulls // in the record from the 2nd split int splitLength = 15; FileSplit split = new FileSplit(inputFile, 0, splitLength, (String[]) null); LineRecordReader reader = new LineRecordReader(conf, split, recordDelimiterBytes); LongWritable key = new LongWritable(); Text value = new Text(); // Get first record: "abcdefghij" assertTrue("Expected record got nothing", reader.next(key, value)); assertEquals("Wrong length for record value", 10, value.getLength()); // Position should be 12 right after "abcdefghij++" assertEquals("Wrong position after record read", 12, reader.getPos()); // Get second record: "kl" assertTrue("Expected record got nothing", reader.next(key, value)); assertEquals("Wrong length for record value", 2, value.getLength()); // Position should be 16 right after "abcdefghij++kl++" assertEquals("Wrong position after record read", 16, reader.getPos()); // Get third record: "mno" assertTrue("Expected record got nothing", reader.next(key, value)); assertEquals("Wrong length for record value", 3, value.getLength()); // Position should be 19 right after "abcdefghij++kl++mno" assertEquals("Wrong position after record read", 19, reader.getPos()); assertFalse(reader.next(key, value)); assertEquals("Wrong position after record read", 19, reader.getPos()); reader.close(); // No record is in the second split because the second split will drop // the first record, which was already reported by the first split. split = new FileSplit(inputFile, splitLength, inputData.length() - splitLength, (String[]) null); reader = new LineRecordReader(conf, split, recordDelimiterBytes); // The position should be 19 right after "abcdefghij++kl++mno" and should // not change assertEquals("Wrong position after record read", 19, reader.getPos()); assertFalse("Unexpected record returned", reader.next(key, value)); assertEquals("Wrong position after record read", 19, reader.getPos()); reader.close(); // multi char delimiter with starting part of the delimiter in the data inputData = "abcd+efgh++ijk++mno"; inputFile = createInputFile(conf, inputData); splitLength = 5; split = new FileSplit(inputFile, 0, splitLength, (String[]) null); reader = new LineRecordReader(conf, split, recordDelimiterBytes); // Get first record: "abcd+efgh" assertTrue("Expected record got nothing", reader.next(key, value)); assertEquals("Wrong position after record read", 11, reader.getPos()); assertEquals("Wrong length for record value", 9, value.getLength()); // should have jumped over the delimiter, no record assertFalse("Unexpected record returned", reader.next(key, value)); assertEquals("Wrong position after record read", 11, reader.getPos()); reader.close(); // next split: check for duplicate or dropped records split = new FileSplit(inputFile, splitLength, inputData.length() - splitLength, (String[]) null); reader = new LineRecordReader(conf, split, recordDelimiterBytes); // Get second record: "ijk" first in this split assertTrue("Expected record got nothing", reader.next(key, value)); assertEquals("Wrong position after record read", 16, reader.getPos()); assertEquals("Wrong length for record value", 3, value.getLength()); // Get third record: "mno" second in this split assertTrue("Expected record got nothing", reader.next(key, value)); assertEquals("Wrong position after record read", 19, reader.getPos()); assertEquals("Wrong length for record value", 3, value.getLength()); // should be at the end of the input assertFalse(reader.next(key, value)); assertEquals("Wrong position after record read", 19, reader.getPos()); reader.close(); inputData = "abcd|efgh|+|ij|kl|+|mno|pqr"; inputFile = createInputFile(conf, inputData); delimiter = "|+|"; recordDelimiterBytes = delimiter.getBytes(StandardCharsets.UTF_8); // walking over the buffer and split sizes checks for proper processing // of the ambiguous bytes of the delimiter for (int bufferSize = 1; bufferSize <= inputData.length(); bufferSize++) { for (int splitSize = 1; splitSize < inputData.length(); splitSize++) { conf.setInt("io.file.buffer.size", bufferSize); split = new FileSplit(inputFile, 0, bufferSize, (String[]) null); reader = new LineRecordReader(conf, split, recordDelimiterBytes); // Get first record: "abcd|efgh" always possible assertTrue("Expected record got nothing", reader.next(key, value)); assertTrue("abcd|efgh".equals(value.toString())); assertEquals("Wrong position after record read", 9, value.getLength()); // Position should be 12 right after "|+|" int recordPos = 12; assertEquals("Wrong position after record read", recordPos, reader.getPos()); // get the next record: "ij|kl" if the split/buffer allows it if (reader.next(key, value)) { // check the record info: "ij|kl" assertTrue("ij|kl".equals(value.toString())); // Position should be 20 right after "|+|" recordPos = 20; assertEquals("Wrong position after record read", recordPos, reader.getPos()); } // get the third record: "mno|pqr" if the split/buffer allows it if (reader.next(key, value)) { // check the record info: "mno|pqr" assertTrue("mno|pqr".equals(value.toString())); // Position should be 27 at the end of the string now recordPos = inputData.length(); assertEquals("Wrong position after record read", recordPos, reader.getPos()); } // no more records can be read we should still be at the last position assertFalse("Unexpected record returned", reader.next(key, value)); assertEquals("Wrong position after record read", recordPos, reader.getPos()); reader.close(); } } } @Test public void testUncompressedInputDefaultDelimiterPosValue() throws Exception { Configuration conf = new Configuration(); String inputData = "1234567890\r\n12\r\n345"; Path inputFile = createInputFile(conf, inputData); conf.setInt("io.file.buffer.size", 10); conf.setInt(org.apache.hadoop.mapreduce.lib.input. LineRecordReader.MAX_LINE_LENGTH, Integer.MAX_VALUE); FileSplit split = new FileSplit(inputFile, 0, 15, (String[])null); LineRecordReader reader = new LineRecordReader(conf, split, null); LongWritable key = new LongWritable(); Text value = new Text(); reader.next(key, value); // Get first record:"1234567890" assertEquals(10, value.getLength()); // Position should be 12 right after "1234567890\r\n" assertEquals(12, reader.getPos()); reader.next(key, value); // Get second record:"12" assertEquals(2, value.getLength()); // Position should be 16 right after "1234567890\r\n12\r\n" assertEquals(16, reader.getPos()); assertFalse(reader.next(key, value)); split = new FileSplit(inputFile, 15, 4, (String[])null); reader = new LineRecordReader(conf, split, null); // The second split dropped the first record "\n" // The position should be 16 right after "1234567890\r\n12\r\n" assertEquals(16, reader.getPos()); reader.next(key, value); // Get third record:"345" assertEquals(3, value.getLength()); // Position should be 19 right after "1234567890\r\n12\r\n345" assertEquals(19, reader.getPos()); assertFalse(reader.next(key, value)); assertEquals(19, reader.getPos()); inputData = "123456789\r\r\n"; inputFile = createInputFile(conf, inputData); split = new FileSplit(inputFile, 0, 12, (String[])null); reader = new LineRecordReader(conf, split, null); reader.next(key, value); // Get first record:"123456789" assertEquals(9, value.getLength()); // Position should be 10 right after "123456789\r" assertEquals(10, reader.getPos()); reader.next(key, value); // Get second record:"" assertEquals(0, value.getLength()); // Position should be 12 right after "123456789\r\r\n" assertEquals(12, reader.getPos()); assertFalse(reader.next(key, value)); assertEquals(12, reader.getPos()); } @Test public void testBzipWithMultibyteDelimiter() throws IOException { String testFileName = "compressedMultibyteDelimiter.txt.bz2"; // firstSplitLength < (headers + blockMarker) will pass always since no // records will be read (in the test file that is byte 0..9) // firstSplitlength > (compressed file length - one compressed block // size + 1) will also always pass since the second split will be empty // (833 bytes is the last block start in the used data file) int firstSplitLength = 100; URL testFileUrl = getClass().getClassLoader().getResource(testFileName); assertNotNull("Cannot find " + testFileName, testFileUrl); File testFile = new File(testFileUrl.getFile()); long testFileSize = testFile.length(); Path testFilePath = new Path(testFile.getAbsolutePath()); assertTrue("Split size is smaller than header length", firstSplitLength > 9); assertTrue("Split size is larger than compressed file size " + testFilePath, testFileSize > firstSplitLength); Configuration conf = new Configuration(); conf.setInt(org.apache.hadoop.mapreduce.lib.input. LineRecordReader.MAX_LINE_LENGTH, Integer.MAX_VALUE); String delimiter = "<E-LINE>\r\r\n"; conf.set("textinputformat.record.delimiter", delimiter); testSplitRecordsForFile(conf, firstSplitLength, testFileSize, testFilePath); } }
robzor92/hops
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapred/TestLineRecordReader.java
Java
apache-2.0
29,127
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Captcha\Exception; class DomainException extends \DomainException implements ExceptionInterface { }
mowema/verano
vendor/zendframework/zendframework/library/Zend/Captcha/Exception/DomainException.php
PHP
bsd-3-clause
440
<!DOCTYPE html> <!-- Copyright (c) 2012 Intel Corporation. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of works must retain the original copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the original copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this work without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Authors: Liu, Jinfeng <[email protected]> --> <html> <head> <title>CSS3 MultiColumn Test: CSS3Multicolumn_column-count_3_p</title> <link rel="author" title="Intel" href="http://www.intel.com/" /> <link rel="help" href="http://www.w3.org/TR/2011/CR-css3-multicol-20110412/#cc" /> <meta name="assert" content="Check if 'column-count: 3' on test p" /> <script type="text/javascript" src="../resources/testharness.js"></script> <script type="text/javascript" src="../resources/testharnessreport.js"></script> <script type="text/javascript" src="support/support.js"></script> <style> #test{ height: 100px; width: 400px; padding: 5px; border: 5px solid black; margin: 5px; background: #eee; } </style> </head> <body> <div id="log"></div> <p class="test" id="test">m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m</p> <script type="text/javascript"> var div = document.querySelector("#test"); var t = async_test(document.title, {timeout: 500}); t.step(function () { div.style[headProp("column-count")] = "3"; var colcount = GetCurrentStyle("column-count"); assert_equals(colcount, "3", "The p column-count"); }); t.done(); </script> </body> </html>
kaixinjxq/web-testing-service
wts/tests/multicolumn/CSS3Multicolumn_column-count_3_p.html
HTML
bsd-3-clause
2,959
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/image_loader_factory.h" #include "chrome/browser/extensions/image_loader.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "components/browser_context_keyed_service/browser_context_dependency_manager.h" namespace extensions { // static ImageLoader* ImageLoaderFactory::GetForProfile(Profile* profile) { return static_cast<ImageLoader*>( GetInstance()->GetServiceForBrowserContext(profile, true)); } ImageLoaderFactory* ImageLoaderFactory::GetInstance() { return Singleton<ImageLoaderFactory>::get(); } ImageLoaderFactory::ImageLoaderFactory() : BrowserContextKeyedServiceFactory( "ImageLoader", BrowserContextDependencyManager::GetInstance()) { } ImageLoaderFactory::~ImageLoaderFactory() { } BrowserContextKeyedService* ImageLoaderFactory::BuildServiceInstanceFor( content::BrowserContext* profile) const { return new ImageLoader; } bool ImageLoaderFactory::ServiceIsCreatedWithBrowserContext() const { return false; } content::BrowserContext* ImageLoaderFactory::GetBrowserContextToUse( content::BrowserContext* context) const { return chrome::GetBrowserContextRedirectedInIncognito(context); } } // namespace extensions
espadrine/opera
chromium/src/chrome/browser/extensions/image_loader_factory.cc
C++
bsd-3-clause
1,446
YUI.add('yui2-simpleeditor', function(Y) { var YAHOO = Y.YUI2; /* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ (function() { var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Lang = YAHOO.lang; /** * @module editor * @description <p>Creates a rich custom Toolbar Button. Primarily used with the Rich Text Editor's Toolbar</p> * @class ToolbarButtonAdvanced * @namespace YAHOO.widget * @requires yahoo, dom, element, event, container_core, menu, button * * Provides a toolbar button based on the button and menu widgets. * @constructor * @class ToolbarButtonAdvanced * @param {String/HTMLElement} el The element to turn into a button. * @param {Object} attrs Object liternal containing configuration parameters. */ if (YAHOO.widget.Button) { YAHOO.widget.ToolbarButtonAdvanced = YAHOO.widget.Button; /** * @property buttonType * @private * @description Tells if the Button is a Rich Button or a Simple Button */ YAHOO.widget.ToolbarButtonAdvanced.prototype.buttonType = 'rich'; /** * @method checkValue * @param {String} value The value of the option that we want to mark as selected * @description Select an option by value */ YAHOO.widget.ToolbarButtonAdvanced.prototype.checkValue = function(value) { var _menuItems = this.getMenu().getItems(); if (_menuItems.length === 0) { this.getMenu()._onBeforeShow(); _menuItems = this.getMenu().getItems(); } for (var i = 0; i < _menuItems.length; i++) { _menuItems[i].cfg.setProperty('checked', false); if (_menuItems[i].value == value) { _menuItems[i].cfg.setProperty('checked', true); } } }; } else { YAHOO.widget.ToolbarButtonAdvanced = function() {}; } /** * @description <p>Creates a basic custom Toolbar Button. Primarily used with the Rich Text Editor's Toolbar</p><p>Provides a toolbar button based on the button and menu widgets, &lt;select&gt; elements are used in place of menu's.</p> * @class ToolbarButton * @namespace YAHOO.widget * @requires yahoo, dom, element, event * @extends YAHOO.util.Element * * * @constructor * @param {String/HTMLElement} el The element to turn into a button. * @param {Object} attrs Object liternal containing configuration parameters. */ YAHOO.widget.ToolbarButton = function(el, attrs) { YAHOO.log('ToolbarButton Initalizing', 'info', 'ToolbarButton'); YAHOO.log(arguments.length + ' arguments passed to constructor', 'info', 'Toolbar'); if (Lang.isObject(arguments[0]) && !Dom.get(el).nodeType) { attrs = el; } var local_attrs = (attrs || {}); var oConfig = { element: null, attributes: local_attrs }; if (!oConfig.attributes.type) { oConfig.attributes.type = 'push'; } oConfig.element = document.createElement('span'); oConfig.element.setAttribute('unselectable', 'on'); oConfig.element.className = 'yui-button yui-' + oConfig.attributes.type + '-button'; oConfig.element.innerHTML = '<span class="first-child"><a href="#">LABEL</a></span>'; oConfig.element.firstChild.firstChild.tabIndex = '-1'; oConfig.attributes.id = (oConfig.attributes.id || Dom.generateId()); oConfig.element.id = oConfig.attributes.id; YAHOO.widget.ToolbarButton.superclass.constructor.call(this, oConfig.element, oConfig.attributes); }; YAHOO.extend(YAHOO.widget.ToolbarButton, YAHOO.util.Element, { /** * @property buttonType * @private * @description Tells if the Button is a Rich Button or a Simple Button */ buttonType: 'normal', /** * @method _handleMouseOver * @private * @description Adds classes to the button elements on mouseover (hover) */ _handleMouseOver: function() { if (!this.get('disabled')) { this.addClass('yui-button-hover'); this.addClass('yui-' + this.get('type') + '-button-hover'); } }, /** * @method _handleMouseOut * @private * @description Removes classes from the button elements on mouseout (hover) */ _handleMouseOut: function() { this.removeClass('yui-button-hover'); this.removeClass('yui-' + this.get('type') + '-button-hover'); }, /** * @method checkValue * @param {String} value The value of the option that we want to mark as selected * @description Select an option by value */ checkValue: function(value) { if (this.get('type') == 'menu') { var opts = this._button.options; if (opts) { for (var i = 0; i < opts.length; i++) { if (opts[i].value == value) { opts.selectedIndex = i; } } } } }, /** * @method init * @description The ToolbarButton class's initialization method */ init: function(p_oElement, p_oAttributes) { YAHOO.widget.ToolbarButton.superclass.init.call(this, p_oElement, p_oAttributes); this.on('mouseover', this._handleMouseOver, this, true); this.on('mouseout', this._handleMouseOut, this, true); this.on('click', function(ev) { Event.stopEvent(ev); return false; }, this, true); }, /** * @method initAttributes * @description Initializes all of the configuration attributes used to create * the toolbar. * @param {Object} attr Object literal specifying a set of * configuration attributes used to create the toolbar. */ initAttributes: function(attr) { YAHOO.widget.ToolbarButton.superclass.initAttributes.call(this, attr); /** * @attribute value * @description The value of the button * @type String */ this.setAttributeConfig('value', { value: attr.value }); /** * @attribute menu * @description The menu attribute, see YAHOO.widget.Button * @type Object */ this.setAttributeConfig('menu', { value: attr.menu || false }); /** * @attribute type * @description The type of button to create: push, menu, color, select, spin * @type String */ this.setAttributeConfig('type', { value: attr.type, writeOnce: true, method: function(type) { var el, opt; if (!this._button) { this._button = this.get('element').getElementsByTagName('a')[0]; } switch (type) { case 'select': case 'menu': el = document.createElement('select'); el.id = this.get('id'); var menu = this.get('menu'); for (var i = 0; i < menu.length; i++) { opt = document.createElement('option'); opt.innerHTML = menu[i].text; opt.value = menu[i].value; if (menu[i].checked) { opt.selected = true; } el.appendChild(opt); } this._button.parentNode.replaceChild(el, this._button); Event.on(el, 'change', this._handleSelect, this, true); this._button = el; break; } } }); /** * @attribute disabled * @description Set the button into a disabled state * @type String */ this.setAttributeConfig('disabled', { value: attr.disabled || false, method: function(disabled) { if (disabled) { this.addClass('yui-button-disabled'); this.addClass('yui-' + this.get('type') + '-button-disabled'); } else { this.removeClass('yui-button-disabled'); this.removeClass('yui-' + this.get('type') + '-button-disabled'); } if ((this.get('type') == 'menu') || (this.get('type') == 'select')) { this._button.disabled = disabled; } } }); /** * @attribute label * @description The text label for the button * @type String */ this.setAttributeConfig('label', { value: attr.label, method: function(label) { if (!this._button) { this._button = this.get('element').getElementsByTagName('a')[0]; } if (this.get('type') == 'push') { this._button.innerHTML = label; } } }); /** * @attribute title * @description The title of the button * @type String */ this.setAttributeConfig('title', { value: attr.title }); /** * @config container * @description The container that the button is rendered to, handled by Toolbar * @type String */ this.setAttributeConfig('container', { value: null, writeOnce: true, method: function(cont) { this.appendTo(cont); } }); }, /** * @private * @method _handleSelect * @description The event fired when a change event gets fired on a select element * @param {Event} ev The change event. */ _handleSelect: function(ev) { var tar = Event.getTarget(ev); var value = tar.options[tar.selectedIndex].value; this.fireEvent('change', {type: 'change', value: value }); }, /** * @method getMenu * @description A stub function to mimic YAHOO.widget.Button's getMenu method */ getMenu: function() { return this.get('menu'); }, /** * @method destroy * @description Destroy the button */ destroy: function() { Event.purgeElement(this.get('element'), true); this.get('element').parentNode.removeChild(this.get('element')); //Brutal Object Destroy for (var i in this) { if (Lang.hasOwnProperty(this, i)) { this[i] = null; } } }, /** * @method fireEvent * @description Overridden fireEvent method to prevent DOM events from firing if the button is disabled. */ fireEvent: function(p_sType, p_aArgs) { // Disabled buttons should not respond to DOM events if (this.DOM_EVENTS[p_sType] && this.get('disabled')) { Event.stopEvent(p_aArgs); return; } YAHOO.widget.ToolbarButton.superclass.fireEvent.call(this, p_sType, p_aArgs); }, /** * @method toString * @description Returns a string representing the toolbar. * @return {String} */ toString: function() { return 'ToolbarButton (' + this.get('id') + ')'; } }); })(); /** * @module editor * @description <p>Creates a rich Toolbar widget based on Button. Primarily used with the Rich Text Editor</p> * @namespace YAHOO.widget * @requires yahoo, dom, element, event, toolbarbutton * @optional container_core, dragdrop */ (function() { var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Lang = YAHOO.lang; var getButton = function(id) { var button = id; if (Lang.isString(id)) { button = this.getButtonById(id); } if (Lang.isNumber(id)) { button = this.getButtonByIndex(id); } if ((!(button instanceof YAHOO.widget.ToolbarButton)) && (!(button instanceof YAHOO.widget.ToolbarButtonAdvanced))) { button = this.getButtonByValue(id); } if ((button instanceof YAHOO.widget.ToolbarButton) || (button instanceof YAHOO.widget.ToolbarButtonAdvanced)) { return button; } return false; }; /** * Provides a rich toolbar widget based on the button and menu widgets * @constructor * @class Toolbar * @extends YAHOO.util.Element * @param {String/HTMLElement} el The element to turn into a toolbar. * @param {Object} attrs Object liternal containing configuration parameters. */ YAHOO.widget.Toolbar = function(el, attrs) { YAHOO.log('Toolbar Initalizing', 'info', 'Toolbar'); YAHOO.log(arguments.length + ' arguments passed to constructor', 'info', 'Toolbar'); if (Lang.isObject(arguments[0]) && !Dom.get(el).nodeType) { attrs = el; } var local_attrs = {}; if (attrs) { Lang.augmentObject(local_attrs, attrs); //Break the config reference } var oConfig = { element: null, attributes: local_attrs }; if (Lang.isString(el) && Dom.get(el)) { oConfig.element = Dom.get(el); } else if (Lang.isObject(el) && Dom.get(el) && Dom.get(el).nodeType) { oConfig.element = Dom.get(el); } if (!oConfig.element) { YAHOO.log('No element defined, creating toolbar container', 'warn', 'Toolbar'); oConfig.element = document.createElement('DIV'); oConfig.element.id = Dom.generateId(); if (local_attrs.container && Dom.get(local_attrs.container)) { YAHOO.log('Container found in config appending to it (' + Dom.get(local_attrs.container).id + ')', 'info', 'Toolbar'); Dom.get(local_attrs.container).appendChild(oConfig.element); } } if (!oConfig.element.id) { oConfig.element.id = ((Lang.isString(el)) ? el : Dom.generateId()); YAHOO.log('No element ID defined for toolbar container, creating..', 'warn', 'Toolbar'); } YAHOO.log('Initing toolbar with id: ' + oConfig.element.id, 'info', 'Toolbar'); var fs = document.createElement('fieldset'); var lg = document.createElement('legend'); lg.innerHTML = 'Toolbar'; fs.appendChild(lg); var cont = document.createElement('DIV'); oConfig.attributes.cont = cont; Dom.addClass(cont, 'yui-toolbar-subcont'); fs.appendChild(cont); oConfig.element.appendChild(fs); oConfig.element.tabIndex = -1; oConfig.attributes.element = oConfig.element; oConfig.attributes.id = oConfig.element.id; this._configuredButtons = []; YAHOO.widget.Toolbar.superclass.constructor.call(this, oConfig.element, oConfig.attributes); }; YAHOO.extend(YAHOO.widget.Toolbar, YAHOO.util.Element, { /** * @protected * @property _configuredButtons * @type Array */ _configuredButtons: null, /** * @method _addMenuClasses * @private * @description This method is called from Menu's renderEvent to add a few more classes to the menu items * @param {String} ev The event that fired. * @param {Array} na Array of event information. * @param {Object} o Button config object. */ _addMenuClasses: function(ev, na, o) { Dom.addClass(this.element, 'yui-toolbar-' + o.get('value') + '-menu'); if (Dom.hasClass(o._button.parentNode.parentNode, 'yui-toolbar-select')) { Dom.addClass(this.element, 'yui-toolbar-select-menu'); } var items = this.getItems(); for (var i = 0; i < items.length; i++) { Dom.addClass(items[i].element, 'yui-toolbar-' + o.get('value') + '-' + ((items[i].value) ? items[i].value.replace(/ /g, '-').toLowerCase() : items[i]._oText.nodeValue.replace(/ /g, '-').toLowerCase())); Dom.addClass(items[i].element, 'yui-toolbar-' + o.get('value') + '-' + ((items[i].value) ? items[i].value.replace(/ /g, '-') : items[i]._oText.nodeValue.replace(/ /g, '-'))); } }, /** * @property buttonType * @description The default button to use * @type Object */ buttonType: YAHOO.widget.ToolbarButton, /** * @property dd * @description The DragDrop instance associated with the Toolbar * @type Object */ dd: null, /** * @property _colorData * @description Object reference containing colors hex and text values. * @type Object */ _colorData: { /* {{{ _colorData */ '#111111': 'Obsidian', '#2D2D2D': 'Dark Gray', '#434343': 'Shale', '#5B5B5B': 'Flint', '#737373': 'Gray', '#8B8B8B': 'Concrete', '#A2A2A2': 'Gray', '#B9B9B9': 'Titanium', '#000000': 'Black', '#D0D0D0': 'Light Gray', '#E6E6E6': 'Silver', '#FFFFFF': 'White', '#BFBF00': 'Pumpkin', '#FFFF00': 'Yellow', '#FFFF40': 'Banana', '#FFFF80': 'Pale Yellow', '#FFFFBF': 'Butter', '#525330': 'Raw Siena', '#898A49': 'Mildew', '#AEA945': 'Olive', '#7F7F00': 'Paprika', '#C3BE71': 'Earth', '#E0DCAA': 'Khaki', '#FCFAE1': 'Cream', '#60BF00': 'Cactus', '#80FF00': 'Chartreuse', '#A0FF40': 'Green', '#C0FF80': 'Pale Lime', '#DFFFBF': 'Light Mint', '#3B5738': 'Green', '#668F5A': 'Lime Gray', '#7F9757': 'Yellow', '#407F00': 'Clover', '#8A9B55': 'Pistachio', '#B7C296': 'Light Jade', '#E6EBD5': 'Breakwater', '#00BF00': 'Spring Frost', '#00FF80': 'Pastel Green', '#40FFA0': 'Light Emerald', '#80FFC0': 'Sea Foam', '#BFFFDF': 'Sea Mist', '#033D21': 'Dark Forrest', '#438059': 'Moss', '#7FA37C': 'Medium Green', '#007F40': 'Pine', '#8DAE94': 'Yellow Gray Green', '#ACC6B5': 'Aqua Lung', '#DDEBE2': 'Sea Vapor', '#00BFBF': 'Fog', '#00FFFF': 'Cyan', '#40FFFF': 'Turquoise Blue', '#80FFFF': 'Light Aqua', '#BFFFFF': 'Pale Cyan', '#033D3D': 'Dark Teal', '#347D7E': 'Gray Turquoise', '#609A9F': 'Green Blue', '#007F7F': 'Seaweed', '#96BDC4': 'Green Gray', '#B5D1D7': 'Soapstone', '#E2F1F4': 'Light Turquoise', '#0060BF': 'Summer Sky', '#0080FF': 'Sky Blue', '#40A0FF': 'Electric Blue', '#80C0FF': 'Light Azure', '#BFDFFF': 'Ice Blue', '#1B2C48': 'Navy', '#385376': 'Biscay', '#57708F': 'Dusty Blue', '#00407F': 'Sea Blue', '#7792AC': 'Sky Blue Gray', '#A8BED1': 'Morning Sky', '#DEEBF6': 'Vapor', '#0000BF': 'Deep Blue', '#0000FF': 'Blue', '#4040FF': 'Cerulean Blue', '#8080FF': 'Evening Blue', '#BFBFFF': 'Light Blue', '#212143': 'Deep Indigo', '#373E68': 'Sea Blue', '#444F75': 'Night Blue', '#00007F': 'Indigo Blue', '#585E82': 'Dockside', '#8687A4': 'Blue Gray', '#D2D1E1': 'Light Blue Gray', '#6000BF': 'Neon Violet', '#8000FF': 'Blue Violet', '#A040FF': 'Violet Purple', '#C080FF': 'Violet Dusk', '#DFBFFF': 'Pale Lavender', '#302449': 'Cool Shale', '#54466F': 'Dark Indigo', '#655A7F': 'Dark Violet', '#40007F': 'Violet', '#726284': 'Smoky Violet', '#9E8FA9': 'Slate Gray', '#DCD1DF': 'Violet White', '#BF00BF': 'Royal Violet', '#FF00FF': 'Fuchsia', '#FF40FF': 'Magenta', '#FF80FF': 'Orchid', '#FFBFFF': 'Pale Magenta', '#4A234A': 'Dark Purple', '#794A72': 'Medium Purple', '#936386': 'Cool Granite', '#7F007F': 'Purple', '#9D7292': 'Purple Moon', '#C0A0B6': 'Pale Purple', '#ECDAE5': 'Pink Cloud', '#BF005F': 'Hot Pink', '#FF007F': 'Deep Pink', '#FF409F': 'Grape', '#FF80BF': 'Electric Pink', '#FFBFDF': 'Pink', '#451528': 'Purple Red', '#823857': 'Purple Dino', '#A94A76': 'Purple Gray', '#7F003F': 'Rose', '#BC6F95': 'Antique Mauve', '#D8A5BB': 'Cool Marble', '#F7DDE9': 'Pink Granite', '#C00000': 'Apple', '#FF0000': 'Fire Truck', '#FF4040': 'Pale Red', '#FF8080': 'Salmon', '#FFC0C0': 'Warm Pink', '#441415': 'Sepia', '#82393C': 'Rust', '#AA4D4E': 'Brick', '#800000': 'Brick Red', '#BC6E6E': 'Mauve', '#D8A3A4': 'Shrimp Pink', '#F8DDDD': 'Shell Pink', '#BF5F00': 'Dark Orange', '#FF7F00': 'Orange', '#FF9F40': 'Grapefruit', '#FFBF80': 'Canteloupe', '#FFDFBF': 'Wax', '#482C1B': 'Dark Brick', '#855A40': 'Dirt', '#B27C51': 'Tan', '#7F3F00': 'Nutmeg', '#C49B71': 'Mustard', '#E1C4A8': 'Pale Tan', '#FDEEE0': 'Marble' /* }}} */ }, /** * @property _colorPicker * @description The HTML Element containing the colorPicker * @type HTMLElement */ _colorPicker: null, /** * @property STR_COLLAPSE * @description String for Toolbar Collapse Button * @type String */ STR_COLLAPSE: 'Collapse Toolbar', /** * @property STR_EXPAND * @description String for Toolbar Collapse Button - Expand * @type String */ STR_EXPAND: 'Expand Toolbar', /** * @property STR_SPIN_LABEL * @description String for spinbutton dynamic label. Note the {VALUE} will be replaced with YAHOO.lang.substitute * @type String */ STR_SPIN_LABEL: 'Spin Button with value {VALUE}. Use Control Shift Up Arrow and Control Shift Down arrow keys to increase or decrease the value.', /** * @property STR_SPIN_UP * @description String for spinbutton up * @type String */ STR_SPIN_UP: 'Click to increase the value of this input', /** * @property STR_SPIN_DOWN * @description String for spinbutton down * @type String */ STR_SPIN_DOWN: 'Click to decrease the value of this input', /** * @property _titlebar * @description Object reference to the titlebar * @type HTMLElement */ _titlebar: null, /** * @property browser * @description Standard browser detection * @type Object */ browser: YAHOO.env.ua, /** * @protected * @property _buttonList * @description Internal property list of current buttons in the toolbar * @type Array */ _buttonList: null, /** * @protected * @property _buttonGroupList * @description Internal property list of current button groups in the toolbar * @type Array */ _buttonGroupList: null, /** * @protected * @property _sep * @description Internal reference to the separator HTML Element for cloning * @type HTMLElement */ _sep: null, /** * @protected * @property _sepCount * @description Internal refernce for counting separators, so we can give them a useful class name for styling * @type Number */ _sepCount: null, /** * @protected * @property draghandle * @type HTMLElement */ _dragHandle: null, /** * @protected * @property _toolbarConfigs * @type Object */ _toolbarConfigs: { renderer: true }, /** * @protected * @property CLASS_CONTAINER * @description Default CSS class to apply to the toolbar container element * @type String */ CLASS_CONTAINER: 'yui-toolbar-container', /** * @protected * @property CLASS_DRAGHANDLE * @description Default CSS class to apply to the toolbar's drag handle element * @type String */ CLASS_DRAGHANDLE: 'yui-toolbar-draghandle', /** * @protected * @property CLASS_SEPARATOR * @description Default CSS class to apply to all separators in the toolbar * @type String */ CLASS_SEPARATOR: 'yui-toolbar-separator', /** * @protected * @property CLASS_DISABLED * @description Default CSS class to apply when the toolbar is disabled * @type String */ CLASS_DISABLED: 'yui-toolbar-disabled', /** * @protected * @property CLASS_PREFIX * @description Default prefix for dynamically created class names * @type String */ CLASS_PREFIX: 'yui-toolbar', /** * @method init * @description The Toolbar class's initialization method */ init: function(p_oElement, p_oAttributes) { YAHOO.widget.Toolbar.superclass.init.call(this, p_oElement, p_oAttributes); }, /** * @method initAttributes * @description Initializes all of the configuration attributes used to create * the toolbar. * @param {Object} attr Object literal specifying a set of * configuration attributes used to create the toolbar. */ initAttributes: function(attr) { YAHOO.widget.Toolbar.superclass.initAttributes.call(this, attr); this.addClass(this.CLASS_CONTAINER); /** * @attribute buttonType * @description The buttonType to use (advanced or basic) * @type String */ this.setAttributeConfig('buttonType', { value: attr.buttonType || 'basic', writeOnce: true, validator: function(type) { switch (type) { case 'advanced': case 'basic': return true; } return false; }, method: function(type) { if (type == 'advanced') { if (YAHOO.widget.Button) { this.buttonType = YAHOO.widget.ToolbarButtonAdvanced; } else { YAHOO.log('Can not find YAHOO.widget.Button', 'error', 'Toolbar'); this.buttonType = YAHOO.widget.ToolbarButton; } } else { this.buttonType = YAHOO.widget.ToolbarButton; } } }); /** * @attribute buttons * @description Object specifying the buttons to include in the toolbar * Example: * <code><pre> * { * { id: 'b3', type: 'button', label: 'Underline', value: 'underline' }, * { type: 'separator' }, * { id: 'b4', type: 'menu', label: 'Align', value: 'align', * menu: [ * { text: "Left", value: 'alignleft' }, * { text: "Center", value: 'aligncenter' }, * { text: "Right", value: 'alignright' } * ] * } * } * </pre></code> * @type Array */ this.setAttributeConfig('buttons', { value: [], writeOnce: true, method: function(data) { var i, button, buttons, len, b; for (i in data) { if (Lang.hasOwnProperty(data, i)) { if (data[i].type == 'separator') { this.addSeparator(); } else if (data[i].group !== undefined) { buttons = this.addButtonGroup(data[i]); if (buttons) { len = buttons.length; for(b = 0; b < len; b++) { if (buttons[b]) { this._configuredButtons[this._configuredButtons.length] = buttons[b].id; } } } } else { button = this.addButton(data[i]); if (button) { this._configuredButtons[this._configuredButtons.length] = button.id; } } } } } }); /** * @attribute disabled * @description Boolean indicating if the toolbar should be disabled. It will also disable the draggable attribute if it is on. * @default false * @type Boolean */ this.setAttributeConfig('disabled', { value: false, method: function(disabled) { if (this.get('disabled') === disabled) { return false; } if (disabled) { this.addClass(this.CLASS_DISABLED); this.set('draggable', false); this.disableAllButtons(); } else { this.removeClass(this.CLASS_DISABLED); if (this._configs.draggable._initialConfig.value) { //Draggable by default, set it back this.set('draggable', true); } this.resetAllButtons(); } } }); /** * @config cont * @description The container for the toolbar. * @type HTMLElement */ this.setAttributeConfig('cont', { value: attr.cont, readOnly: true }); /** * @attribute grouplabels * @description Boolean indicating if the toolbar should show the group label's text string. * @default true * @type Boolean */ this.setAttributeConfig('grouplabels', { value: ((attr.grouplabels === false) ? false : true), method: function(grouplabels) { if (grouplabels) { Dom.removeClass(this.get('cont'), (this.CLASS_PREFIX + '-nogrouplabels')); } else { Dom.addClass(this.get('cont'), (this.CLASS_PREFIX + '-nogrouplabels')); } } }); /** * @attribute titlebar * @description Boolean indicating if the toolbar should have a titlebar. If * passed a string, it will use that as the titlebar text * @default false * @type Boolean or String */ this.setAttributeConfig('titlebar', { value: false, method: function(titlebar) { if (titlebar) { if (this._titlebar && this._titlebar.parentNode) { this._titlebar.parentNode.removeChild(this._titlebar); } this._titlebar = document.createElement('DIV'); this._titlebar.tabIndex = '-1'; Event.on(this._titlebar, 'focus', function() { this._handleFocus(); }, this, true); Dom.addClass(this._titlebar, this.CLASS_PREFIX + '-titlebar'); if (Lang.isString(titlebar)) { var h2 = document.createElement('h2'); h2.tabIndex = '-1'; h2.innerHTML = '<a href="#" tabIndex="0">' + titlebar + '</a>'; this._titlebar.appendChild(h2); Event.on(h2.firstChild, 'click', function(ev) { Event.stopEvent(ev); }); Event.on([h2, h2.firstChild], 'focus', function() { this._handleFocus(); }, this, true); } if (this.get('firstChild')) { this.insertBefore(this._titlebar, this.get('firstChild')); } else { this.appendChild(this._titlebar); } if (this.get('collapse')) { this.set('collapse', true); } } else if (this._titlebar) { if (this._titlebar && this._titlebar.parentNode) { this._titlebar.parentNode.removeChild(this._titlebar); } } } }); /** * @attribute collapse * @description Boolean indicating if the the titlebar should have a collapse button. * The collapse button will not remove the toolbar, it will minimize it to the titlebar * @default false * @type Boolean */ this.setAttributeConfig('collapse', { value: false, method: function(collapse) { if (this._titlebar) { var collapseEl = null; var el = Dom.getElementsByClassName('collapse', 'span', this._titlebar); if (collapse) { if (el.length > 0) { //There is already a collapse button return true; } collapseEl = document.createElement('SPAN'); collapseEl.innerHTML = 'X'; collapseEl.title = this.STR_COLLAPSE; Dom.addClass(collapseEl, 'collapse'); this._titlebar.appendChild(collapseEl); Event.addListener(collapseEl, 'click', function() { if (Dom.hasClass(this.get('cont').parentNode, 'yui-toolbar-container-collapsed')) { this.collapse(false); //Expand Toolbar } else { this.collapse(); //Collapse Toolbar } }, this, true); } else { collapseEl = Dom.getElementsByClassName('collapse', 'span', this._titlebar); if (collapseEl[0]) { if (Dom.hasClass(this.get('cont').parentNode, 'yui-toolbar-container-collapsed')) { //We are closed, reopen the titlebar.. this.collapse(false); //Expand Toolbar } collapseEl[0].parentNode.removeChild(collapseEl[0]); } } } } }); /** * @attribute draggable * @description Boolean indicating if the toolbar should be draggable. * @default false * @type Boolean */ this.setAttributeConfig('draggable', { value: (attr.draggable || false), method: function(draggable) { if (draggable && !this.get('titlebar')) { YAHOO.log('Dragging enabled', 'info', 'Toolbar'); if (!this._dragHandle) { this._dragHandle = document.createElement('SPAN'); this._dragHandle.innerHTML = '|'; this._dragHandle.setAttribute('title', 'Click to drag the toolbar'); this._dragHandle.id = this.get('id') + '_draghandle'; Dom.addClass(this._dragHandle, this.CLASS_DRAGHANDLE); if (this.get('cont').hasChildNodes()) { this.get('cont').insertBefore(this._dragHandle, this.get('cont').firstChild); } else { this.get('cont').appendChild(this._dragHandle); } this.dd = new YAHOO.util.DD(this.get('id')); this.dd.setHandleElId(this._dragHandle.id); } } else { YAHOO.log('Dragging disabled', 'info', 'Toolbar'); if (this._dragHandle) { this._dragHandle.parentNode.removeChild(this._dragHandle); this._dragHandle = null; this.dd = null; } } if (this._titlebar) { if (draggable) { this.dd = new YAHOO.util.DD(this.get('id')); this.dd.setHandleElId(this._titlebar); Dom.addClass(this._titlebar, 'draggable'); } else { Dom.removeClass(this._titlebar, 'draggable'); if (this.dd) { this.dd.unreg(); this.dd = null; } } } }, validator: function(value) { var ret = true; if (!YAHOO.util.DD) { ret = false; } return ret; } }); }, /** * @method addButtonGroup * @description Add a new button group to the toolbar. (uses addButton) * @param {Object} oGroup Object literal reference to the Groups Config (contains an array of button configs as well as the group label) */ addButtonGroup: function(oGroup) { if (!this.get('element')) { this._queue[this._queue.length] = ['addButtonGroup', arguments]; return false; } if (!this.hasClass(this.CLASS_PREFIX + '-grouped')) { this.addClass(this.CLASS_PREFIX + '-grouped'); } var div = document.createElement('DIV'); Dom.addClass(div, this.CLASS_PREFIX + '-group'); Dom.addClass(div, this.CLASS_PREFIX + '-group-' + oGroup.group); if (oGroup.label) { var label = document.createElement('h3'); label.innerHTML = oGroup.label; div.appendChild(label); } if (!this.get('grouplabels')) { Dom.addClass(this.get('cont'), this.CLASS_PREFIX, '-nogrouplabels'); } this.get('cont').appendChild(div); //For accessibility, let's put all of the group buttons in an Unordered List var ul = document.createElement('ul'); div.appendChild(ul); if (!this._buttonGroupList) { this._buttonGroupList = {}; } this._buttonGroupList[oGroup.group] = ul; //An array of the button ids added to this group //This is used for destruction later... var addedButtons = [], button; for (var i = 0; i < oGroup.buttons.length; i++) { var li = document.createElement('li'); li.className = this.CLASS_PREFIX + '-groupitem'; ul.appendChild(li); if ((oGroup.buttons[i].type !== undefined) && oGroup.buttons[i].type == 'separator') { this.addSeparator(li); } else { oGroup.buttons[i].container = li; button = this.addButton(oGroup.buttons[i]); if (button) { addedButtons[addedButtons.length] = button.id; } } } return addedButtons; }, /** * @method addButtonToGroup * @description Add a new button to a toolbar group. Buttons supported: * push, split, menu, select, color, spin * @param {Object} oButton Object literal reference to the Button's Config * @param {String} group The Group identifier passed into the initial config * @param {HTMLElement} after Optional HTML element to insert this button after in the DOM. */ addButtonToGroup: function(oButton, group, after) { var groupCont = this._buttonGroupList[group], li = document.createElement('li'); li.className = this.CLASS_PREFIX + '-groupitem'; oButton.container = li; this.addButton(oButton, after); groupCont.appendChild(li); }, /** * @method addButton * @description Add a new button to the toolbar. Buttons supported: * push, split, menu, select, color, spin * @param {Object} oButton Object literal reference to the Button's Config * @param {HTMLElement} after Optional HTML element to insert this button after in the DOM. */ addButton: function(oButton, after) { if (!this.get('element')) { this._queue[this._queue.length] = ['addButton', arguments]; return false; } if (!this._buttonList) { this._buttonList = []; } YAHOO.log('Adding button of type: ' + oButton.type, 'info', 'Toolbar'); if (!oButton.container) { oButton.container = this.get('cont'); } if ((oButton.type == 'menu') || (oButton.type == 'split') || (oButton.type == 'select')) { if (Lang.isArray(oButton.menu)) { for (var i in oButton.menu) { if (Lang.hasOwnProperty(oButton.menu, i)) { var funcObject = { fn: function(ev, x, oMenu) { if (!oButton.menucmd) { oButton.menucmd = oButton.value; } oButton.value = ((oMenu.value) ? oMenu.value : oMenu._oText.nodeValue); }, scope: this }; oButton.menu[i].onclick = funcObject; } } } } var _oButton = {}, skip = false; for (var o in oButton) { if (Lang.hasOwnProperty(oButton, o)) { if (!this._toolbarConfigs[o]) { _oButton[o] = oButton[o]; } } } if (oButton.type == 'select') { _oButton.type = 'menu'; } if (oButton.type == 'spin') { _oButton.type = 'push'; } if (_oButton.type == 'color') { if (YAHOO.widget.Overlay) { _oButton = this._makeColorButton(_oButton); } else { skip = true; } } if (_oButton.menu) { if ((YAHOO.widget.Overlay) && (oButton.menu instanceof YAHOO.widget.Overlay)) { oButton.menu.showEvent.subscribe(function() { this._button = _oButton; }); } else { for (var m = 0; m < _oButton.menu.length; m++) { if (!_oButton.menu[m].value) { _oButton.menu[m].value = _oButton.menu[m].text; } } if (this.browser.webkit) { _oButton.focusmenu = false; } } } if (skip) { oButton = false; } else { //Add to .get('buttons') manually this._configs.buttons.value[this._configs.buttons.value.length] = oButton; var tmp = new this.buttonType(_oButton); tmp.get('element').tabIndex = '-1'; tmp.get('element').setAttribute('role', 'button'); tmp._selected = true; if (this.get('disabled')) { //Toolbar is disabled, disable the new button too! tmp.set('disabled', true); } if (!oButton.id) { oButton.id = tmp.get('id'); } YAHOO.log('Button created (' + oButton.type + ')', 'info', 'Toolbar'); if (after) { var el = tmp.get('element'); var nextSib = null; if (after.get) { nextSib = after.get('element').nextSibling; } else if (after.nextSibling) { nextSib = after.nextSibling; } if (nextSib) { nextSib.parentNode.insertBefore(el, nextSib); } } tmp.addClass(this.CLASS_PREFIX + '-' + tmp.get('value')); var icon = document.createElement('span'); icon.className = this.CLASS_PREFIX + '-icon'; tmp.get('element').insertBefore(icon, tmp.get('firstChild')); if (tmp._button.tagName.toLowerCase() == 'button') { tmp.get('element').setAttribute('unselectable', 'on'); //Replace the Button HTML Element with an a href if it exists var a = document.createElement('a'); a.innerHTML = tmp._button.innerHTML; a.href = '#'; a.tabIndex = '-1'; Event.on(a, 'click', function(ev) { Event.stopEvent(ev); }); tmp._button.parentNode.replaceChild(a, tmp._button); tmp._button = a; } if (oButton.type == 'select') { if (tmp._button.tagName.toLowerCase() == 'select') { icon.parentNode.removeChild(icon); var iel = tmp._button, parEl = tmp.get('element'); parEl.parentNode.replaceChild(iel, parEl); //The 'element' value is currently the orphaned element //In order for "destroy" to execute we need to get('element') to reference the correct node. //I'm not sure if there is a direct approach to setting this value. tmp._configs.element.value = iel; } else { //Don't put a class on it if it's a real select element tmp.addClass(this.CLASS_PREFIX + '-select'); } } if (oButton.type == 'spin') { if (!Lang.isArray(oButton.range)) { oButton.range = [ 10, 100 ]; } this._makeSpinButton(tmp, oButton); } tmp.get('element').setAttribute('title', tmp.get('label')); if (oButton.type != 'spin') { if ((YAHOO.widget.Overlay) && (_oButton.menu instanceof YAHOO.widget.Overlay)) { var showPicker = function(ev) { var exec = true; if (ev.keyCode && (ev.keyCode == 9)) { exec = false; } if (exec) { if (this._colorPicker) { this._colorPicker._button = oButton.value; } var menuEL = tmp.getMenu().element; if (Dom.getStyle(menuEL, 'visibility') == 'hidden') { tmp.getMenu().show(); } else { tmp.getMenu().hide(); } } YAHOO.util.Event.stopEvent(ev); }; tmp.on('mousedown', showPicker, oButton, this); tmp.on('keydown', showPicker, oButton, this); } else if ((oButton.type != 'menu') && (oButton.type != 'select')) { tmp.on('keypress', this._buttonClick, oButton, this); tmp.on('mousedown', function(ev) { YAHOO.util.Event.stopEvent(ev); this._buttonClick(ev, oButton); }, oButton, this); tmp.on('click', function(ev) { YAHOO.util.Event.stopEvent(ev); }); } else { //Stop the mousedown event so we can trap the selection in the editor! tmp.on('mousedown', function(ev) { //YAHOO.util.Event.stopEvent(ev); }); tmp.on('click', function(ev) { //YAHOO.util.Event.stopEvent(ev); }); tmp.on('change', function(ev) { if (!ev.target) { if (!oButton.menucmd) { oButton.menucmd = oButton.value; } oButton.value = ev.value; this._buttonClick(ev, oButton); } }, this, true); var self = this; //Hijack the mousedown event in the menu and make it fire a button click.. tmp.on('appendTo', function() { var tmp = this; if (tmp.getMenu() && tmp.getMenu().mouseDownEvent) { tmp.getMenu().mouseDownEvent.subscribe(function(ev, args) { YAHOO.log('mouseDownEvent', 'warn', 'Toolbar'); var oMenu = args[1]; YAHOO.util.Event.stopEvent(args[0]); tmp._onMenuClick(args[0], tmp); if (!oButton.menucmd) { oButton.menucmd = oButton.value; } oButton.value = ((oMenu.value) ? oMenu.value : oMenu._oText.nodeValue); self._buttonClick.call(self, args[1], oButton); tmp._hideMenu(); return false; }); tmp.getMenu().clickEvent.subscribe(function(ev, args) { YAHOO.log('clickEvent', 'warn', 'Toolbar'); YAHOO.util.Event.stopEvent(args[0]); }); tmp.getMenu().mouseUpEvent.subscribe(function(ev, args) { YAHOO.log('mouseUpEvent', 'warn', 'Toolbar'); YAHOO.util.Event.stopEvent(args[0]); }); } }); } } else { //Stop the mousedown event so we can trap the selection in the editor! tmp.on('mousedown', function(ev) { YAHOO.util.Event.stopEvent(ev); }); tmp.on('click', function(ev) { YAHOO.util.Event.stopEvent(ev); }); } if (this.browser.ie) { /* //Add a couple of new events for IE tmp.DOM_EVENTS.focusin = true; tmp.DOM_EVENTS.focusout = true; //Stop them so we don't loose focus in the Editor tmp.on('focusin', function(ev) { YAHOO.util.Event.stopEvent(ev); }, oButton, this); tmp.on('focusout', function(ev) { YAHOO.util.Event.stopEvent(ev); }, oButton, this); tmp.on('click', function(ev) { YAHOO.util.Event.stopEvent(ev); }, oButton, this); */ } if (this.browser.webkit) { //This will keep the document from gaining focus and the editor from loosing it.. //Forcefully remove the focus calls in button! tmp.hasFocus = function() { return true; }; } this._buttonList[this._buttonList.length] = tmp; if ((oButton.type == 'menu') || (oButton.type == 'split') || (oButton.type == 'select')) { if (Lang.isArray(oButton.menu)) { YAHOO.log('Button type is (' + oButton.type + '), doing extra renderer work.', 'info', 'Toolbar'); var menu = tmp.getMenu(); if (menu && menu.renderEvent) { menu.renderEvent.subscribe(this._addMenuClasses, tmp); if (oButton.renderer) { menu.renderEvent.subscribe(oButton.renderer, tmp); } } } } } return oButton; }, /** * @method addSeparator * @description Add a new button separator to the toolbar. * @param {HTMLElement} cont Optional HTML element to insert this button into. * @param {HTMLElement} after Optional HTML element to insert this button after in the DOM. */ addSeparator: function(cont, after) { if (!this.get('element')) { this._queue[this._queue.length] = ['addSeparator', arguments]; return false; } var sepCont = ((cont) ? cont : this.get('cont')); if (!this.get('element')) { this._queue[this._queue.length] = ['addSeparator', arguments]; return false; } if (this._sepCount === null) { this._sepCount = 0; } if (!this._sep) { YAHOO.log('Separator does not yet exist, creating', 'info', 'Toolbar'); this._sep = document.createElement('SPAN'); Dom.addClass(this._sep, this.CLASS_SEPARATOR); this._sep.innerHTML = '|'; } YAHOO.log('Separator does exist, cloning', 'info', 'Toolbar'); var _sep = this._sep.cloneNode(true); this._sepCount++; Dom.addClass(_sep, this.CLASS_SEPARATOR + '-' + this._sepCount); if (after) { var nextSib = null; if (after.get) { nextSib = after.get('element').nextSibling; } else if (after.nextSibling) { nextSib = after.nextSibling; } else { nextSib = after; } if (nextSib) { if (nextSib == after) { nextSib.parentNode.appendChild(_sep); } else { nextSib.parentNode.insertBefore(_sep, nextSib); } } } else { sepCont.appendChild(_sep); } return _sep; }, /** * @method _createColorPicker * @private * @description Creates the core DOM reference to the color picker menu item. * @param {String} id the id of the toolbar to prefix this DOM container with. */ _createColorPicker: function(id) { if (Dom.get(id + '_colors')) { Dom.get(id + '_colors').parentNode.removeChild(Dom.get(id + '_colors')); } var picker = document.createElement('div'); picker.className = 'yui-toolbar-colors'; picker.id = id + '_colors'; picker.style.display = 'none'; Event.on(window, 'load', function() { document.body.appendChild(picker); }, this, true); this._colorPicker = picker; var html = ''; for (var i in this._colorData) { if (Lang.hasOwnProperty(this._colorData, i)) { html += '<a style="background-color: ' + i + '" href="#">' + i.replace('#', '') + '</a>'; } } html += '<span><em>X</em><strong></strong></span>'; window.setTimeout(function() { picker.innerHTML = html; }, 0); Event.on(picker, 'mouseover', function(ev) { var picker = this._colorPicker; var em = picker.getElementsByTagName('em')[0]; var strong = picker.getElementsByTagName('strong')[0]; var tar = Event.getTarget(ev); if (tar.tagName.toLowerCase() == 'a') { em.style.backgroundColor = tar.style.backgroundColor; strong.innerHTML = this._colorData['#' + tar.innerHTML] + '<br>' + tar.innerHTML; } }, this, true); Event.on(picker, 'focus', function(ev) { Event.stopEvent(ev); }); Event.on(picker, 'click', function(ev) { Event.stopEvent(ev); }); Event.on(picker, 'mousedown', function(ev) { Event.stopEvent(ev); var tar = Event.getTarget(ev); if (tar.tagName.toLowerCase() == 'a') { var retVal = this.fireEvent('colorPickerClicked', { type: 'colorPickerClicked', target: this, button: this._colorPicker._button, color: tar.innerHTML, colorName: this._colorData['#' + tar.innerHTML] } ); if (retVal !== false) { var info = { color: tar.innerHTML, colorName: this._colorData['#' + tar.innerHTML], value: this._colorPicker._button }; this.fireEvent('buttonClick', { type: 'buttonClick', target: this.get('element'), button: info }); } this.getButtonByValue(this._colorPicker._button).getMenu().hide(); } }, this, true); }, /** * @method _resetColorPicker * @private * @description Clears the currently selected color or mouseover color in the color picker. */ _resetColorPicker: function() { var em = this._colorPicker.getElementsByTagName('em')[0]; var strong = this._colorPicker.getElementsByTagName('strong')[0]; em.style.backgroundColor = 'transparent'; strong.innerHTML = ''; }, /** * @method _makeColorButton * @private * @description Called to turn a "color" button into a menu button with an Overlay for the menu. * @param {Object} _oButton <a href="YAHOO.widget.ToolbarButton.html">YAHOO.widget.ToolbarButton</a> reference */ _makeColorButton: function(_oButton) { if (!this._colorPicker) { this._createColorPicker(this.get('id')); } _oButton.type = 'color'; _oButton.menu = new YAHOO.widget.Overlay(this.get('id') + '_' + _oButton.value + '_menu', { visible: false, position: 'absolute', iframe: true }); _oButton.menu.setBody(''); _oButton.menu.render(this.get('cont')); Dom.addClass(_oButton.menu.element, 'yui-button-menu'); Dom.addClass(_oButton.menu.element, 'yui-color-button-menu'); _oButton.menu.beforeShowEvent.subscribe(function() { _oButton.menu.cfg.setProperty('zindex', 5); //Re Adjust the overlays zIndex.. not sure why. _oButton.menu.cfg.setProperty('context', [this.getButtonById(_oButton.id).get('element'), 'tl', 'bl']); //Re Adjust the overlay.. not sure why. //Move the DOM reference of the color picker to the Overlay that we are about to show. this._resetColorPicker(); var _p = this._colorPicker; if (_p.parentNode) { _p.parentNode.removeChild(_p); } _oButton.menu.setBody(''); _oButton.menu.appendToBody(_p); this._colorPicker.style.display = 'block'; }, this, true); return _oButton; }, /** * @private * @method _makeSpinButton * @description Create a button similar to an OS Spin button.. It has an up/down arrow combo to scroll through a range of int values. * @param {Object} _button <a href="YAHOO.widget.ToolbarButton.html">YAHOO.widget.ToolbarButton</a> reference * @param {Object} oButton Object literal containing the buttons initial config */ _makeSpinButton: function(_button, oButton) { _button.addClass(this.CLASS_PREFIX + '-spinbutton'); var self = this, _par = _button._button.parentNode.parentNode, //parentNode of Button Element for appending child range = oButton.range, _b1 = document.createElement('a'), _b2 = document.createElement('a'); _b1.href = '#'; _b2.href = '#'; _b1.tabIndex = '-1'; _b2.tabIndex = '-1'; //Setup the up and down arrows _b1.className = 'up'; _b1.title = this.STR_SPIN_UP; _b1.innerHTML = this.STR_SPIN_UP; _b2.className = 'down'; _b2.title = this.STR_SPIN_DOWN; _b2.innerHTML = this.STR_SPIN_DOWN; //Append them to the container _par.appendChild(_b1); _par.appendChild(_b2); var label = YAHOO.lang.substitute(this.STR_SPIN_LABEL, { VALUE: _button.get('label') }); _button.set('title', label); var cleanVal = function(value) { value = ((value < range[0]) ? range[0] : value); value = ((value > range[1]) ? range[1] : value); return value; }; var br = this.browser; var tbar = false; var strLabel = this.STR_SPIN_LABEL; if (this._titlebar && this._titlebar.firstChild) { tbar = this._titlebar.firstChild; } var _intUp = function(ev) { YAHOO.util.Event.stopEvent(ev); if (!_button.get('disabled') && (ev.keyCode != 9)) { var value = parseInt(_button.get('label'), 10); value++; value = cleanVal(value); _button.set('label', ''+value); var label = YAHOO.lang.substitute(strLabel, { VALUE: _button.get('label') }); _button.set('title', label); if (!br.webkit && tbar) { //tbar.focus(); //We do this for accessibility, on the re-focus of the element, a screen reader will re-read the title that was just changed //_button.focus(); } self._buttonClick(ev, oButton); } }; var _intDown = function(ev) { YAHOO.util.Event.stopEvent(ev); if (!_button.get('disabled') && (ev.keyCode != 9)) { var value = parseInt(_button.get('label'), 10); value--; value = cleanVal(value); _button.set('label', ''+value); var label = YAHOO.lang.substitute(strLabel, { VALUE: _button.get('label') }); _button.set('title', label); if (!br.webkit && tbar) { //tbar.focus(); //We do this for accessibility, on the re-focus of the element, a screen reader will re-read the title that was just changed //_button.focus(); } self._buttonClick(ev, oButton); } }; var _intKeyUp = function(ev) { if (ev.keyCode == 38) { _intUp(ev); } else if (ev.keyCode == 40) { _intDown(ev); } else if (ev.keyCode == 107 && ev.shiftKey) { //Plus Key _intUp(ev); } else if (ev.keyCode == 109 && ev.shiftKey) { //Minus Key _intDown(ev); } }; //Handle arrow keys.. _button.on('keydown', _intKeyUp, this, true); //Listen for the click on the up button and act on it //Listen for the click on the down button and act on it Event.on(_b1, 'mousedown',function(ev) { Event.stopEvent(ev); }, this, true); Event.on(_b2, 'mousedown', function(ev) { Event.stopEvent(ev); }, this, true); Event.on(_b1, 'click', _intUp, this, true); Event.on(_b2, 'click', _intDown, this, true); }, /** * @protected * @method _buttonClick * @description Click handler for all buttons in the toolbar. * @param {String} ev The event that was passed in. * @param {Object} info Object literal of information about the button that was clicked. */ _buttonClick: function(ev, info) { var doEvent = true; if (ev && ev.type == 'keypress') { if (ev.keyCode == 9) { doEvent = false; } else if ((ev.keyCode === 13) || (ev.keyCode === 0) || (ev.keyCode === 32)) { } else { doEvent = false; } } if (doEvent) { var fireNextEvent = true, retValue = false; info.isSelected = this.isSelected(info.id); if (info.value) { YAHOO.log('fireEvent::' + info.value + 'Click', 'info', 'Toolbar'); retValue = this.fireEvent(info.value + 'Click', { type: info.value + 'Click', target: this.get('element'), button: info }); if (retValue === false) { fireNextEvent = false; } } if (info.menucmd && fireNextEvent) { YAHOO.log('fireEvent::' + info.menucmd + 'Click', 'info', 'Toolbar'); retValue = this.fireEvent(info.menucmd + 'Click', { type: info.menucmd + 'Click', target: this.get('element'), button: info }); if (retValue === false) { fireNextEvent = false; } } if (fireNextEvent) { YAHOO.log('fireEvent::buttonClick', 'info', 'Toolbar'); this.fireEvent('buttonClick', { type: 'buttonClick', target: this.get('element'), button: info }); } if (info.type == 'select') { var button = this.getButtonById(info.id); if (button.buttonType == 'rich') { var txt = info.value; for (var i = 0; i < info.menu.length; i++) { if (info.menu[i].value == info.value) { txt = info.menu[i].text; break; } } button.set('label', '<span class="yui-toolbar-' + info.menucmd + '-' + (info.value).replace(/ /g, '-').toLowerCase() + '">' + txt + '</span>'); var _items = button.getMenu().getItems(); for (var m = 0; m < _items.length; m++) { if (_items[m].value.toLowerCase() == info.value.toLowerCase()) { _items[m].cfg.setProperty('checked', true); } else { _items[m].cfg.setProperty('checked', false); } } } } if (ev) { Event.stopEvent(ev); } } }, /** * @private * @property _keyNav * @description Flag to determine if the arrow nav listeners have been attached * @type Boolean */ _keyNav: null, /** * @private * @property _navCounter * @description Internal counter for walking the buttons in the toolbar with the arrow keys * @type Number */ _navCounter: null, /** * @private * @method _navigateButtons * @description Handles the navigation/focus of toolbar buttons with the Arrow Keys * @param {Event} ev The Key Event */ _navigateButtons: function(ev) { switch (ev.keyCode) { case 37: case 39: if (ev.keyCode == 37) { this._navCounter--; } else { this._navCounter++; } if (this._navCounter > (this._buttonList.length - 1)) { this._navCounter = 0; } if (this._navCounter < 0) { this._navCounter = (this._buttonList.length - 1); } if (this._buttonList[this._navCounter]) { var el = this._buttonList[this._navCounter].get('element'); if (this.browser.ie) { el = this._buttonList[this._navCounter].get('element').getElementsByTagName('a')[0]; } if (this._buttonList[this._navCounter].get('disabled')) { this._navigateButtons(ev); } else { el.focus(); } } break; } }, /** * @private * @method _handleFocus * @description Sets up the listeners for the arrow key navigation */ _handleFocus: function() { if (!this._keyNav) { var ev = 'keypress'; if (this.browser.ie) { ev = 'keydown'; } Event.on(this.get('element'), ev, this._navigateButtons, this, true); this._keyNav = true; this._navCounter = -1; } }, /** * @method getButtonById * @description Gets a button instance from the toolbar by is Dom id. * @param {String} id The Dom id to query for. * @return {<a href="YAHOO.widget.ToolbarButton.html">YAHOO.widget.ToolbarButton</a>} */ getButtonById: function(id) { var len = this._buttonList.length; for (var i = 0; i < len; i++) { if (this._buttonList[i] && this._buttonList[i].get('id') == id) { return this._buttonList[i]; } } return false; }, /** * @method getButtonByValue * @description Gets a button instance or a menuitem instance from the toolbar by it's value. * @param {String} value The button value to query for. * @return {<a href="YAHOO.widget.ToolbarButton.html">YAHOO.widget.ToolbarButton</a> or <a href="YAHOO.widget.MenuItem.html">YAHOO.widget.MenuItem</a>} */ getButtonByValue: function(value) { var _buttons = this.get('buttons'); if (!_buttons) { return false; } var len = _buttons.length; for (var i = 0; i < len; i++) { if (_buttons[i].group !== undefined) { for (var m = 0; m < _buttons[i].buttons.length; m++) { if ((_buttons[i].buttons[m].value == value) || (_buttons[i].buttons[m].menucmd == value)) { return this.getButtonById(_buttons[i].buttons[m].id); } if (_buttons[i].buttons[m].menu) { //Menu Button, loop through the values for (var s = 0; s < _buttons[i].buttons[m].menu.length; s++) { if (_buttons[i].buttons[m].menu[s].value == value) { return this.getButtonById(_buttons[i].buttons[m].id); } } } } } else { if ((_buttons[i].value == value) || (_buttons[i].menucmd == value)) { return this.getButtonById(_buttons[i].id); } if (_buttons[i].menu) { //Menu Button, loop through the values for (var j = 0; j < _buttons[i].menu.length; j++) { if (_buttons[i].menu[j].value == value) { return this.getButtonById(_buttons[i].id); } } } } } return false; }, /** * @method getButtonByIndex * @description Gets a button instance from the toolbar by is index in _buttonList. * @param {Number} index The index of the button in _buttonList. * @return {<a href="YAHOO.widget.ToolbarButton.html">YAHOO.widget.ToolbarButton</a>} */ getButtonByIndex: function(index) { if (this._buttonList[index]) { return this._buttonList[index]; } else { return false; } }, /** * @method getButtons * @description Returns an array of buttons in the current toolbar * @return {Array} */ getButtons: function() { return this._buttonList; }, /** * @method disableButton * @description Disables a button in the toolbar. * @param {String/Number} id Disable a button by it's id, index or value. * @return {Boolean} */ disableButton: function(id) { var button = getButton.call(this, id); if (button) { button.set('disabled', true); } else { return false; } }, /** * @method enableButton * @description Enables a button in the toolbar. * @param {String/Number} id Enable a button by it's id, index or value. * @return {Boolean} */ enableButton: function(id) { if (this.get('disabled')) { return false; } var button = getButton.call(this, id); if (button) { if (button.get('disabled')) { button.set('disabled', false); } } else { return false; } }, /** * @method isSelected * @description Tells if a button is selected or not. * @param {String/Number} id A button by it's id, index or value. * @return {Boolean} */ isSelected: function(id) { var button = getButton.call(this, id); if (button) { return button._selected; } return false; }, /** * @method selectButton * @description Selects a button in the toolbar. * @param {String/Number} id Select a button by it's id, index or value. * @param {String} value If this is a Menu Button, check this item in the menu * @return {Boolean} */ selectButton: function(id, value) { var button = getButton.call(this, id); if (button) { button.addClass('yui-button-selected'); button.addClass('yui-button-' + button.get('value') + '-selected'); button._selected = true; if (value) { if (button.buttonType == 'rich') { var _items = button.getMenu().getItems(); for (var m = 0; m < _items.length; m++) { if (_items[m].value == value) { _items[m].cfg.setProperty('checked', true); button.set('label', '<span class="yui-toolbar-' + button.get('value') + '-' + (value).replace(/ /g, '-').toLowerCase() + '">' + _items[m]._oText.nodeValue + '</span>'); } else { _items[m].cfg.setProperty('checked', false); } } } } } else { return false; } }, /** * @method deselectButton * @description Deselects a button in the toolbar. * @param {String/Number} id Deselect a button by it's id, index or value. * @return {Boolean} */ deselectButton: function(id) { var button = getButton.call(this, id); if (button) { button.removeClass('yui-button-selected'); button.removeClass('yui-button-' + button.get('value') + '-selected'); button.removeClass('yui-button-hover'); button._selected = false; } else { return false; } }, /** * @method deselectAllButtons * @description Deselects all buttons in the toolbar. * @return {Boolean} */ deselectAllButtons: function() { var len = this._buttonList.length; for (var i = 0; i < len; i++) { this.deselectButton(this._buttonList[i]); } }, /** * @method disableAllButtons * @description Disables all buttons in the toolbar. * @return {Boolean} */ disableAllButtons: function() { if (this.get('disabled')) { return false; } var len = this._buttonList.length; for (var i = 0; i < len; i++) { this.disableButton(this._buttonList[i]); } }, /** * @method enableAllButtons * @description Enables all buttons in the toolbar. * @return {Boolean} */ enableAllButtons: function() { if (this.get('disabled')) { return false; } var len = this._buttonList.length; for (var i = 0; i < len; i++) { this.enableButton(this._buttonList[i]); } }, /** * @method resetAllButtons * @description Resets all buttons to their initial state. * @param {Object} _ex Except these buttons * @return {Boolean} */ resetAllButtons: function(_ex) { if (!Lang.isObject(_ex)) { _ex = {}; } if (this.get('disabled') || !this._buttonList) { return false; } var len = this._buttonList.length; for (var i = 0; i < len; i++) { var _button = this._buttonList[i]; if (_button) { var disabled = _button._configs.disabled._initialConfig.value; if (_ex[_button.get('id')]) { this.enableButton(_button); this.selectButton(_button); } else { if (disabled) { this.disableButton(_button); } else { this.enableButton(_button); } this.deselectButton(_button); } } } }, /** * @method destroyButton * @description Destroy a button in the toolbar. * @param {String/Number} id Destroy a button by it's id or index. * @return {Boolean} */ destroyButton: function(id) { var button = getButton.call(this, id); if (button) { var thisID = button.get('id'), new_list = [], i = 0, len = this._buttonList.length; button.destroy(); for (i = 0; i < len; i++) { if (this._buttonList[i].get('id') != thisID) { new_list[new_list.length]= this._buttonList[i]; } } this._buttonList = new_list; } else { return false; } }, /** * @method destroy * @description Destroys the toolbar, all of it's elements and objects. * @return {Boolean} */ destroy: function() { var len = this._configuredButtons.length, j, i, b; for(b = 0; b < len; b++) { this.destroyButton(this._configuredButtons[b]); } this._configuredButtons = null; this.get('element').innerHTML = ''; this.get('element').className = ''; //Brutal Object Destroy for (i in this) { if (Lang.hasOwnProperty(this, i)) { this[i] = null; } } return true; }, /** * @method collapse * @description Programatically collapse the toolbar. * @param {Boolean} collapse True to collapse, false to expand. */ collapse: function(collapse) { var el = Dom.getElementsByClassName('collapse', 'span', this._titlebar); if (collapse === false) { Dom.removeClass(this.get('cont').parentNode, 'yui-toolbar-container-collapsed'); if (el[0]) { Dom.removeClass(el[0], 'collapsed'); el[0].title = this.STR_COLLAPSE; } this.fireEvent('toolbarExpanded', { type: 'toolbarExpanded', target: this }); } else { if (el[0]) { Dom.addClass(el[0], 'collapsed'); el[0].title = this.STR_EXPAND; } Dom.addClass(this.get('cont').parentNode, 'yui-toolbar-container-collapsed'); this.fireEvent('toolbarCollapsed', { type: 'toolbarCollapsed', target: this }); } }, /** * @method toString * @description Returns a string representing the toolbar. * @return {String} */ toString: function() { return 'Toolbar (#' + this.get('element').id + ') with ' + this._buttonList.length + ' buttons.'; } }); /** * @event buttonClick * @param {Object} o The object passed to this handler is the button config used to create the button. * @description Fires when any botton receives a click event. Passes back a single object representing the buttons config object. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event valueClick * @param {Object} o The object passed to this handler is the button config used to create the button. * @description This is a special dynamic event that is created and dispatched based on the value property * of the button config. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * Example: * <code><pre> * buttons : [ * { type: 'button', value: 'test', value: 'testButton' } * ]</pre> * </code> * With the valueClick event you could subscribe to this buttons click event with this: * tbar.in('testButtonClick', function() { alert('test button clicked'); }) * @type YAHOO.util.CustomEvent */ /** * @event toolbarExpanded * @description Fires when the toolbar is expanded via the collapse button. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event toolbarCollapsed * @description Fires when the toolbar is collapsed via the collapse button. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ })(); /** * @module editor * @description <p>The Rich Text Editor is a UI control that replaces a standard HTML textarea; it allows for the rich formatting of text content, including common structural treatments like lists, formatting treatments like bold and italic text, and drag-and-drop inclusion and sizing of images. The Rich Text Editor's toolbar is extensible via a plugin architecture so that advanced implementations can achieve a high degree of customization.</p> * @namespace YAHOO.widget * @requires yahoo, dom, element, event, toolbar * @optional animation, container_core, resize, dragdrop */ (function() { var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Lang = YAHOO.lang, Toolbar = YAHOO.widget.Toolbar; /** * The Rich Text Editor is a UI control that replaces a standard HTML textarea; it allows for the rich formatting of text content, including common structural treatments like lists, formatting treatments like bold and italic text, and drag-and-drop inclusion and sizing of images. The Rich Text Editor's toolbar is extensible via a plugin architecture so that advanced implementations can achieve a high degree of customization. * @constructor * @class SimpleEditor * @extends YAHOO.util.Element * @param {String/HTMLElement} el The textarea element to turn into an editor. * @param {Object} attrs Object liternal containing configuration parameters. */ YAHOO.widget.SimpleEditor = function(el, attrs) { YAHOO.log('SimpleEditor Initalizing', 'info', 'SimpleEditor'); var o = {}; if (Lang.isObject(el) && (!el.tagName) && !attrs) { Lang.augmentObject(o, el); //Break the config reference el = document.createElement('textarea'); this.DOMReady = true; if (o.container) { var c = Dom.get(o.container); c.appendChild(el); } else { document.body.appendChild(el); } } else { if (attrs) { Lang.augmentObject(o, attrs); //Break the config reference } } var oConfig = { element: null, attributes: o }, id = null; if (Lang.isString(el)) { id = el; } else { if (oConfig.attributes.id) { id = oConfig.attributes.id; } else { this.DOMReady = true; id = Dom.generateId(el); } } oConfig.element = el; var element_cont = document.createElement('DIV'); oConfig.attributes.element_cont = new YAHOO.util.Element(element_cont, { id: id + '_container' }); var div = document.createElement('div'); Dom.addClass(div, 'first-child'); oConfig.attributes.element_cont.appendChild(div); if (!oConfig.attributes.toolbar_cont) { oConfig.attributes.toolbar_cont = document.createElement('DIV'); oConfig.attributes.toolbar_cont.id = id + '_toolbar'; div.appendChild(oConfig.attributes.toolbar_cont); } var editorWrapper = document.createElement('DIV'); div.appendChild(editorWrapper); oConfig.attributes.editor_wrapper = editorWrapper; YAHOO.widget.SimpleEditor.superclass.constructor.call(this, oConfig.element, oConfig.attributes); }; YAHOO.extend(YAHOO.widget.SimpleEditor, YAHOO.util.Element, { /** * @private * @property _resizeConfig * @description The default config for the Resize Utility */ _resizeConfig: { handles: ['br'], autoRatio: true, status: true, proxy: true, useShim: true, setSize: false }, /** * @private * @method _setupResize * @description Creates the Resize instance and binds its events. */ _setupResize: function() { if (!YAHOO.util.DD || !YAHOO.util.Resize) { return false; } if (this.get('resize')) { var config = {}; Lang.augmentObject(config, this._resizeConfig); //Break the config reference this.resize = new YAHOO.util.Resize(this.get('element_cont').get('element'), config); this.resize.on('resize', function(args) { var anim = this.get('animate'); this.set('animate', false); this.set('width', args.width + 'px'); var h = args.height, th = (this.toolbar.get('element').clientHeight + 2), dh = 0; if (this.dompath) { dh = (this.dompath.clientHeight + 1); //It has a 1px top border.. } var newH = (h - th - dh); this.set('height', newH + 'px'); this.get('element_cont').setStyle('height', ''); this.set('animate', anim); }, this, true); } }, /** * @property resize * @description A reference to the Resize object * @type YAHOO.util.Resize */ resize: null, /** * @private * @method _setupDD * @description Sets up the DD instance used from the 'drag' config option. */ _setupDD: function() { if (!YAHOO.util.DD) { return false; } if (this.get('drag')) { YAHOO.log('Attaching DD instance to Editor', 'info', 'SimpleEditor'); var d = this.get('drag'), dd = YAHOO.util.DD; if (d === 'proxy') { dd = YAHOO.util.DDProxy; } this.dd = new dd(this.get('element_cont').get('element')); this.toolbar.addClass('draggable'); this.dd.setHandleElId(this.toolbar._titlebar); } }, /** * @property dd * @description A reference to the DragDrop object. * @type YAHOO.util.DD/YAHOO.util.DDProxy */ dd: null, /** * @private * @property _lastCommand * @description A cache of the last execCommand (used for Undo/Redo so they don't mark an undo level) * @type String */ _lastCommand: null, _undoNodeChange: function() {}, _storeUndo: function() {}, /** * @private * @method _checkKey * @description Checks a keyMap entry against a key event * @param {Object} k The _keyMap object * @param {Event} e The Mouse Event * @return {Boolean} */ _checkKey: function(k, e) { var ret = false; if ((e.keyCode === k.key)) { if (k.mods && (k.mods.length > 0)) { var val = 0; for (var i = 0; i < k.mods.length; i++) { if (this.browser.mac) { if (k.mods[i] == 'ctrl') { k.mods[i] = 'meta'; } } if (e[k.mods[i] + 'Key'] === true) { val++; } } if (val === k.mods.length) { ret = true; } } else { ret = true; } } //YAHOO.log('Shortcut Key Check: (' + k.key + ') return: ' + ret, 'info', 'SimpleEditor'); return ret; }, /** * @private * @property _keyMap * @description Named key maps for various actions in the Editor. Example: <code>CLOSE_WINDOW: { key: 87, mods: ['shift', 'ctrl'] }</code>. * This entry shows that when key 87 (W) is found with the modifiers of shift and control, the window will close. You can customize this object to tweak keyboard shortcuts. * @type {Object/Mixed} */ _keyMap: { SELECT_ALL: { key: 65, //A key mods: ['ctrl'] }, CLOSE_WINDOW: { key: 87, //W key mods: ['shift', 'ctrl'] }, FOCUS_TOOLBAR: { key: 27, mods: ['shift'] }, FOCUS_AFTER: { key: 27 }, FONT_SIZE_UP: { key: 38, mods: ['shift', 'ctrl'] }, FONT_SIZE_DOWN: { key: 40, mods: ['shift', 'ctrl'] }, CREATE_LINK: { key: 76, mods: ['shift', 'ctrl'] }, BOLD: { key: 66, mods: ['shift', 'ctrl'] }, ITALIC: { key: 73, mods: ['shift', 'ctrl'] }, UNDERLINE: { key: 85, mods: ['shift', 'ctrl'] }, UNDO: { key: 90, mods: ['ctrl'] }, REDO: { key: 90, mods: ['shift', 'ctrl'] }, JUSTIFY_LEFT: { key: 219, mods: ['shift', 'ctrl'] }, JUSTIFY_CENTER: { key: 220, mods: ['shift', 'ctrl'] }, JUSTIFY_RIGHT: { key: 221, mods: ['shift', 'ctrl'] } }, /** * @private * @method _cleanClassName * @description Makes a useable classname from dynamic data, by dropping it to lowercase and replacing spaces with -'s. * @param {String} str The classname to clean up * @return {String} */ _cleanClassName: function(str) { return str.replace(/ /g, '-').toLowerCase(); }, /** * @property _textarea * @description Flag to determine if we are using a textarea or an HTML Node. * @type Boolean */ _textarea: null, /** * @property _docType * @description The DOCTYPE to use in the editable container. * @type String */ _docType: '<!DOCTYPE HTML PUBLIC "-/'+'/W3C/'+'/DTD HTML 4.01/'+'/EN" "http:/'+'/www.w3.org/TR/html4/strict.dtd">', /** * @property editorDirty * @description This flag will be set when certain things in the Editor happen. It is to be used by the developer to check to see if content has changed. * @type Boolean */ editorDirty: null, /** * @property _defaultCSS * @description The default CSS used in the config for 'css'. This way you can add to the config like this: { css: YAHOO.widget.SimpleEditor.prototype._defaultCSS + 'ADD MYY CSS HERE' } * @type String */ _defaultCSS: 'html { height: 95%; } body { padding: 7px; background-color: #fff; font: 13px/1.22 arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small; } a, a:visited, a:hover { color: blue !important; text-decoration: underline !important; cursor: text !important; } .warning-localfile { border-bottom: 1px dashed red !important; } .yui-busy { cursor: wait !important; } img.selected { border: 2px dotted #808080; } img { cursor: pointer !important; border: none; } body.ptags.webkit div.yui-wk-p { margin: 11px 0; } body.ptags.webkit div.yui-wk-div { margin: 0; }', /** * @property _defaultToolbar * @private * @description Default toolbar config. * @type Object */ _defaultToolbar: null, /** * @property _lastButton * @private * @description The last button pressed, so we don't disable it. * @type Object */ _lastButton: null, /** * @property _baseHREF * @private * @description The base location of the editable page (this page) so that relative paths for image work. * @type String */ _baseHREF: function() { var href = document.location.href; if (href.indexOf('?') !== -1) { //Remove the query string href = href.substring(0, href.indexOf('?')); } href = href.substring(0, href.lastIndexOf('/')) + '/'; return href; }(), /** * @property _lastImage * @private * @description Safari reference for the last image selected (for styling as selected). * @type HTMLElement */ _lastImage: null, /** * @property _blankImageLoaded * @private * @description Don't load the blank image more than once.. * @type Boolean */ _blankImageLoaded: null, /** * @property _fixNodesTimer * @private * @description Holder for the fixNodes timer * @type Date */ _fixNodesTimer: null, /** * @property _nodeChangeTimer * @private * @description Holds a reference to the nodeChange setTimeout call * @type Number */ _nodeChangeTimer: null, /** * @property _nodeChangeDelayTimer * @private * @description Holds a reference to the nodeChangeDelay setTimeout call * @type Number */ _nodeChangeDelayTimer: null, /** * @property _lastNodeChangeEvent * @private * @description Flag to determine the last event that fired a node change * @type Event */ _lastNodeChangeEvent: null, /** * @property _lastNodeChange * @private * @description Flag to determine when the last node change was fired * @type Date */ _lastNodeChange: 0, /** * @property _rendered * @private * @description Flag to determine if editor has been rendered or not * @type Boolean */ _rendered: null, /** * @property DOMReady * @private * @description Flag to determine if DOM is ready or not * @type Boolean */ DOMReady: null, /** * @property _selection * @private * @description Holder for caching iframe selections * @type Object */ _selection: null, /** * @property _mask * @private * @description DOM Element holder for the editor Mask when disabled * @type Object */ _mask: null, /** * @property _showingHiddenElements * @private * @description Status of the hidden elements button * @type Boolean */ _showingHiddenElements: null, /** * @property currentWindow * @description A reference to the currently open EditorWindow * @type Object */ currentWindow: null, /** * @property currentEvent * @description A reference to the current editor event * @type Event */ currentEvent: null, /** * @property operaEvent * @private * @description setTimeout holder for Opera and Image DoubleClick event.. * @type Object */ operaEvent: null, /** * @property currentFont * @description A reference to the last font selected from the Toolbar * @type HTMLElement */ currentFont: null, /** * @property currentElement * @description A reference to the current working element in the editor * @type Array */ currentElement: null, /** * @property dompath * @description A reference to the dompath container for writing the current working dom path to. * @type HTMLElement */ dompath: null, /** * @property beforeElement * @description A reference to the H2 placed before the editor for Accessibilty. * @type HTMLElement */ beforeElement: null, /** * @property afterElement * @description A reference to the H2 placed after the editor for Accessibilty. * @type HTMLElement */ afterElement: null, /** * @property invalidHTML * @description Contains a list of HTML elements that are invalid inside the editor. They will be removed when they are found. If you set the value of a key to "{ keepContents: true }", then the element will be replaced with a yui-non span to be filtered out when cleanHTML is called. The only tag that is ignored here is the span tag as it will force the Editor into a loop and freeze the browser. However.. all of these tags will be removed in the cleanHTML routine. * @type Object */ invalidHTML: { form: true, input: true, button: true, select: true, link: true, html: true, body: true, iframe: true, script: true, style: true, textarea: true }, /** * @property toolbar * @description Local property containing the <a href="YAHOO.widget.Toolbar.html">YAHOO.widget.Toolbar</a> instance * @type <a href="YAHOO.widget.Toolbar.html">YAHOO.widget.Toolbar</a> */ toolbar: null, /** * @private * @property _contentTimer * @description setTimeout holder for documentReady check */ _contentTimer: null, /** * @private * @property _contentTimerMax * @description The number of times the loaded content should be checked before giving up. Default: 500 */ _contentTimerMax: 500, /** * @private * @property _contentTimerCounter * @description Counter to check the number of times the body is polled for before giving up * @type Number */ _contentTimerCounter: 0, /** * @private * @property _disabled * @description The Toolbar items that should be disabled if there is no selection present in the editor. * @type Array */ _disabled: [ 'createlink', 'fontname', 'fontsize', 'forecolor', 'backcolor' ], /** * @private * @property _alwaysDisabled * @description The Toolbar items that should ALWAYS be disabled event if there is a selection present in the editor. * @type Object */ _alwaysDisabled: { undo: true, redo: true }, /** * @private * @property _alwaysEnabled * @description The Toolbar items that should ALWAYS be enabled event if there isn't a selection present in the editor. * @type Object */ _alwaysEnabled: { }, /** * @private * @property _semantic * @description The Toolbar commands that we should attempt to make tags out of instead of using styles. * @type Object */ _semantic: { 'bold': true, 'italic' : true, 'underline' : true }, /** * @private * @property _tag2cmd * @description A tag map of HTML tags to convert to the different types of commands so we can select the proper toolbar button. * @type Object */ _tag2cmd: { 'b': 'bold', 'strong': 'bold', 'i': 'italic', 'em': 'italic', 'u': 'underline', 'sup': 'superscript', 'sub': 'subscript', 'img': 'insertimage', 'a' : 'createlink', 'ul' : 'insertunorderedlist', 'ol' : 'insertorderedlist' }, /** * @private _createIframe * @description Creates the DOM and YUI Element for the iFrame editor area. * @param {String} id The string ID to prefix the iframe with * @return {Object} iFrame object */ _createIframe: function() { var ifrmDom = document.createElement('iframe'); ifrmDom.id = this.get('id') + '_editor'; var config = { border: '0', frameBorder: '0', marginWidth: '0', marginHeight: '0', leftMargin: '0', topMargin: '0', allowTransparency: 'true', width: '100%' }; if (this.get('autoHeight')) { config.scrolling = 'no'; } for (var i in config) { if (Lang.hasOwnProperty(config, i)) { ifrmDom.setAttribute(i, config[i]); } } var isrc = 'javascript:;'; if (this.browser.ie) { //isrc = 'about:blank'; //TODO - Check this, I have changed it before.. isrc = 'javascript:false;'; } ifrmDom.setAttribute('src', isrc); var ifrm = new YAHOO.util.Element(ifrmDom); ifrm.setStyle('visibility', 'hidden'); return ifrm; }, /** * @private _isElement * @description Checks to see if an Element reference is a valid one and has a certain tag type * @param {HTMLElement} el The element to check * @param {String} tag The tag that the element needs to be * @return {Boolean} */ _isElement: function(el, tag) { if (el && el.tagName && (el.tagName.toLowerCase() == tag)) { return true; } if (el && el.getAttribute && (el.getAttribute('tag') == tag)) { return true; } return false; }, /** * @private _hasParent * @description Checks to see if an Element reference or one of it's parents is a valid one and has a certain tag type * @param {HTMLElement} el The element to check * @param {String} tag The tag that the element needs to be * @return HTMLElement */ _hasParent: function(el, tag) { if (!el || !el.parentNode) { return false; } while (el.parentNode) { if (this._isElement(el, tag)) { return el; } if (el.parentNode) { el = el.parentNode; } else { return false; } } return false; }, /** * @private * @method _getDoc * @description Get the Document of the IFRAME * @return {Object} */ _getDoc: function() { var value = false; try { if (this.get('iframe').get('element').contentWindow.document) { value = this.get('iframe').get('element').contentWindow.document; return value; } } catch (e) { return false; } }, /** * @private * @method _getWindow * @description Get the Window of the IFRAME * @return {Object} */ _getWindow: function() { return this.get('iframe').get('element').contentWindow; }, /** * @method focus * @description Attempt to set the focus of the iframes window. */ focus: function() { this._getWindow().focus(); }, /** * @private * @depreciated - This should not be used, moved to this.focus(); * @method _focusWindow * @description Attempt to set the focus of the iframes window. */ _focusWindow: function() { YAHOO.log('_focusWindow: depreciated in favor of this.focus()', 'warn', 'Editor'); this.focus(); }, /** * @private * @method _hasSelection * @description Determines if there is a selection in the editor document. * @return {Boolean} */ _hasSelection: function() { var sel = this._getSelection(); var range = this._getRange(); var hasSel = false; if (!sel || !range) { return hasSel; } //Internet Explorer if (this.browser.ie) { if (range.text) { hasSel = true; } if (range.html) { hasSel = true; } } else { if (this.browser.webkit) { if (sel+'' !== '') { hasSel = true; } } else { if (sel && (sel.toString() !== '') && (sel !== undefined)) { hasSel = true; } } } return hasSel; }, /** * @private * @method _getSelection * @description Handles the different selection objects across the A-Grade list. * @return {Object} Selection Object */ _getSelection: function() { var _sel = null; if (this._getDoc() && this._getWindow()) { if (this._getDoc().selection &&! this.browser.opera) { _sel = this._getDoc().selection; } else { _sel = this._getWindow().getSelection(); } //Handle Safari's lack of Selection Object if (this.browser.webkit) { if (_sel.baseNode) { this._selection = {}; this._selection.baseNode = _sel.baseNode; this._selection.baseOffset = _sel.baseOffset; this._selection.extentNode = _sel.extentNode; this._selection.extentOffset = _sel.extentOffset; } else if (this._selection !== null) { _sel = this._getWindow().getSelection(); _sel.setBaseAndExtent( this._selection.baseNode, this._selection.baseOffset, this._selection.extentNode, this._selection.extentOffset); this._selection = null; } } } return _sel; }, /** * @private * @method _selectNode * @description Places the highlight around a given node * @param {HTMLElement} node The node to select */ _selectNode: function(node, collapse) { if (!node) { return false; } var sel = this._getSelection(), range = null; if (this.browser.ie) { try { //IE freaks out here sometimes.. range = this._getDoc().body.createTextRange(); range.moveToElementText(node); range.select(); } catch (e) { YAHOO.log('IE failed to select element: ' + node.tagName, 'warn', 'SimpleEditor'); } } else if (this.browser.webkit) { if (collapse) { sel.setBaseAndExtent(node, 1, node, node.innerText.length); } else { sel.setBaseAndExtent(node, 0, node, node.innerText.length); } } else if (this.browser.opera) { sel = this._getWindow().getSelection(); range = this._getDoc().createRange(); range.selectNode(node); sel.removeAllRanges(); sel.addRange(range); } else { range = this._getDoc().createRange(); range.selectNodeContents(node); sel.removeAllRanges(); sel.addRange(range); } //TODO - Check Performance this.nodeChange(); }, /** * @private * @method _getRange * @description Handles the different range objects across the A-Grade list. * @return {Object} Range Object */ _getRange: function() { var sel = this._getSelection(); if (sel === null) { return null; } if (this.browser.webkit && !sel.getRangeAt) { var _range = this._getDoc().createRange(); try { _range.setStart(sel.anchorNode, sel.anchorOffset); _range.setEnd(sel.focusNode, sel.focusOffset); } catch (e) { _range = this._getWindow().getSelection()+''; } return _range; } if (this.browser.ie) { try { return sel.createRange(); } catch (e2) { return null; } } if (sel.rangeCount > 0) { return sel.getRangeAt(0); } return null; }, /** * @private * @method _setDesignMode * @description Sets the designMode property of the iFrame document's body. * @param {String} state This should be either on or off */ _setDesignMode: function(state) { if (this.get('setDesignMode')) { try { this._getDoc().designMode = ((state.toLowerCase() == 'off') ? 'off' : 'on'); } catch(e) { } } }, /** * @private * @method _toggleDesignMode * @description Toggles the designMode property of the iFrame document on and off. * @return {String} The state that it was set to. */ _toggleDesignMode: function() { YAHOO.log('It is not recommended to use this method and it will be depreciated.', 'warn', 'SimpleEditor'); var _dMode = this._getDoc().designMode, _state = ((_dMode.toLowerCase() == 'on') ? 'off' : 'on'); this._setDesignMode(_state); return _state; }, /** * @private * @property _focused * @description Holder for trapping focus/blur state and prevent double events * @type Boolean */ _focused: null, /** * @private * @method _handleFocus * @description Handles the focus of the iframe. Note, this is window focus event, not an Editor focus event. * @param {Event} e The DOM Event */ _handleFocus: function(e) { if (!this._focused) { //YAHOO.log('Editor Window Focused', 'info', 'SimpleEditor'); this._focused = true; this.fireEvent('editorWindowFocus', { type: 'editorWindowFocus', target: this }); } }, /** * @private * @method _handleBlur * @description Handles the blur of the iframe. Note, this is window blur event, not an Editor blur event. * @param {Event} e The DOM Event */ _handleBlur: function(e) { if (this._focused) { //YAHOO.log('Editor Window Blurred', 'info', 'SimpleEditor'); this._focused = false; this.fireEvent('editorWindowBlur', { type: 'editorWindowBlur', target: this }); } }, /** * @private * @method _initEditorEvents * @description This method sets up the listeners on the Editors document. */ _initEditorEvents: function() { //Setup Listeners on iFrame var doc = this._getDoc(), win = this._getWindow(); Event.on(doc, 'mouseup', this._handleMouseUp, this, true); Event.on(doc, 'mousedown', this._handleMouseDown, this, true); Event.on(doc, 'click', this._handleClick, this, true); Event.on(doc, 'dblclick', this._handleDoubleClick, this, true); Event.on(doc, 'keypress', this._handleKeyPress, this, true); Event.on(doc, 'keyup', this._handleKeyUp, this, true); Event.on(doc, 'keydown', this._handleKeyDown, this, true); /* TODO -- Everyone but Opera works here.. Event.on(doc, 'paste', function() { YAHOO.log('PASTE', 'info', 'SimpleEditor'); }, this, true); */ //Focus and blur.. Event.on(win, 'focus', this._handleFocus, this, true); Event.on(win, 'blur', this._handleBlur, this, true); }, /** * @private * @method _removeEditorEvents * @description This method removes the listeners on the Editors document (for disabling). */ _removeEditorEvents: function() { //Remove Listeners on iFrame var doc = this._getDoc(), win = this._getWindow(); Event.removeListener(doc, 'mouseup', this._handleMouseUp, this, true); Event.removeListener(doc, 'mousedown', this._handleMouseDown, this, true); Event.removeListener(doc, 'click', this._handleClick, this, true); Event.removeListener(doc, 'dblclick', this._handleDoubleClick, this, true); Event.removeListener(doc, 'keypress', this._handleKeyPress, this, true); Event.removeListener(doc, 'keyup', this._handleKeyUp, this, true); Event.removeListener(doc, 'keydown', this._handleKeyDown, this, true); //Focus and blur.. Event.removeListener(win, 'focus', this._handleFocus, this, true); Event.removeListener(win, 'blur', this._handleBlur, this, true); }, _fixWebkitDivs: function() { if (this.browser.webkit) { var divs = this._getDoc().body.getElementsByTagName('div'); Dom.addClass(divs, 'yui-wk-div'); } }, /** * @private * @method _initEditor * @param {Boolean} raw Don't add events. * @description This method is fired from _checkLoaded when the document is ready. It turns on designMode and set's up the listeners. */ _initEditor: function(raw) { if (this._editorInit) { return; } this._editorInit = true; if (this.browser.ie) { this._getDoc().body.style.margin = '0'; } if (!this.get('disabled')) { this._setDesignMode('on'); this._contentTimerCounter = 0; } if (!this._getDoc().body) { YAHOO.log('Body is null, check again', 'error', 'SimpleEditor'); this._contentTimerCounter = 0; this._editorInit = false; this._checkLoaded(); return false; } YAHOO.log('editorLoaded', 'info', 'SimpleEditor'); if (!raw) { this.toolbar.on('buttonClick', this._handleToolbarClick, this, true); } if (!this.get('disabled')) { this._initEditorEvents(); this.toolbar.set('disabled', false); } if (raw) { this.fireEvent('editorContentReloaded', { type: 'editorreloaded', target: this }); } else { this.fireEvent('editorContentLoaded', { type: 'editorLoaded', target: this }); } this._fixWebkitDivs(); if (this.get('dompath')) { YAHOO.log('Delayed DomPath write', 'info', 'SimpleEditor'); var self = this; setTimeout(function() { self._writeDomPath.call(self); self._setupResize.call(self); }, 150); } var br = []; for (var i in this.browser) { if (this.browser[i]) { br.push(i); } } if (this.get('ptags')) { br.push('ptags'); } Dom.addClass(this._getDoc().body, br.join(' ')); this.nodeChange(true); }, /** * @private * @method _checkLoaded * @param {Boolean} raw Don't add events. * @description Called from a setTimeout loop to check if the iframes body.onload event has fired, then it will init the editor. */ _checkLoaded: function(raw) { this._editorInit = false; this._contentTimerCounter++; if (this._contentTimer) { clearTimeout(this._contentTimer); } if (this._contentTimerCounter > this._contentTimerMax) { YAHOO.log('ERROR: Body Did Not load', 'error', 'SimpleEditor'); return false; } var init = false; try { if (this._getDoc() && this._getDoc().body) { if (this.browser.ie) { if (this._getDoc().body.readyState == 'complete') { init = true; } } else { if (this._getDoc().body._rteLoaded === true) { init = true; } } } } catch (e) { init = false; YAHOO.log('checking body (e)' + e, 'error', 'SimpleEditor'); } if (init === true) { //The onload event has fired, clean up after ourselves and fire the _initEditor method YAHOO.log('Firing _initEditor', 'info', 'SimpleEditor'); this._initEditor(raw); } else { var self = this; this._contentTimer = setTimeout(function() { self._checkLoaded.call(self, raw); }, 20); } }, /** * @private * @method _setInitialContent * @param {Boolean} raw Don't add events. * @description This method will open the iframes content document and write the textareas value into it, then start the body.onload checking. */ _setInitialContent: function(raw) { YAHOO.log('Populating editor body with contents of the text area', 'info', 'SimpleEditor'); var value = ((this._textarea) ? this.get('element').value : this.get('element').innerHTML), doc = null; if (value === '') { value = '<br>'; } var html = Lang.substitute(this.get('html'), { TITLE: this.STR_TITLE, CONTENT: this._cleanIncomingHTML(value), CSS: this.get('css'), HIDDEN_CSS: ((this.get('hiddencss')) ? this.get('hiddencss') : '/* No Hidden CSS */'), EXTRA_CSS: ((this.get('extracss')) ? this.get('extracss') : '/* No Extra CSS */') }), check = true; html = html.replace(/RIGHT_BRACKET/gi, '{'); html = html.replace(/LEFT_BRACKET/gi, '}'); if (document.compatMode != 'BackCompat') { YAHOO.log('Adding Doctype to editable area', 'info', 'SimpleEditor'); html = this._docType + "\n" + html; } else { YAHOO.log('DocType skipped because we are in BackCompat Mode.', 'warn', 'SimpleEditor'); } if (this.browser.ie || this.browser.webkit || this.browser.opera || (navigator.userAgent.indexOf('Firefox/1.5') != -1)) { //Firefox 1.5 doesn't like setting designMode on an document created with a data url try { //Adobe AIR Code if (this.browser.air) { doc = this._getDoc().implementation.createHTMLDocument(); var origDoc = this._getDoc(); origDoc.open(); origDoc.close(); doc.open(); doc.write(html); doc.close(); var node = origDoc.importNode(doc.getElementsByTagName("html")[0], true); origDoc.replaceChild(node, origDoc.getElementsByTagName("html")[0]); origDoc.body._rteLoaded = true; } else { doc = this._getDoc(); doc.open(); doc.write(html); doc.close(); } } catch (e) { YAHOO.log('Setting doc failed.. (_setInitialContent)', 'error', 'SimpleEditor'); //Safari will only be here if we are hidden check = false; } } else { //This keeps Firefox 2 from writing the iframe to history preserving the back buttons functionality this.get('iframe').get('element').src = 'data:text/html;charset=utf-8,' + encodeURIComponent(html); } this.get('iframe').setStyle('visibility', ''); if (check) { this._checkLoaded(raw); } }, /** * @private * @method _setMarkupType * @param {String} action The action to take. Possible values are: css, default or semantic * @description This method will turn on/off the useCSS execCommand. */ _setMarkupType: function(action) { switch (this.get('markup')) { case 'css': this._setEditorStyle(true); break; case 'default': this._setEditorStyle(false); break; case 'semantic': case 'xhtml': if (this._semantic[action]) { this._setEditorStyle(false); } else { this._setEditorStyle(true); } break; } }, /** * Set the editor to use CSS instead of HTML * @param {Booleen} stat True/False */ _setEditorStyle: function(stat) { try { this._getDoc().execCommand('useCSS', false, !stat); } catch (ex) { } }, /** * @private * @method _getSelectedElement * @description This method will attempt to locate the element that was last interacted with, either via selection, location or event. * @return {HTMLElement} The currently selected element. */ _getSelectedElement: function() { var doc = this._getDoc(), range = null, sel = null, elm = null, check = true; if (this.browser.ie) { this.currentEvent = this._getWindow().event; //Event utility assumes window.event, so we need to reset it to this._getWindow().event; range = this._getRange(); if (range) { elm = range.item ? range.item(0) : range.parentElement(); if (this._hasSelection()) { //TODO //WTF.. Why can't I get an element reference here?!??! } if (elm === doc.body) { elm = null; } } if ((this.currentEvent !== null) && (this.currentEvent.keyCode === 0)) { elm = Event.getTarget(this.currentEvent); } } else { sel = this._getSelection(); range = this._getRange(); if (!sel || !range) { return null; } //TODO if (!this._hasSelection() && this.browser.webkit3) { //check = false; } if (this.browser.gecko) { //Added in 2.6.0 if (range.startContainer) { if (range.startContainer.nodeType === 3) { elm = range.startContainer.parentNode; } else if (range.startContainer.nodeType === 1) { elm = range.startContainer; } //Added in 2.7.0 if (this.currentEvent) { var tar = Event.getTarget(this.currentEvent); if (!this._isElement(tar, 'html')) { if (elm !== tar) { elm = tar; } } } } } if (check) { if (sel.anchorNode && (sel.anchorNode.nodeType == 3)) { if (sel.anchorNode.parentNode) { //next check parentNode elm = sel.anchorNode.parentNode; } if (sel.anchorNode.nextSibling != sel.focusNode.nextSibling) { elm = sel.anchorNode.nextSibling; } } if (this._isElement(elm, 'br')) { elm = null; } if (!elm) { elm = range.commonAncestorContainer; if (!range.collapsed) { if (range.startContainer == range.endContainer) { if (range.startOffset - range.endOffset < 2) { if (range.startContainer.hasChildNodes()) { elm = range.startContainer.childNodes[range.startOffset]; } } } } } } } if (this.currentEvent !== null) { try { switch (this.currentEvent.type) { case 'click': case 'mousedown': case 'mouseup': if (this.browser.webkit) { elm = Event.getTarget(this.currentEvent); } break; default: //Do nothing break; } } catch (e) { YAHOO.log('Firefox 1.5 errors here: ' + e, 'error', 'SimpleEditor'); } } else if ((this.currentElement && this.currentElement[0]) && (!this.browser.ie)) { //TODO is this still needed? //elm = this.currentElement[0]; } if (this.browser.opera || this.browser.webkit) { if (this.currentEvent && !elm) { elm = YAHOO.util.Event.getTarget(this.currentEvent); } } if (!elm || !elm.tagName) { elm = doc.body; } if (this._isElement(elm, 'html')) { //Safari sometimes gives us the HTML node back.. elm = doc.body; } if (this._isElement(elm, 'body')) { //make sure that body means this body not the parent.. elm = doc.body; } if (elm && !elm.parentNode) { //Not in document elm = doc.body; } if (elm === undefined) { elm = null; } return elm; }, /** * @private * @method _getDomPath * @description This method will attempt to build the DOM path from the currently selected element. * @param HTMLElement el The element to start with, if not provided _getSelectedElement is used * @return {Array} An array of node references that will create the DOM Path. */ _getDomPath: function(el) { if (!el) { el = this._getSelectedElement(); } var domPath = []; while (el !== null) { if (el.ownerDocument != this._getDoc()) { el = null; break; } //Check to see if we get el.nodeName and nodeType if (el.nodeName && el.nodeType && (el.nodeType == 1)) { domPath[domPath.length] = el; } if (this._isElement(el, 'body')) { break; } el = el.parentNode; } if (domPath.length === 0) { if (this._getDoc() && this._getDoc().body) { domPath[0] = this._getDoc().body; } } return domPath.reverse(); }, /** * @private * @method _writeDomPath * @description Write the current DOM path out to the dompath container below the editor. */ _writeDomPath: function() { var path = this._getDomPath(), pathArr = [], classPath = '', pathStr = ''; for (var i = 0; i < path.length; i++) { var tag = path[i].tagName.toLowerCase(); if ((tag == 'ol') && (path[i].type)) { tag += ':' + path[i].type; } if (Dom.hasClass(path[i], 'yui-tag')) { tag = path[i].getAttribute('tag'); } if ((this.get('markup') == 'semantic') || (this.get('markup') == 'xhtml')) { switch (tag) { case 'b': tag = 'strong'; break; case 'i': tag = 'em'; break; } } if (!Dom.hasClass(path[i], 'yui-non')) { if (Dom.hasClass(path[i], 'yui-tag')) { pathStr = tag; } else { classPath = ((path[i].className !== '') ? '.' + path[i].className.replace(/ /g, '.') : ''); if ((classPath.indexOf('yui') != -1) || (classPath.toLowerCase().indexOf('apple-style-span') != -1)) { classPath = ''; } pathStr = tag + ((path[i].id) ? '#' + path[i].id : '') + classPath; } switch (tag) { case 'body': pathStr = 'body'; break; case 'a': if (path[i].getAttribute('href', 2)) { pathStr += ':' + path[i].getAttribute('href', 2).replace('mailto:', '').replace('http:/'+'/', '').replace('https:/'+'/', ''); //May need to add others here ftp } break; case 'img': var h = path[i].height; var w = path[i].width; if (path[i].style.height) { h = parseInt(path[i].style.height, 10); } if (path[i].style.width) { w = parseInt(path[i].style.width, 10); } pathStr += '(' + w + 'x' + h + ')'; break; } if (pathStr.length > 10) { pathStr = '<span title="' + pathStr + '">' + pathStr.substring(0, 10) + '...' + '</span>'; } else { pathStr = '<span title="' + pathStr + '">' + pathStr + '</span>'; } pathArr[pathArr.length] = pathStr; } } var str = pathArr.join(' ' + this.SEP_DOMPATH + ' '); //Prevent flickering if (this.dompath.innerHTML != str) { this.dompath.innerHTML = str; } }, /** * @private * @method _fixNodes * @description Fix href and imgs as well as remove invalid HTML. */ _fixNodes: function() { try { var doc = this._getDoc(), els = []; for (var v in this.invalidHTML) { if (YAHOO.lang.hasOwnProperty(this.invalidHTML, v)) { if (v.toLowerCase() != 'span') { var tags = doc.body.getElementsByTagName(v); if (tags.length) { for (var i = 0; i < tags.length; i++) { els.push(tags[i]); } } } } } for (var h = 0; h < els.length; h++) { if (els[h].parentNode) { if (Lang.isObject(this.invalidHTML[els[h].tagName.toLowerCase()]) && this.invalidHTML[els[h].tagName.toLowerCase()].keepContents) { this._swapEl(els[h], 'span', function(el) { el.className = 'yui-non'; }); } else { els[h].parentNode.removeChild(els[h]); } } } var imgs = this._getDoc().getElementsByTagName('img'); Dom.addClass(imgs, 'yui-img'); } catch(e) {} }, /** * @private * @method _isNonEditable * @param Event ev The Dom event being checked * @description Method is called at the beginning of all event handlers to check if this element or a parent element has the class yui-noedit (this.CLASS_NOEDIT) applied. * If it does, then this method will stop the event and return true. The event handlers will then return false and stop the nodeChange from occuring. This method will also * disable and enable the Editor's toolbar based on the noedit state. * @return Boolean */ _isNonEditable: function(ev) { if (this.get('allowNoEdit')) { var el = Event.getTarget(ev); if (this._isElement(el, 'html')) { el = null; } var path = this._getDomPath(el); for (var i = (path.length - 1); i > -1; i--) { if (Dom.hasClass(path[i], this.CLASS_NOEDIT)) { //if (this.toolbar.get('disabled') === false) { // this.toolbar.set('disabled', true); //} try { this._getDoc().execCommand('enableObjectResizing', false, 'false'); } catch (e) {} this.nodeChange(); Event.stopEvent(ev); YAHOO.log('CLASS_NOEDIT found in DOM Path, stopping event', 'info', 'SimpleEditor'); return true; } } //if (this.toolbar.get('disabled') === true) { //Should only happen once.. //this.toolbar.set('disabled', false); try { this._getDoc().execCommand('enableObjectResizing', false, 'true'); } catch (e2) {} //} } return false; }, /** * @private * @method _setCurrentEvent * @param {Event} ev The event to cache * @description Sets the current event property */ _setCurrentEvent: function(ev) { this.currentEvent = ev; }, /** * @private * @method _handleClick * @param {Event} ev The event we are working on. * @description Handles all click events inside the iFrame document. */ _handleClick: function(ev) { var ret = this.fireEvent('beforeEditorClick', { type: 'beforeEditorClick', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); if (this.currentWindow) { this.closeWindow(); } if (this.currentWindow) { this.closeWindow(); } if (this.browser.webkit) { var tar =Event.getTarget(ev); if (this._isElement(tar, 'a') || this._isElement(tar.parentNode, 'a')) { Event.stopEvent(ev); this.nodeChange(); } } else { this.nodeChange(); } this.fireEvent('editorClick', { type: 'editorClick', target: this, ev: ev }); }, /** * @private * @method _handleMouseUp * @param {Event} ev The event we are working on. * @description Handles all mouseup events inside the iFrame document. */ _handleMouseUp: function(ev) { var ret = this.fireEvent('beforeEditorMouseUp', { type: 'beforeEditorMouseUp', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } //Don't set current event for mouseup. //It get's fired after a menu is closed and gives up a bogus event to work with //this._setCurrentEvent(ev); var self = this; if (this.browser.opera) { /* * @knownissue Opera appears to stop the MouseDown, Click and DoubleClick events on an image inside of a document with designMode on.. * @browser Opera * @description This work around traps the MouseUp event and sets a timer to check if another MouseUp event fires in so many seconds. If another event is fired, they we internally fire the DoubleClick event. */ var sel = Event.getTarget(ev); if (this._isElement(sel, 'img')) { this.nodeChange(); if (this.operaEvent) { clearTimeout(this.operaEvent); this.operaEvent = null; this._handleDoubleClick(ev); } else { this.operaEvent = window.setTimeout(function() { self.operaEvent = false; }, 700); } } } //This will stop Safari from selecting the entire document if you select all the text in the editor if (this.browser.webkit || this.browser.opera) { if (this.browser.webkit) { Event.stopEvent(ev); } } this.nodeChange(); this.fireEvent('editorMouseUp', { type: 'editorMouseUp', target: this, ev: ev }); }, /** * @private * @method _handleMouseDown * @param {Event} ev The event we are working on. * @description Handles all mousedown events inside the iFrame document. */ _handleMouseDown: function(ev) { var ret = this.fireEvent('beforeEditorMouseDown', { type: 'beforeEditorMouseDown', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); var sel = Event.getTarget(ev); if (this.browser.webkit && this._hasSelection()) { var _sel = this._getSelection(); if (!this.browser.webkit3) { _sel.collapse(true); } else { _sel.collapseToStart(); } } if (this.browser.webkit && this._lastImage) { Dom.removeClass(this._lastImage, 'selected'); this._lastImage = null; } if (this._isElement(sel, 'img') || this._isElement(sel, 'a')) { if (this.browser.webkit) { Event.stopEvent(ev); if (this._isElement(sel, 'img')) { Dom.addClass(sel, 'selected'); this._lastImage = sel; } } if (this.currentWindow) { this.closeWindow(); } this.nodeChange(); } this.fireEvent('editorMouseDown', { type: 'editorMouseDown', target: this, ev: ev }); }, /** * @private * @method _handleDoubleClick * @param {Event} ev The event we are working on. * @description Handles all doubleclick events inside the iFrame document. */ _handleDoubleClick: function(ev) { var ret = this.fireEvent('beforeEditorDoubleClick', { type: 'beforeEditorDoubleClick', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); var sel = Event.getTarget(ev); if (this._isElement(sel, 'img')) { this.currentElement[0] = sel; this.toolbar.fireEvent('insertimageClick', { type: 'insertimageClick', target: this.toolbar }); this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this }); } else if (this._hasParent(sel, 'a')) { //Handle elements inside an a this.currentElement[0] = this._hasParent(sel, 'a'); this.toolbar.fireEvent('createlinkClick', { type: 'createlinkClick', target: this.toolbar }); this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this }); } this.nodeChange(); this.fireEvent('editorDoubleClick', { type: 'editorDoubleClick', target: this, ev: ev }); }, /** * @private * @method _handleKeyUp * @param {Event} ev The event we are working on. * @description Handles all keyup events inside the iFrame document. */ _handleKeyUp: function(ev) { var ret = this.fireEvent('beforeEditorKeyUp', { type: 'beforeEditorKeyUp', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } this._storeUndo(); this._setCurrentEvent(ev); switch (ev.keyCode) { case this._keyMap.SELECT_ALL.key: if (this._checkKey(this._keyMap.SELECT_ALL, ev)) { this.nodeChange(); } break; case 32: //Space Bar case 35: //End case 36: //Home case 37: //Left Arrow case 38: //Up Arrow case 39: //Right Arrow case 40: //Down Arrow case 46: //Forward Delete case 8: //Delete case this._keyMap.CLOSE_WINDOW.key: //W key if window is open if ((ev.keyCode == this._keyMap.CLOSE_WINDOW.key) && this.currentWindow) { if (this._checkKey(this._keyMap.CLOSE_WINDOW, ev)) { this.closeWindow(); } } else { if (!this.browser.ie) { if (this._nodeChangeTimer) { clearTimeout(this._nodeChangeTimer); } var self = this; this._nodeChangeTimer = setTimeout(function() { self._nodeChangeTimer = null; self.nodeChange.call(self); }, 100); } else { this.nodeChange(); } this.editorDirty = true; } break; } this.fireEvent('editorKeyUp', { type: 'editorKeyUp', target: this, ev: ev }); }, /** * @private * @method _handleKeyPress * @param {Event} ev The event we are working on. * @description Handles all keypress events inside the iFrame document. */ _handleKeyPress: function(ev) { var ret = this.fireEvent('beforeEditorKeyPress', { type: 'beforeEditorKeyPress', target: this, ev: ev }); if (ret === false) { return false; } if (this.get('allowNoEdit')) { //if (ev && ev.keyCode && ((ev.keyCode == 46) || ev.keyCode == 63272)) { if (ev && ev.keyCode && (ev.keyCode == 63272)) { //Forward delete key YAHOO.log('allowNoEdit is set, forward delete key has been disabled', 'warn', 'SimpleEditor'); Event.stopEvent(ev); } } if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); this._storeUndo(); if (this.browser.opera) { if (ev.keyCode === 13) { var tar = this._getSelectedElement(); if (!this._isElement(tar, 'li')) { this.execCommand('inserthtml', '<br>'); Event.stopEvent(ev); } } } if (this.browser.webkit) { if (!this.browser.webkit3) { if (ev.keyCode && (ev.keyCode == 122) && (ev.metaKey)) { //This is CMD + z (for undo) if (this._hasParent(this._getSelectedElement(), 'li')) { YAHOO.log('We are in an LI and we found CMD + z, stopping the event', 'warn', 'SimpleEditor'); Event.stopEvent(ev); } } } this._listFix(ev); } this._fixListDupIds(); this.fireEvent('editorKeyPress', { type: 'editorKeyPress', target: this, ev: ev }); }, /** * @private * @method _handleKeyDown * @param {Event} ev The event we are working on. * @description Handles all keydown events inside the iFrame document. */ _handleKeyDown: function(ev) { var ret = this.fireEvent('beforeEditorKeyDown', { type: 'beforeEditorKeyDown', target: this, ev: ev }); if (ret === false) { return false; } var tar = null, _range = null; if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); if (this.currentWindow) { this.closeWindow(); } if (this.currentWindow) { this.closeWindow(); } var doExec = false, action = null, value = null, exec = false; //YAHOO.log('keyCode: ' + ev.keyCode, 'info', 'SimpleEditor'); switch (ev.keyCode) { case this._keyMap.FOCUS_TOOLBAR.key: if (this._checkKey(this._keyMap.FOCUS_TOOLBAR, ev)) { var h = this.toolbar.getElementsByTagName('h2')[0]; if (h && h.firstChild) { h.firstChild.focus(); } } else if (this._checkKey(this._keyMap.FOCUS_AFTER, ev)) { //Focus After Element - Esc this.afterElement.focus(); } Event.stopEvent(ev); doExec = false; break; //case 76: //L case this._keyMap.CREATE_LINK.key: //L if (this._hasSelection()) { if (this._checkKey(this._keyMap.CREATE_LINK, ev)) { var makeLink = true; if (this.get('limitCommands')) { if (!this.toolbar.getButtonByValue('createlink')) { YAHOO.log('Toolbar Button for (createlink) was not found, skipping exec.', 'info', 'SimpleEditor'); makeLink = false; } } if (makeLink) { this.execCommand('createlink', ''); this.toolbar.fireEvent('createlinkClick', { type: 'createlinkClick', target: this.toolbar }); this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this }); doExec = false; } } } break; //case 90: //Z case this._keyMap.UNDO.key: case this._keyMap.REDO.key: if (this._checkKey(this._keyMap.REDO, ev)) { action = 'redo'; doExec = true; } else if (this._checkKey(this._keyMap.UNDO, ev)) { action = 'undo'; doExec = true; } break; //case 66: //B case this._keyMap.BOLD.key: if (this._checkKey(this._keyMap.BOLD, ev)) { action = 'bold'; doExec = true; } break; case this._keyMap.FONT_SIZE_UP.key: case this._keyMap.FONT_SIZE_DOWN.key: var uk = false, dk = false; if (this._checkKey(this._keyMap.FONT_SIZE_UP, ev)) { uk = true; } if (this._checkKey(this._keyMap.FONT_SIZE_DOWN, ev)) { dk = true; } if (uk || dk) { var fs_button = this.toolbar.getButtonByValue('fontsize'), label = parseInt(fs_button.get('label'), 10), newValue = (label + 1); if (dk) { newValue = (label - 1); } action = 'fontsize'; value = newValue + 'px'; doExec = true; } break; //case 73: //I case this._keyMap.ITALIC.key: if (this._checkKey(this._keyMap.ITALIC, ev)) { action = 'italic'; doExec = true; } break; //case 85: //U case this._keyMap.UNDERLINE.key: if (this._checkKey(this._keyMap.UNDERLINE, ev)) { action = 'underline'; doExec = true; } break; case 9: if (this.browser.ie) { //Insert a tab in Internet Explorer _range = this._getRange(); tar = this._getSelectedElement(); if (!this._isElement(tar, 'li')) { if (_range) { _range.pasteHTML('&nbsp;&nbsp;&nbsp;&nbsp;'); _range.collapse(false); _range.select(); } Event.stopEvent(ev); } } //Firefox 3 code if (this.browser.gecko > 1.8) { tar = this._getSelectedElement(); if (this._isElement(tar, 'li')) { if (ev.shiftKey) { this._getDoc().execCommand('outdent', null, ''); } else { this._getDoc().execCommand('indent', null, ''); } } else if (!this._hasSelection()) { this.execCommand('inserthtml', '&nbsp;&nbsp;&nbsp;&nbsp;'); } Event.stopEvent(ev); } break; case 13: var p = null, i = 0; if (this.get('ptags') && !ev.shiftKey) { if (this.browser.gecko) { tar = this._getSelectedElement(); if (!this._hasParent(tar, 'li')) { if (this._hasParent(tar, 'p')) { p = this._getDoc().createElement('p'); p.innerHTML = '&nbsp;'; Dom.insertAfter(p, tar); this._selectNode(p.firstChild); } else if (this._isElement(tar, 'body')) { this.execCommand('insertparagraph', null); var ps = this._getDoc().body.getElementsByTagName('p'); for (i = 0; i < ps.length; i++) { if (ps[i].getAttribute('_moz_dirty') !== null) { p = this._getDoc().createElement('p'); p.innerHTML = '&nbsp;'; Dom.insertAfter(p, ps[i]); this._selectNode(p.firstChild); ps[i].removeAttribute('_moz_dirty'); } } } else { YAHOO.log('Something went wrong with paragraphs, please file a bug!!', 'error', 'SimpleEditor'); doExec = true; action = 'insertparagraph'; } Event.stopEvent(ev); } } if (this.browser.webkit) { tar = this._getSelectedElement(); if (!this._hasParent(tar, 'li')) { this.execCommand('insertparagraph', null); var divs = this._getDoc().body.getElementsByTagName('div'); for (i = 0; i < divs.length; i++) { if (!Dom.hasClass(divs[i], 'yui-wk-div')) { Dom.addClass(divs[i], 'yui-wk-p'); } } Event.stopEvent(ev); } } } else { if (this.browser.webkit) { tar = this._getSelectedElement(); if (!this._hasParent(tar, 'li')) { if (this.browser.webkit4) { this.execCommand('insertlinebreak'); } else { this.execCommand('inserthtml', '<var id="yui-br"></var>'); var holder = this._getDoc().getElementById('yui-br'), br = this._getDoc().createElement('br'), caret = this._getDoc().createElement('span'); holder.parentNode.replaceChild(br, holder); caret.className = 'yui-non'; caret.innerHTML = '&nbsp;'; Dom.insertAfter(caret, br); this._selectNode(caret); } Event.stopEvent(ev); } } if (this.browser.ie) { YAHOO.log('Stopping P tags', 'info', 'SimpleEditor'); //Insert a <br> instead of a <p></p> in Internet Explorer _range = this._getRange(); tar = this._getSelectedElement(); if (!this._isElement(tar, 'li')) { if (_range) { _range.pasteHTML('<br>'); _range.collapse(false); _range.select(); } Event.stopEvent(ev); } } } break; } if (this.browser.ie) { this._listFix(ev); } if (doExec && action) { this.execCommand(action, value); Event.stopEvent(ev); this.nodeChange(); } this._storeUndo(); this.fireEvent('editorKeyDown', { type: 'editorKeyDown', target: this, ev: ev }); }, /** * @private * @property _fixListRunning * @type Boolean * @description Keeps more than one _fixListDupIds from running at the same time. */ _fixListRunning: null, /** * @private * @method _fixListDupIds * @description Some browsers will duplicate the id of an LI when created in designMode. * This method will fix the duplicate id issue. However it will only preserve the first element * in the document list with the unique id. */ _fixListDupIds: function() { if (this._fixListRunning) { return false; } if (this._getDoc()) { this._fixListRunning = true; var lis = this._getDoc().body.getElementsByTagName('li'), i = 0, ids = {}; for (i = 0; i < lis.length; i++) { if (lis[i].id) { if (ids[lis[i].id]) { lis[i].id = ''; } ids[lis[i].id] = true; } } this._fixListRunning = false; } }, /** * @private * @method _listFix * @param {Event} ev The event we are working on. * @description Handles the Enter key, Tab Key and Shift + Tab keys for List Items. */ _listFix: function(ev) { //YAHOO.log('Lists Fix (' + ev.keyCode + ')', 'info', 'SimpleEditor'); var testLi = null, par = null, preContent = false, range = null; //Enter Key if (this.browser.webkit) { if (ev.keyCode && (ev.keyCode == 13)) { if (this._hasParent(this._getSelectedElement(), 'li')) { var tar = this._hasParent(this._getSelectedElement(), 'li'); if (tar.previousSibling) { if (tar.firstChild && (tar.firstChild.length == 1)) { this._selectNode(tar); } } } } } //Shift + Tab Key if (ev.keyCode && ((!this.browser.webkit3 && (ev.keyCode == 25)) || ((this.browser.webkit3 || !this.browser.webkit) && ((ev.keyCode == 9) && ev.shiftKey)))) { testLi = this._getSelectedElement(); if (this._hasParent(testLi, 'li')) { testLi = this._hasParent(testLi, 'li'); YAHOO.log('We have a SHIFT tab in an LI, reverse it..', 'info', 'SimpleEditor'); if (this._hasParent(testLi, 'ul') || this._hasParent(testLi, 'ol')) { YAHOO.log('We have a double parent, move up a level', 'info', 'SimpleEditor'); par = this._hasParent(testLi, 'ul'); if (!par) { par = this._hasParent(testLi, 'ol'); } //YAHOO.log(par.previousSibling + ' :: ' + par.previousSibling.innerHTML); if (this._isElement(par.previousSibling, 'li')) { par.removeChild(testLi); par.parentNode.insertBefore(testLi, par.nextSibling); if (this.browser.ie) { range = this._getDoc().body.createTextRange(); range.moveToElementText(testLi); range.collapse(false); range.select(); } if (this.browser.webkit) { this._selectNode(testLi.firstChild); } Event.stopEvent(ev); } } } } //Tab Key if (ev.keyCode && ((ev.keyCode == 9) && (!ev.shiftKey))) { YAHOO.log('List Fix - Tab', 'info', 'SimpleEditor'); var preLi = this._getSelectedElement(); if (this._hasParent(preLi, 'li')) { preContent = this._hasParent(preLi, 'li').innerHTML; } //YAHOO.log('preLI: ' + preLi.tagName + ' :: ' + preLi.innerHTML); if (this.browser.webkit) { this._getDoc().execCommand('inserttext', false, '\t'); } testLi = this._getSelectedElement(); if (this._hasParent(testLi, 'li')) { YAHOO.log('We have a tab in an LI', 'info', 'SimpleEditor'); par = this._hasParent(testLi, 'li'); YAHOO.log('parLI: ' + par.tagName + ' :: ' + par.innerHTML); var newUl = this._getDoc().createElement(par.parentNode.tagName.toLowerCase()); if (this.browser.webkit) { var span = Dom.getElementsByClassName('Apple-tab-span', 'span', par); //Remove the span element that Safari puts in if (span[0]) { par.removeChild(span[0]); par.innerHTML = Lang.trim(par.innerHTML); //Put the HTML from the LI into this new LI if (preContent) { par.innerHTML = '<span class="yui-non">' + preContent + '</span>&nbsp;'; } else { par.innerHTML = '<span class="yui-non">&nbsp;</span>&nbsp;'; } } } else { if (preContent) { par.innerHTML = preContent + '&nbsp;'; } else { par.innerHTML = '&nbsp;'; } } par.parentNode.replaceChild(newUl, par); newUl.appendChild(par); if (this.browser.webkit) { this._getSelection().setBaseAndExtent(par.firstChild, 1, par.firstChild, par.firstChild.innerText.length); if (!this.browser.webkit3) { par.parentNode.parentNode.style.display = 'list-item'; setTimeout(function() { par.parentNode.parentNode.style.display = 'block'; }, 1); } } else if (this.browser.ie) { range = this._getDoc().body.createTextRange(); range.moveToElementText(par); range.collapse(false); range.select(); } else { this._selectNode(par); } Event.stopEvent(ev); } if (this.browser.webkit) { Event.stopEvent(ev); } this.nodeChange(); } }, /** * @method nodeChange * @param {Boolean} force Optional paramenter to skip the threshold counter * @description Handles setting up the toolbar buttons, getting the Dom path, fixing nodes. */ nodeChange: function(force) { var NCself = this; this._storeUndo(); if (this.get('nodeChangeDelay')) { this._nodeChangeDelayTimer = window.setTimeout(function() { NCself._nodeChangeDelayTimer = null; NCself._nodeChange.apply(NCself, arguments); }, 0); } else { this._nodeChange(); } }, /** * @private * @method _nodeChange * @param {Boolean} force Optional paramenter to skip the threshold counter * @description Fired from nodeChange in a setTimeout. */ _nodeChange: function(force) { var threshold = parseInt(this.get('nodeChangeThreshold'), 10), thisNodeChange = Math.round(new Date().getTime() / 1000), self = this; if (force === true) { this._lastNodeChange = 0; } if ((this._lastNodeChange + threshold) < thisNodeChange) { if (this._fixNodesTimer === null) { this._fixNodesTimer = window.setTimeout(function() { self._fixNodes.call(self); self._fixNodesTimer = null; }, 0); } } this._lastNodeChange = thisNodeChange; if (this.currentEvent) { try { this._lastNodeChangeEvent = this.currentEvent.type; } catch (e) {} } var beforeNodeChange = this.fireEvent('beforeNodeChange', { type: 'beforeNodeChange', target: this }); if (beforeNodeChange === false) { return false; } if (this.get('dompath')) { window.setTimeout(function() { self._writeDomPath.call(self); }, 0); } //Check to see if we are disabled before continuing if (!this.get('disabled')) { if (this.STOP_NODE_CHANGE) { //Reset this var for next action this.STOP_NODE_CHANGE = false; return false; } else { var sel = this._getSelection(), range = this._getRange(), el = this._getSelectedElement(), fn_button = this.toolbar.getButtonByValue('fontname'), fs_button = this.toolbar.getButtonByValue('fontsize'), undo_button = this.toolbar.getButtonByValue('undo'), redo_button = this.toolbar.getButtonByValue('redo'); //Handle updating the toolbar with active buttons var _ex = {}; if (this._lastButton) { _ex[this._lastButton.id] = true; //this._lastButton = null; } if (!this._isElement(el, 'body')) { if (fn_button) { _ex[fn_button.get('id')] = true; } if (fs_button) { _ex[fs_button.get('id')] = true; } } if (redo_button) { delete _ex[redo_button.get('id')]; } this.toolbar.resetAllButtons(_ex); //Handle disabled buttons for (var d = 0; d < this._disabled.length; d++) { var _button = this.toolbar.getButtonByValue(this._disabled[d]); if (_button && _button.get) { if (this._lastButton && (_button.get('id') === this._lastButton.id)) { //Skip } else { if (!this._hasSelection() && !this.get('insert')) { switch (this._disabled[d]) { case 'fontname': case 'fontsize': break; default: //No Selection - disable this.toolbar.disableButton(_button); } } else { if (!this._alwaysDisabled[this._disabled[d]]) { this.toolbar.enableButton(_button); } } if (!this._alwaysEnabled[this._disabled[d]]) { this.toolbar.deselectButton(_button); } } } } var path = this._getDomPath(); var tag = null, cmd = null; for (var i = 0; i < path.length; i++) { tag = path[i].tagName.toLowerCase(); if (path[i].getAttribute('tag')) { tag = path[i].getAttribute('tag').toLowerCase(); } cmd = this._tag2cmd[tag]; if (cmd === undefined) { cmd = []; } if (!Lang.isArray(cmd)) { cmd = [cmd]; } //Bold and Italic styles if (path[i].style.fontWeight.toLowerCase() == 'bold') { cmd[cmd.length] = 'bold'; } if (path[i].style.fontStyle.toLowerCase() == 'italic') { cmd[cmd.length] = 'italic'; } if (path[i].style.textDecoration.toLowerCase() == 'underline') { cmd[cmd.length] = 'underline'; } if (path[i].style.textDecoration.toLowerCase() == 'line-through') { cmd[cmd.length] = 'strikethrough'; } if (cmd.length > 0) { for (var j = 0; j < cmd.length; j++) { this.toolbar.selectButton(cmd[j]); this.toolbar.enableButton(cmd[j]); } } //Handle Alignment switch (path[i].style.textAlign.toLowerCase()) { case 'left': case 'right': case 'center': case 'justify': var alignType = path[i].style.textAlign.toLowerCase(); if (path[i].style.textAlign.toLowerCase() == 'justify') { alignType = 'full'; } this.toolbar.selectButton('justify' + alignType); this.toolbar.enableButton('justify' + alignType); break; } } //After for loop //Reset Font Family and Size to the inital configs if (fn_button) { var family = fn_button._configs.label._initialConfig.value; fn_button.set('label', '<span class="yui-toolbar-fontname-' + this._cleanClassName(family) + '">' + family + '</span>'); this._updateMenuChecked('fontname', family); } if (fs_button) { fs_button.set('label', fs_button._configs.label._initialConfig.value); } var hd_button = this.toolbar.getButtonByValue('heading'); if (hd_button) { hd_button.set('label', hd_button._configs.label._initialConfig.value); this._updateMenuChecked('heading', 'none'); } var img_button = this.toolbar.getButtonByValue('insertimage'); if (img_button && this.currentWindow && (this.currentWindow.name == 'insertimage')) { this.toolbar.disableButton(img_button); } if (this._lastButton && this._lastButton.isSelected) { this.toolbar.deselectButton(this._lastButton.id); } this._undoNodeChange(); } } this.fireEvent('afterNodeChange', { type: 'afterNodeChange', target: this }); }, /** * @private * @method _updateMenuChecked * @param {Object} button The command identifier of the button you want to check * @param {String} value The value of the menu item you want to check * @param {<a href="YAHOO.widget.Toolbar.html">YAHOO.widget.Toolbar</a>} The Toolbar instance the button belongs to (defaults to this.toolbar) * @description Gets the menu from a button instance, if the menu is not rendered it will render it. It will then search the menu for the specified value, unchecking all other items and checking the specified on. */ _updateMenuChecked: function(button, value, tbar) { if (!tbar) { tbar = this.toolbar; } var _button = tbar.getButtonByValue(button); _button.checkValue(value); }, /** * @private * @method _handleToolbarClick * @param {Event} ev The event that triggered the button click * @description This is an event handler attached to the Toolbar's buttonClick event. It will fire execCommand with the command identifier from the Toolbar Button. */ _handleToolbarClick: function(ev) { var value = ''; var str = ''; var cmd = ev.button.value; if (ev.button.menucmd) { value = cmd; cmd = ev.button.menucmd; } this._lastButton = ev.button; if (this.STOP_EXEC_COMMAND) { YAHOO.log('execCommand skipped because we found the STOP_EXEC_COMMAND flag set to true', 'warn', 'SimpleEditor'); YAHOO.log('NOEXEC::execCommand::(' + cmd + '), (' + value + ')', 'warn', 'SimpleEditor'); this.STOP_EXEC_COMMAND = false; return false; } else { this.execCommand(cmd, value); if (!this.browser.webkit) { var Fself = this; setTimeout(function() { Fself.focus.call(Fself); }, 5); } } Event.stopEvent(ev); }, /** * @private * @method _setupAfterElement * @description Creates the accessibility h2 header and places it after the iframe in the Dom for navigation. */ _setupAfterElement: function() { if (!this.beforeElement) { this.beforeElement = document.createElement('h2'); this.beforeElement.className = 'yui-editor-skipheader'; this.beforeElement.tabIndex = '-1'; this.beforeElement.innerHTML = this.STR_BEFORE_EDITOR; this.get('element_cont').get('firstChild').insertBefore(this.beforeElement, this.toolbar.get('nextSibling')); } if (!this.afterElement) { this.afterElement = document.createElement('h2'); this.afterElement.className = 'yui-editor-skipheader'; this.afterElement.tabIndex = '-1'; this.afterElement.innerHTML = this.STR_LEAVE_EDITOR; this.get('element_cont').get('firstChild').appendChild(this.afterElement); } }, /** * @private * @method _disableEditor * @param {Boolean} disabled Pass true to disable, false to enable * @description Creates a mask to place over the Editor. */ _disableEditor: function(disabled) { var iframe, par, html, height; if (!this.get('disabled_iframe')) { iframe = this._createIframe(); iframe.set('id', 'disabled_' + this.get('iframe').get('id')); iframe.setStyle('height', '100%'); iframe.setStyle('display', 'none'); iframe.setStyle('visibility', 'visible'); this.set('disabled_iframe', iframe); par = this.get('iframe').get('parentNode'); par.appendChild(iframe.get('element')); } if (!iframe) { iframe = this.get('disabled_iframe'); } if (disabled) { this._orgIframe = this.get('iframe'); if (this.toolbar) { this.toolbar.set('disabled', true); } html = this.getEditorHTML(); height = this.get('iframe').get('offsetHeight'); iframe.setStyle('visibility', ''); iframe.setStyle('position', ''); iframe.setStyle('top', ''); iframe.setStyle('left', ''); this._orgIframe.setStyle('visibility', 'hidden'); this._orgIframe.setStyle('position', 'absolute'); this._orgIframe.setStyle('top', '-99999px'); this._orgIframe.setStyle('left', '-99999px'); this.set('iframe', iframe); this._setInitialContent(true); if (!this._mask) { this._mask = document.createElement('DIV'); Dom.addClass(this._mask, 'yui-editor-masked'); if (this.browser.ie) { this._mask.style.height = height + 'px'; } this.get('iframe').get('parentNode').appendChild(this._mask); } this.on('editorContentReloaded', function() { this._getDoc().body._rteLoaded = false; this.setEditorHTML(html); iframe.setStyle('display', 'block'); this.unsubscribeAll('editorContentReloaded'); }); } else { if (this._mask) { this._mask.parentNode.removeChild(this._mask); this._mask = null; if (this.toolbar) { this.toolbar.set('disabled', false); } iframe.setStyle('visibility', 'hidden'); iframe.setStyle('position', 'absolute'); iframe.setStyle('top', '-99999px'); iframe.setStyle('left', '-99999px'); this._orgIframe.setStyle('visibility', ''); this._orgIframe.setStyle('position', ''); this._orgIframe.setStyle('top', ''); this._orgIframe.setStyle('left', ''); this.set('iframe', this._orgIframe); this.focus(); var self = this; window.setTimeout(function() { self.nodeChange.call(self); }, 100); } } }, /** * @property SEP_DOMPATH * @description The value to place in between the Dom path items * @type String */ SEP_DOMPATH: '<', /** * @property STR_LEAVE_EDITOR * @description The accessibility string for the element after the iFrame * @type String */ STR_LEAVE_EDITOR: 'You have left the Rich Text Editor.', /** * @property STR_BEFORE_EDITOR * @description The accessibility string for the element before the iFrame * @type String */ STR_BEFORE_EDITOR: 'This text field can contain stylized text and graphics. To cycle through all formatting options, use the keyboard shortcut Shift + Escape to place focus on the toolbar and navigate between options with your arrow keys. To exit this text editor use the Escape key and continue tabbing. <h4>Common formatting keyboard shortcuts:</h4><ul><li>Control Shift B sets text to bold</li> <li>Control Shift I sets text to italic</li> <li>Control Shift U underlines text</li> <li>Control Shift L adds an HTML link</li></ul>', /** * @property STR_TITLE * @description The Title of the HTML document that is created in the iFrame * @type String */ STR_TITLE: 'Rich Text Area.', /** * @property STR_IMAGE_HERE * @description The text to place in the URL textbox when using the blankimage. * @type String */ STR_IMAGE_HERE: 'Image URL Here', /** * @property STR_IMAGE_URL * @description The label string for Image URL * @type String */ STR_IMAGE_URL: 'Image URL', /** * @property STR_LINK_URL * @description The label string for the Link URL. * @type String */ STR_LINK_URL: 'Link URL', /** * @protected * @property STOP_EXEC_COMMAND * @description Set to true when you want the default execCommand function to not process anything * @type Boolean */ STOP_EXEC_COMMAND: false, /** * @protected * @property STOP_NODE_CHANGE * @description Set to true when you want the default nodeChange function to not process anything * @type Boolean */ STOP_NODE_CHANGE: false, /** * @protected * @property CLASS_NOEDIT * @description CSS class applied to elements that are not editable. * @type String */ CLASS_NOEDIT: 'yui-noedit', /** * @protected * @property CLASS_CONTAINER * @description Default CSS class to apply to the editors container element * @type String */ CLASS_CONTAINER: 'yui-editor-container', /** * @protected * @property CLASS_EDITABLE * @description Default CSS class to apply to the editors iframe element * @type String */ CLASS_EDITABLE: 'yui-editor-editable', /** * @protected * @property CLASS_EDITABLE_CONT * @description Default CSS class to apply to the editors iframe's parent element * @type String */ CLASS_EDITABLE_CONT: 'yui-editor-editable-container', /** * @protected * @property CLASS_PREFIX * @description Default prefix for dynamically created class names * @type String */ CLASS_PREFIX: 'yui-editor', /** * @property browser * @description Standard browser detection * @type Object */ browser: function() { var br = YAHOO.env.ua; //Check for webkit3 if (br.webkit >= 420) { br.webkit3 = br.webkit; } else { br.webkit3 = 0; } if (br.webkit >= 530) { br.webkit4 = br.webkit; } else { br.webkit4 = 0; } br.mac = false; //Check for Mac if (navigator.userAgent.indexOf('Macintosh') !== -1) { br.mac = true; } return br; }(), /** * @method init * @description The Editor class' initialization method */ init: function(p_oElement, p_oAttributes) { YAHOO.log('init', 'info', 'SimpleEditor'); if (!this._defaultToolbar) { this._defaultToolbar = { collapse: true, titlebar: 'Text Editing Tools', draggable: false, buttons: [ { group: 'fontstyle', label: 'Font Name and Size', buttons: [ { type: 'select', label: 'Arial', value: 'fontname', disabled: true, menu: [ { text: 'Arial', checked: true }, { text: 'Arial Black' }, { text: 'Comic Sans MS' }, { text: 'Courier New' }, { text: 'Lucida Console' }, { text: 'Tahoma' }, { text: 'Times New Roman' }, { text: 'Trebuchet MS' }, { text: 'Verdana' } ] }, { type: 'spin', label: '13', value: 'fontsize', range: [ 9, 75 ], disabled: true } ] }, { type: 'separator' }, { group: 'textstyle', label: 'Font Style', buttons: [ { type: 'push', label: 'Bold CTRL + SHIFT + B', value: 'bold' }, { type: 'push', label: 'Italic CTRL + SHIFT + I', value: 'italic' }, { type: 'push', label: 'Underline CTRL + SHIFT + U', value: 'underline' }, { type: 'push', label: 'Strike Through', value: 'strikethrough' }, { type: 'separator' }, { type: 'color', label: 'Font Color', value: 'forecolor', disabled: true }, { type: 'color', label: 'Background Color', value: 'backcolor', disabled: true } ] }, { type: 'separator' }, { group: 'indentlist', label: 'Lists', buttons: [ { type: 'push', label: 'Create an Unordered List', value: 'insertunorderedlist' }, { type: 'push', label: 'Create an Ordered List', value: 'insertorderedlist' } ] }, { type: 'separator' }, { group: 'insertitem', label: 'Insert Item', buttons: [ { type: 'push', label: 'HTML Link CTRL + SHIFT + L', value: 'createlink', disabled: true }, { type: 'push', label: 'Insert Image', value: 'insertimage' } ] } ] }; } YAHOO.widget.SimpleEditor.superclass.init.call(this, p_oElement, p_oAttributes); YAHOO.widget.EditorInfo._instances[this.get('id')] = this; this.currentElement = []; this.on('contentReady', function() { this.DOMReady = true; this.fireQueue(); }, this, true); }, /** * @method initAttributes * @description Initializes all of the configuration attributes used to create * the editor. * @param {Object} attr Object literal specifying a set of * configuration attributes used to create the editor. */ initAttributes: function(attr) { YAHOO.widget.SimpleEditor.superclass.initAttributes.call(this, attr); var self = this; /** * @config setDesignMode * @description Should the Editor set designMode on the document. Default: true. * @default true * @type Boolean */ this.setAttributeConfig('setDesignMode', { value: ((attr.setDesignMode === false) ? false : true) }); /** * @config nodeChangeDelay * @description Do we wrap the nodeChange method in a timeout for performance. Default: true. * @default true * @type Boolean */ this.setAttributeConfig('nodeChangeDelay', { value: ((attr.nodeChangeDelay === false) ? false : true) }); /** * @config maxUndo * @description The max number of undo levels to store. * @default 30 * @type Number */ this.setAttributeConfig('maxUndo', { writeOnce: true, value: attr.maxUndo || 30 }); /** * @config ptags * @description If true, the editor uses &lt;P&gt; tags instead of &lt;br&gt; tags. (Use Shift + Enter to get a &lt;br&gt;) * @default false * @type Boolean */ this.setAttributeConfig('ptags', { writeOnce: true, value: attr.ptags || false }); /** * @config insert * @description If true, selection is not required for: fontname, fontsize, forecolor, backcolor. * @default false * @type Boolean */ this.setAttributeConfig('insert', { writeOnce: true, value: attr.insert || false, method: function(insert) { if (insert) { var buttons = { fontname: true, fontsize: true, forecolor: true, backcolor: true }; var tmp = this._defaultToolbar.buttons; for (var i = 0; i < tmp.length; i++) { if (tmp[i].buttons) { for (var a = 0; a < tmp[i].buttons.length; a++) { if (tmp[i].buttons[a].value) { if (buttons[tmp[i].buttons[a].value]) { delete tmp[i].buttons[a].disabled; } } } } } } } }); /** * @config container * @description Used when dynamically creating the Editor from Javascript with no default textarea. * We will create one and place it in this container. If no container is passed we will append to document.body. * @default false * @type HTMLElement */ this.setAttributeConfig('container', { writeOnce: true, value: attr.container || false }); /** * @config plainText * @description Process the inital textarea data as if it was plain text. Accounting for spaces, tabs and line feeds. * @default false * @type Boolean */ this.setAttributeConfig('plainText', { writeOnce: true, value: attr.plainText || false }); /** * @private * @config iframe * @description Internal config for holding the iframe element. * @default null * @type HTMLElement */ this.setAttributeConfig('iframe', { value: null }); /** * @private * @config disabled_iframe * @description Internal config for holding the iframe element used when disabling the Editor. * @default null * @type HTMLElement */ this.setAttributeConfig('disabled_iframe', { value: null }); /** * @private * @depreciated - No longer used, should use this.get('element') * @config textarea * @description Internal config for holding the textarea element (replaced with element). * @default null * @type HTMLElement */ this.setAttributeConfig('textarea', { value: null, writeOnce: true }); /** * @config nodeChangeThreshold * @description The number of seconds that need to be in between nodeChange processing * @default 3 * @type Number */ this.setAttributeConfig('nodeChangeThreshold', { value: attr.nodeChangeThreshold || 3, validator: YAHOO.lang.isNumber }); /** * @config allowNoEdit * @description Should the editor check for non-edit fields. It should be noted that this technique is not perfect. If the user does the right things, they will still be able to make changes. * Such as highlighting an element below and above the content and hitting a toolbar button or a shortcut key. * @default false * @type Boolean */ this.setAttributeConfig('allowNoEdit', { value: attr.allowNoEdit || false, validator: YAHOO.lang.isBoolean }); /** * @config limitCommands * @description Should the Editor limit the allowed execCommands to the ones available in the toolbar. If true, then execCommand and keyboard shortcuts will fail if they are not defined in the toolbar. * @default false * @type Boolean */ this.setAttributeConfig('limitCommands', { value: attr.limitCommands || false, validator: YAHOO.lang.isBoolean }); /** * @config element_cont * @description Internal config for the editors container * @default false * @type HTMLElement */ this.setAttributeConfig('element_cont', { value: attr.element_cont }); /** * @private * @config editor_wrapper * @description The outter wrapper for the entire editor. * @default null * @type HTMLElement */ this.setAttributeConfig('editor_wrapper', { value: attr.editor_wrapper || null, writeOnce: true }); /** * @attribute height * @description The height of the editor iframe container, not including the toolbar.. * @default Best guessed size of the textarea, for best results use CSS to style the height of the textarea or pass it in as an argument * @type String */ this.setAttributeConfig('height', { value: attr.height || Dom.getStyle(self.get('element'), 'height'), method: function(height) { if (this._rendered) { //We have been rendered, change the height if (this.get('animate')) { var anim = new YAHOO.util.Anim(this.get('iframe').get('parentNode'), { height: { to: parseInt(height, 10) } }, 0.5); anim.animate(); } else { Dom.setStyle(this.get('iframe').get('parentNode'), 'height', height); } } } }); /** * @config autoHeight * @description Remove the scrollbars from the edit area and resize it to fit the content. It will not go any lower than the current config height. * @default false * @type Boolean || Number */ this.setAttributeConfig('autoHeight', { value: attr.autoHeight || false, method: function(a) { if (a) { if (this.get('iframe')) { this.get('iframe').get('element').setAttribute('scrolling', 'no'); } this.on('afterNodeChange', this._handleAutoHeight, this, true); this.on('editorKeyDown', this._handleAutoHeight, this, true); this.on('editorKeyPress', this._handleAutoHeight, this, true); } else { if (this.get('iframe')) { this.get('iframe').get('element').setAttribute('scrolling', 'auto'); } this.unsubscribe('afterNodeChange', this._handleAutoHeight); this.unsubscribe('editorKeyDown', this._handleAutoHeight); this.unsubscribe('editorKeyPress', this._handleAutoHeight); } } }); /** * @attribute width * @description The width of the editor container. * @default Best guessed size of the textarea, for best results use CSS to style the width of the textarea or pass it in as an argument * @type String */ this.setAttributeConfig('width', { value: attr.width || Dom.getStyle(this.get('element'), 'width'), method: function(width) { if (this._rendered) { //We have been rendered, change the width if (this.get('animate')) { var anim = new YAHOO.util.Anim(this.get('element_cont').get('element'), { width: { to: parseInt(width, 10) } }, 0.5); anim.animate(); } else { this.get('element_cont').setStyle('width', width); } } } }); /** * @attribute blankimage * @description The URL for the image placeholder to put in when inserting an image. * @default The yahooapis.com address for the current release + 'assets/blankimage.png' * @type String */ this.setAttributeConfig('blankimage', { value: attr.blankimage || this._getBlankImage() }); /** * @attribute css * @description The Base CSS used to format the content of the editor * @default <code><pre>html { height: 95%; } body { height: 100%; padding: 7px; background-color: #fff; font:13px/1.22 arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small; } a { color: blue; text-decoration: underline; cursor: pointer; } .warning-localfile { border-bottom: 1px dashed red !important; } .yui-busy { cursor: wait !important; } img.selected { //Safari image selection border: 2px dotted #808080; } img { cursor: pointer !important; border: none; } </pre></code> * @type String */ this.setAttributeConfig('css', { value: attr.css || this._defaultCSS, writeOnce: true }); /** * @attribute html * @description The default HTML to be written to the iframe document before the contents are loaded (Note that the DOCTYPE attr will be added at render item) * @default This HTML requires a few things if you are to override: <p><code>{TITLE}, {CSS}, {HIDDEN_CSS}, {EXTRA_CSS}</code> and <code>{CONTENT}</code> need to be there, they are passed to YAHOO.lang.substitute to be replace with other strings.<p> <p><code>onload="document.body._rteLoaded = true;"</code> : the onload statement must be there or the editor will not finish loading.</p> <code> <pre> &lt;html&gt; &lt;head&gt; &lt;title&gt;{TITLE}&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;style&gt; {CSS} &lt;/style&gt; &lt;style&gt; {HIDDEN_CSS} &lt;/style&gt; &lt;style&gt; {EXTRA_CSS} &lt;/style&gt; &lt;/head&gt; &lt;body onload="document.body._rteLoaded = true;"&gt; {CONTENT} &lt;/body&gt; &lt;/html&gt; </pre> </code> * @type String */ this.setAttributeConfig('html', { value: attr.html || '<html><head><title>{TITLE}</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><base href="' + this._baseHREF + '"><style>{CSS}</style><style>{HIDDEN_CSS}</style><style>{EXTRA_CSS}</style></head><body onload="document.body._rteLoaded = true;">{CONTENT}</body></html>', writeOnce: true }); /** * @attribute extracss * @description Extra user defined css to load after the default SimpleEditor CSS * @default '' * @type String */ this.setAttributeConfig('extracss', { value: attr.extracss || '', writeOnce: true }); /** * @attribute handleSubmit * @description Config handles if the editor will attach itself to the textareas parent form's submit handler. If it is set to true, the editor will attempt to attach a submit listener to the textareas parent form. Then it will trigger the editors save handler and place the new content back into the text area before the form is submitted. * @default false * @type Boolean */ this.setAttributeConfig('handleSubmit', { value: attr.handleSubmit || false, method: function(exec) { if (this.get('element').form) { if (!this._formButtons) { this._formButtons = []; } if (exec) { Event.on(this.get('element').form, 'submit', this._handleFormSubmit, this, true); var i = this.get('element').form.getElementsByTagName('input'); for (var s = 0; s < i.length; s++) { var type = i[s].getAttribute('type'); if (type && (type.toLowerCase() == 'submit')) { Event.on(i[s], 'click', this._handleFormButtonClick, this, true); this._formButtons[this._formButtons.length] = i[s]; } } } else { Event.removeListener(this.get('element').form, 'submit', this._handleFormSubmit); if (this._formButtons) { Event.removeListener(this._formButtons, 'click', this._handleFormButtonClick); } } } } }); /** * @attribute disabled * @description This will toggle the editor's disabled state. When the editor is disabled, designMode is turned off and a mask is placed over the iframe so no interaction can take place. All Toolbar buttons are also disabled so they cannot be used. * @default false * @type Boolean */ this.setAttributeConfig('disabled', { value: false, method: function(disabled) { if (this._rendered) { this._disableEditor(disabled); } } }); /** * @config saveEl * @description When save HTML is called, this element will be updated as well as the source of data. * @default element * @type HTMLElement */ this.setAttributeConfig('saveEl', { value: this.get('element') }); /** * @config toolbar_cont * @description Internal config for the toolbars container * @default false * @type Boolean */ this.setAttributeConfig('toolbar_cont', { value: null, writeOnce: true }); /** * @attribute toolbar * @description The default toolbar config. * @type Object */ this.setAttributeConfig('toolbar', { value: attr.toolbar || this._defaultToolbar, writeOnce: true, method: function(toolbar) { if (!toolbar.buttonType) { toolbar.buttonType = this._defaultToolbar.buttonType; } this._defaultToolbar = toolbar; } }); /** * @attribute animate * @description Should the editor animate window movements * @default false unless Animation is found, then true * @type Boolean */ this.setAttributeConfig('animate', { value: ((attr.animate) ? ((YAHOO.util.Anim) ? true : false) : false), validator: function(value) { var ret = true; if (!YAHOO.util.Anim) { ret = false; } return ret; } }); /** * @config panel * @description A reference to the panel we are using for windows. * @default false * @type Boolean */ this.setAttributeConfig('panel', { value: null, writeOnce: true, validator: function(value) { var ret = true; if (!YAHOO.widget.Overlay) { ret = false; } return ret; } }); /** * @attribute focusAtStart * @description Should we focus the window when the content is ready? * @default false * @type Boolean */ this.setAttributeConfig('focusAtStart', { value: attr.focusAtStart || false, writeOnce: true, method: function(fs) { if (fs) { this.on('editorContentLoaded', function() { var self = this; setTimeout(function() { self.focus.call(self); self.editorDirty = false; }, 400); }, this, true); } } }); /** * @attribute dompath * @description Toggle the display of the current Dom path below the editor * @default false * @type Boolean */ this.setAttributeConfig('dompath', { value: attr.dompath || false, method: function(dompath) { if (dompath && !this.dompath) { this.dompath = document.createElement('DIV'); this.dompath.id = this.get('id') + '_dompath'; Dom.addClass(this.dompath, 'dompath'); this.get('element_cont').get('firstChild').appendChild(this.dompath); if (this.get('iframe')) { this._writeDomPath(); } } else if (!dompath && this.dompath) { this.dompath.parentNode.removeChild(this.dompath); this.dompath = null; } } }); /** * @attribute markup * @description Should we try to adjust the markup for the following types: semantic, css, default or xhtml * @default "semantic" * @type String */ this.setAttributeConfig('markup', { value: attr.markup || 'semantic', validator: function(markup) { switch (markup.toLowerCase()) { case 'semantic': case 'css': case 'default': case 'xhtml': return true; } return false; } }); /** * @attribute removeLineBreaks * @description Should we remove linebreaks and extra spaces on cleanup * @default false * @type Boolean */ this.setAttributeConfig('removeLineBreaks', { value: attr.removeLineBreaks || false, validator: YAHOO.lang.isBoolean }); /** * @config drag * @description Set this config to make the Editor draggable, pass 'proxy' to make use YAHOO.util.DDProxy. * @type {Boolean/String} */ this.setAttributeConfig('drag', { writeOnce: true, value: attr.drag || false }); /** * @config resize * @description Set this to true to make the Editor Resizable with YAHOO.util.Resize. The default config is available: myEditor._resizeConfig * Animation will be ignored while performing this resize to allow for the dynamic change in size of the toolbar. * @type Boolean */ this.setAttributeConfig('resize', { writeOnce: true, value: attr.resize || false }); /** * @config filterWord * @description Attempt to filter out MS Word HTML from the Editor's output. * @type Boolean */ this.setAttributeConfig('filterWord', { value: attr.filterWord || false, validator: YAHOO.lang.isBoolean }); }, /** * @private * @method _getBlankImage * @description Retrieves the full url of the image to use as the blank image. * @return {String} The URL to the blank image */ _getBlankImage: function() { if (!this.DOMReady) { this._queue[this._queue.length] = ['_getBlankImage', arguments]; return ''; } var img = ''; if (!this._blankImageLoaded) { if (YAHOO.widget.EditorInfo.blankImage) { this.set('blankimage', YAHOO.widget.EditorInfo.blankImage); this._blankImageLoaded = true; } else { var div = document.createElement('div'); div.style.position = 'absolute'; div.style.top = '-9999px'; div.style.left = '-9999px'; div.className = this.CLASS_PREFIX + '-blankimage'; document.body.appendChild(div); img = YAHOO.util.Dom.getStyle(div, 'background-image'); img = img.replace('url(', '').replace(')', '').replace(/"/g, ''); //Adobe AIR Code img = img.replace('app:/', ''); this.set('blankimage', img); this._blankImageLoaded = true; div.parentNode.removeChild(div); YAHOO.widget.EditorInfo.blankImage = img; } } else { img = this.get('blankimage'); } return img; }, /** * @private * @method _handleAutoHeight * @description Handles resizing the editor's height based on the content */ _handleAutoHeight: function() { var doc = this._getDoc(), body = doc.body, docEl = doc.documentElement; var height = parseInt(Dom.getStyle(this.get('editor_wrapper'), 'height'), 10); var newHeight = body.scrollHeight; if (this.browser.webkit) { newHeight = docEl.scrollHeight; } if (newHeight < parseInt(this.get('height'), 10)) { newHeight = parseInt(this.get('height'), 10); } if ((height != newHeight) && (newHeight >= parseInt(this.get('height'), 10))) { var anim = this.get('animate'); this.set('animate', false); this.set('height', newHeight + 'px'); this.set('animate', anim); if (this.browser.ie) { //Internet Explorer needs this this.get('iframe').setStyle('height', '99%'); this.get('iframe').setStyle('zoom', '1'); var self = this; window.setTimeout(function() { self.get('iframe').setStyle('height', '100%'); }, 1); } } }, /** * @private * @property _formButtons * @description Array of buttons that are in the Editor's parent form (for handleSubmit) * @type Array */ _formButtons: null, /** * @private * @property _formButtonClicked * @description The form button that was clicked to submit the form. * @type HTMLElement */ _formButtonClicked: null, /** * @private * @method _handleFormButtonClick * @description The click listener assigned to each submit button in the Editor's parent form. * @param {Event} ev The click event */ _handleFormButtonClick: function(ev) { var tar = Event.getTarget(ev); this._formButtonClicked = tar; }, /** * @private * @method _handleFormSubmit * @description Handles the form submission. * @param {Object} ev The Form Submit Event */ _handleFormSubmit: function(ev) { this.saveHTML(); var form = this.get('element').form, tar = this._formButtonClicked || false; Event.removeListener(form, 'submit', this._handleFormSubmit); if (YAHOO.env.ua.ie) { //form.fireEvent("onsubmit"); if (tar && !tar.disabled) { tar.click(); } } else { // Gecko, Opera, and Safari if (tar && !tar.disabled) { tar.click(); } var oEvent = document.createEvent("HTMLEvents"); oEvent.initEvent("submit", true, true); form.dispatchEvent(oEvent); if (YAHOO.env.ua.webkit) { if (YAHOO.lang.isFunction(form.submit)) { form.submit(); } } } //2.6.0 //Removed this, not need since removing Safari 2.x //Event.stopEvent(ev); }, /** * @private * @method _handleFontSize * @description Handles the font size button in the toolbar. * @param {Object} o Object returned from Toolbar's buttonClick Event */ _handleFontSize: function(o) { var button = this.toolbar.getButtonById(o.button.id); var value = button.get('label') + 'px'; this.execCommand('fontsize', value); return false; }, /** * @private * @description Handles the colorpicker buttons in the toolbar. * @param {Object} o Object returned from Toolbar's buttonClick Event */ _handleColorPicker: function(o) { var cmd = o.button; var value = '#' + o.color; if ((cmd == 'forecolor') || (cmd == 'backcolor')) { this.execCommand(cmd, value); } }, /** * @private * @method _handleAlign * @description Handles the alignment buttons in the toolbar. * @param {Object} o Object returned from Toolbar's buttonClick Event */ _handleAlign: function(o) { var cmd = null; for (var i = 0; i < o.button.menu.length; i++) { if (o.button.menu[i].value == o.button.value) { cmd = o.button.menu[i].value; } } var value = this._getSelection(); this.execCommand(cmd, value); return false; }, /** * @private * @method _handleAfterNodeChange * @description Fires after a nodeChange happens to setup the things that where reset on the node change (button state). */ _handleAfterNodeChange: function() { var path = this._getDomPath(), elm = null, family = null, fontsize = null, validFont = false, fn_button = this.toolbar.getButtonByValue('fontname'), fs_button = this.toolbar.getButtonByValue('fontsize'), hd_button = this.toolbar.getButtonByValue('heading'); for (var i = 0; i < path.length; i++) { elm = path[i]; var tag = elm.tagName.toLowerCase(); if (elm.getAttribute('tag')) { tag = elm.getAttribute('tag'); } family = elm.getAttribute('face'); if (Dom.getStyle(elm, 'font-family')) { family = Dom.getStyle(elm, 'font-family'); //Adobe AIR Code family = family.replace(/'/g, ''); } if (tag.substring(0, 1) == 'h') { if (hd_button) { for (var h = 0; h < hd_button._configs.menu.value.length; h++) { if (hd_button._configs.menu.value[h].value.toLowerCase() == tag) { hd_button.set('label', hd_button._configs.menu.value[h].text); } } this._updateMenuChecked('heading', tag); } } } if (fn_button) { for (var b = 0; b < fn_button._configs.menu.value.length; b++) { if (family && fn_button._configs.menu.value[b].text.toLowerCase() == family.toLowerCase()) { validFont = true; family = fn_button._configs.menu.value[b].text; //Put the proper menu name in the button } } if (!validFont) { family = fn_button._configs.label._initialConfig.value; } var familyLabel = '<span class="yui-toolbar-fontname-' + this._cleanClassName(family) + '">' + family + '</span>'; if (fn_button.get('label') != familyLabel) { fn_button.set('label', familyLabel); this._updateMenuChecked('fontname', family); } } if (fs_button) { fontsize = parseInt(Dom.getStyle(elm, 'fontSize'), 10); if ((fontsize === null) || isNaN(fontsize)) { fontsize = fs_button._configs.label._initialConfig.value; } fs_button.set('label', ''+fontsize); } if (!this._isElement(elm, 'body') && !this._isElement(elm, 'img')) { this.toolbar.enableButton(fn_button); this.toolbar.enableButton(fs_button); this.toolbar.enableButton('forecolor'); this.toolbar.enableButton('backcolor'); } if (this._isElement(elm, 'img')) { if (YAHOO.widget.Overlay) { this.toolbar.enableButton('createlink'); } } if (this._hasParent(elm, 'blockquote')) { this.toolbar.selectButton('indent'); this.toolbar.disableButton('indent'); this.toolbar.enableButton('outdent'); } if (this._hasParent(elm, 'ol') || this._hasParent(elm, 'ul')) { this.toolbar.disableButton('indent'); } this._lastButton = null; }, /** * @private * @method _handleInsertImageClick * @description Opens the Image Properties Window when the insert Image button is clicked or an Image is Double Clicked. */ _handleInsertImageClick: function() { if (this.get('limitCommands')) { if (!this.toolbar.getButtonByValue('insertimage')) { YAHOO.log('Toolbar Button for (insertimage) was not found, skipping exec.', 'info', 'SimpleEditor'); return false; } } this.toolbar.set('disabled', true); //Disable the toolbar when the prompt is showing var _handleAEC = function() { var el = this.currentElement[0], src = 'http://'; if (!el) { el = this._getSelectedElement(); } if (el) { if (el.getAttribute('src')) { src = el.getAttribute('src', 2); if (src.indexOf(this.get('blankimage')) != -1) { src = this.STR_IMAGE_HERE; } } } var str = prompt(this.STR_IMAGE_URL + ': ', src); if ((str !== '') && (str !== null)) { el.setAttribute('src', str); } else if (str === '') { el.parentNode.removeChild(el); this.currentElement = []; this.nodeChange(); } else if ((str === null)) { src = el.getAttribute('src', 2); if (src.indexOf(this.get('blankimage')) != -1) { el.parentNode.removeChild(el); this.currentElement = []; this.nodeChange(); } } this.closeWindow(); this.toolbar.set('disabled', false); this.unsubscribe('afterExecCommand', _handleAEC, this, true); }; this.on('afterExecCommand', _handleAEC, this, true); }, /** * @private * @method _handleInsertImageWindowClose * @description Handles the closing of the Image Properties Window. */ _handleInsertImageWindowClose: function() { this.nodeChange(); }, /** * @private * @method _isLocalFile * @param {String} url THe url/string to check * @description Checks to see if a string (href or img src) is possibly a local file reference.. */ _isLocalFile: function(url) { if ((url) && (url !== '') && ((url.indexOf('file:/') != -1) || (url.indexOf(':\\') != -1))) { return true; } return false; }, /** * @private * @method _handleCreateLinkClick * @description Handles the opening of the Link Properties Window when the Create Link button is clicked or an href is doubleclicked. */ _handleCreateLinkClick: function() { if (this.get('limitCommands')) { if (!this.toolbar.getButtonByValue('createlink')) { YAHOO.log('Toolbar Button for (createlink) was not found, skipping exec.', 'info', 'SimpleEditor'); return false; } } this.toolbar.set('disabled', true); //Disable the toolbar when the prompt is showing var _handleAEC = function() { var el = this.currentElement[0], url = ''; if (el) { if (el.getAttribute('href', 2) !== null) { url = el.getAttribute('href', 2); } } var str = prompt(this.STR_LINK_URL + ': ', url); if ((str !== '') && (str !== null)) { var urlValue = str; if ((urlValue.indexOf(':/'+'/') == -1) && (urlValue.substring(0,1) != '/') && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) { if ((urlValue.indexOf('@') != -1) && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) { //Found an @ sign, prefix with mailto: urlValue = 'mailto:' + urlValue; } else { /* :// not found adding */ if (urlValue.substring(0, 1) != '#') { //urlValue = 'http:/'+'/' + urlValue; } } } el.setAttribute('href', urlValue); } else if (str !== null) { var _span = this._getDoc().createElement('span'); _span.innerHTML = el.innerHTML; Dom.addClass(_span, 'yui-non'); el.parentNode.replaceChild(_span, el); } this.closeWindow(); this.toolbar.set('disabled', false); this.unsubscribe('afterExecCommand', _handleAEC, this, true); }; this.on('afterExecCommand', _handleAEC, this); }, /** * @private * @method _handleCreateLinkWindowClose * @description Handles the closing of the Link Properties Window. */ _handleCreateLinkWindowClose: function() { this.nodeChange(); this.currentElement = []; }, /** * @method render * @description Calls the private method _render in a setTimeout to allow for other things on the page to continue to load. */ render: function() { if (this._rendered) { return false; } YAHOO.log('Render', 'info', 'SimpleEditor'); if (!this.DOMReady) { YAHOO.log('!DOMReady', 'info', 'SimpleEditor'); this._queue[this._queue.length] = ['render', arguments]; return false; } if (this.get('element')) { if (this.get('element').tagName) { this._textarea = true; if (this.get('element').tagName.toLowerCase() !== 'textarea') { this._textarea = false; } } else { YAHOO.log('No Valid Element', 'error', 'SimpleEditor'); return false; } } else { YAHOO.log('No Element', 'error', 'SimpleEditor'); return false; } this._rendered = true; var self = this; window.setTimeout(function() { self._render.call(self); }, 4); }, /** * @private * @method _render * @description Causes the toolbar and the editor to render and replace the textarea. */ _render: function() { var self = this; this.set('textarea', this.get('element')); this.get('element_cont').setStyle('display', 'none'); this.get('element_cont').addClass(this.CLASS_CONTAINER); this.set('iframe', this._createIframe()); window.setTimeout(function() { self._setInitialContent.call(self); }, 10); this.get('editor_wrapper').appendChild(this.get('iframe').get('element')); if (this.get('disabled')) { this._disableEditor(true); } var tbarConf = this.get('toolbar'); //Create Toolbar instance if (tbarConf instanceof Toolbar) { this.toolbar = tbarConf; //Set the toolbar to disabled until content is loaded this.toolbar.set('disabled', true); } else { //Set the toolbar to disabled until content is loaded tbarConf.disabled = true; this.toolbar = new Toolbar(this.get('toolbar_cont'), tbarConf); } YAHOO.log('fireEvent::toolbarLoaded', 'info', 'SimpleEditor'); this.fireEvent('toolbarLoaded', { type: 'toolbarLoaded', target: this.toolbar }); this.toolbar.on('toolbarCollapsed', function() { if (this.currentWindow) { this.moveWindow(); } }, this, true); this.toolbar.on('toolbarExpanded', function() { if (this.currentWindow) { this.moveWindow(); } }, this, true); this.toolbar.on('fontsizeClick', this._handleFontSize, this, true); this.toolbar.on('colorPickerClicked', function(o) { this._handleColorPicker(o); return false; //Stop the buttonClick event }, this, true); this.toolbar.on('alignClick', this._handleAlign, this, true); this.on('afterNodeChange', this._handleAfterNodeChange, this, true); this.toolbar.on('insertimageClick', this._handleInsertImageClick, this, true); this.on('windowinsertimageClose', this._handleInsertImageWindowClose, this, true); this.toolbar.on('createlinkClick', this._handleCreateLinkClick, this, true); this.on('windowcreatelinkClose', this._handleCreateLinkWindowClose, this, true); //Replace Textarea with editable area this.get('parentNode').replaceChild(this.get('element_cont').get('element'), this.get('element')); this.setStyle('visibility', 'hidden'); this.setStyle('position', 'absolute'); this.setStyle('top', '-9999px'); this.setStyle('left', '-9999px'); this.get('element_cont').appendChild(this.get('element')); this.get('element_cont').setStyle('display', 'block'); Dom.addClass(this.get('iframe').get('parentNode'), this.CLASS_EDITABLE_CONT); this.get('iframe').addClass(this.CLASS_EDITABLE); //Set height and width of editor container this.get('element_cont').setStyle('width', this.get('width')); Dom.setStyle(this.get('iframe').get('parentNode'), 'height', this.get('height')); this.get('iframe').setStyle('width', '100%'); //WIDTH this.get('iframe').setStyle('height', '100%'); this._setupDD(); window.setTimeout(function() { self._setupAfterElement.call(self); }, 0); this.fireEvent('afterRender', { type: 'afterRender', target: this }); }, /** * @method execCommand * @param {String} action The "execCommand" action to try to execute (Example: bold, insertimage, inserthtml) * @param {String} value (optional) The value for a given action such as action: fontname value: 'Verdana' * @description This method attempts to try and level the differences in the various browsers and their support for execCommand actions */ execCommand: function(action, value) { var beforeExec = this.fireEvent('beforeExecCommand', { type: 'beforeExecCommand', target: this, args: arguments }); if ((beforeExec === false) || (this.STOP_EXEC_COMMAND)) { this.STOP_EXEC_COMMAND = false; return false; } this._lastCommand = action; this._setMarkupType(action); if (this.browser.ie) { this._getWindow().focus(); } var exec = true; if (this.get('limitCommands')) { if (!this.toolbar.getButtonByValue(action)) { YAHOO.log('Toolbar Button for (' + action + ') was not found, skipping exec.', 'info', 'SimpleEditor'); exec = false; } } this.editorDirty = true; if ((typeof this['cmd_' + action.toLowerCase()] == 'function') && exec) { YAHOO.log('Found execCommand override method: (cmd_' + action.toLowerCase() + ')', 'info', 'SimpleEditor'); var retValue = this['cmd_' + action.toLowerCase()](value); exec = retValue[0]; if (retValue[1]) { action = retValue[1]; } if (retValue[2]) { value = retValue[2]; } } if (exec) { YAHOO.log('execCommand::(' + action + '), (' + value + ')', 'info', 'SimpleEditor'); try { this._getDoc().execCommand(action, false, value); } catch(e) { YAHOO.log('execCommand Failed', 'error', 'SimpleEditor'); } } else { YAHOO.log('OVERRIDE::execCommand::(' + action + '),(' + value + ') skipped', 'warn', 'SimpleEditor'); } this.on('afterExecCommand', function() { this.unsubscribeAll('afterExecCommand'); this.nodeChange(); }, this, true); this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this }); }, /* {{{ Command Overrides */ /** * @method cmd_bold * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('bold') is used. */ cmd_bold: function(value) { if (!this.browser.webkit) { var el = this._getSelectedElement(); if (el && this._isElement(el, 'span') && this._hasSelection()) { if (el.style.fontWeight == 'bold') { el.style.fontWeight = ''; var b = this._getDoc().createElement('b'), par = el.parentNode; par.replaceChild(b, el); b.appendChild(el); } } } return [true]; }, /** * @method cmd_italic * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('italic') is used. */ cmd_italic: function(value) { if (!this.browser.webkit) { var el = this._getSelectedElement(); if (el && this._isElement(el, 'span') && this._hasSelection()) { if (el.style.fontStyle == 'italic') { el.style.fontStyle = ''; var i = this._getDoc().createElement('i'), par = el.parentNode; par.replaceChild(i, el); i.appendChild(el); } } } return [true]; }, /** * @method cmd_underline * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('underline') is used. */ cmd_underline: function(value) { if (!this.browser.webkit) { var el = this._getSelectedElement(); if (el && this._isElement(el, 'span')) { if (el.style.textDecoration == 'underline') { el.style.textDecoration = 'none'; } else { el.style.textDecoration = 'underline'; } return [false]; } } return [true]; }, /** * @method cmd_backcolor * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('backcolor') is used. */ cmd_backcolor: function(value) { var exec = true, el = this._getSelectedElement(), action = 'backcolor'; if (this.browser.gecko || this.browser.opera) { this._setEditorStyle(true); action = 'hilitecolor'; } if (!this._isElement(el, 'body') && !this._hasSelection()) { el.style.backgroundColor = value; this._selectNode(el); exec = false; } else { if (this.get('insert')) { el = this._createInsertElement({ backgroundColor: value }); } else { this._createCurrentElement('span', { backgroundColor: value, color: el.style.color, fontSize: el.style.fontSize, fontFamily: el.style.fontFamily }); this._selectNode(this.currentElement[0]); } exec = false; } return [exec, action]; }, /** * @method cmd_forecolor * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('forecolor') is used. */ cmd_forecolor: function(value) { var exec = true, el = this._getSelectedElement(); if (!this._isElement(el, 'body') && !this._hasSelection()) { Dom.setStyle(el, 'color', value); this._selectNode(el); exec = false; } else { if (this.get('insert')) { el = this._createInsertElement({ color: value }); } else { this._createCurrentElement('span', { color: value, fontSize: el.style.fontSize, fontFamily: el.style.fontFamily, backgroundColor: el.style.backgroundColor }); this._selectNode(this.currentElement[0]); } exec = false; } return [exec]; }, /** * @method cmd_unlink * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('unlink') is used. */ cmd_unlink: function(value) { this._swapEl(this.currentElement[0], 'span', function(el) { el.className = 'yui-non'; }); return [false]; }, /** * @method cmd_createlink * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('createlink') is used. */ cmd_createlink: function(value) { var el = this._getSelectedElement(), _a = null; if (this._hasParent(el, 'a')) { this.currentElement[0] = this._hasParent(el, 'a'); } else if (this._isElement(el, 'li')) { _a = this._getDoc().createElement('a'); _a.innerHTML = el.innerHTML; el.innerHTML = ''; el.appendChild(_a); this.currentElement[0] = _a; } else if (!this._isElement(el, 'a')) { this._createCurrentElement('a'); _a = this._swapEl(this.currentElement[0], 'a'); this.currentElement[0] = _a; } else { this.currentElement[0] = el; } return [false]; }, /** * @method cmd_insertimage * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('insertimage') is used. */ cmd_insertimage: function(value) { var exec = true, _img = null, action = 'insertimage', el = this._getSelectedElement(); if (value === '') { value = this.get('blankimage'); } /* * @knownissue Safari Cursor Position * @browser Safari 2.x * @description The issue here is that we have no way of knowing where the cursor position is * inside of the iframe, so we have to place the newly inserted data in the best place that we can. */ YAHOO.log('InsertImage: ' + el.tagName, 'info', 'SimpleEditor'); if (this._isElement(el, 'img')) { this.currentElement[0] = el; exec = false; } else { if (this._getDoc().queryCommandEnabled(action)) { this._getDoc().execCommand(action, false, value); var imgs = this._getDoc().getElementsByTagName('img'); for (var i = 0; i < imgs.length; i++) { if (!YAHOO.util.Dom.hasClass(imgs[i], 'yui-img')) { YAHOO.util.Dom.addClass(imgs[i], 'yui-img'); this.currentElement[0] = imgs[i]; } } exec = false; } else { if (el == this._getDoc().body) { _img = this._getDoc().createElement('img'); _img.setAttribute('src', value); YAHOO.util.Dom.addClass(_img, 'yui-img'); this._getDoc().body.appendChild(_img); } else { this._createCurrentElement('img'); _img = this._getDoc().createElement('img'); _img.setAttribute('src', value); YAHOO.util.Dom.addClass(_img, 'yui-img'); this.currentElement[0].parentNode.replaceChild(_img, this.currentElement[0]); } this.currentElement[0] = _img; exec = false; } } return [exec]; }, /** * @method cmd_inserthtml * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('inserthtml') is used. */ cmd_inserthtml: function(value) { var exec = true, action = 'inserthtml', _span = null, _range = null; /* * @knownissue Safari cursor position * @browser Safari 2.x * @description The issue here is that we have no way of knowing where the cursor position is * inside of the iframe, so we have to place the newly inserted data in the best place that we can. */ if (this.browser.webkit && !this._getDoc().queryCommandEnabled(action)) { YAHOO.log('More Safari DOM tricks (inserthtml)', 'info', 'EditorSafari'); this._createCurrentElement('img'); _span = this._getDoc().createElement('span'); _span.innerHTML = value; this.currentElement[0].parentNode.replaceChild(_span, this.currentElement[0]); exec = false; } else if (this.browser.ie) { _range = this._getRange(); if (_range.item) { _range.item(0).outerHTML = value; } else { _range.pasteHTML(value); } exec = false; } return [exec]; }, /** * @method cmd_list * @param tag The tag of the list you want to create (eg, ul or ol) * @description This is a combined execCommand override method. It is called from the cmd_insertorderedlist and cmd_insertunorderedlist methods. */ cmd_list: function(tag) { var exec = true, list = null, li = 0, el = null, str = '', selEl = this._getSelectedElement(), action = 'insertorderedlist'; if (tag == 'ul') { action = 'insertunorderedlist'; } /* * @knownissue Safari 2.+ doesn't support ordered and unordered lists * @browser Safari 2.x * The issue with this workaround is that when applied to a set of text * that has BR's in it, Safari may or may not pick up the individual items as * list items. This is fixed in WebKit (Safari 3) * 2.6.0: Seems there are still some issues with List Creation and Safari 3, reverting to previously working Safari 2.x code */ //if ((this.browser.webkit && !this._getDoc().queryCommandEnabled(action))) { if ((this.browser.webkit && !this.browser.webkit4) || (this.browser.opera)) { if (this._isElement(selEl, 'li') && this._isElement(selEl.parentNode, tag)) { YAHOO.log('We already have a list, undo it', 'info', 'SimpleEditor'); el = selEl.parentNode; list = this._getDoc().createElement('span'); YAHOO.util.Dom.addClass(list, 'yui-non'); str = ''; var lis = el.getElementsByTagName('li'), p_tag = ((this.browser.opera && this.get('ptags')) ? 'p' : 'div'); for (li = 0; li < lis.length; li++) { str += '<' + p_tag + '>' + lis[li].innerHTML + '</' + p_tag + '>'; } list.innerHTML = str; this.currentElement[0] = el; this.currentElement[0].parentNode.replaceChild(list, this.currentElement[0]); } else { YAHOO.log('Create list item', 'info', 'SimpleEditor'); this._createCurrentElement(tag.toLowerCase()); list = this._getDoc().createElement(tag); for (li = 0; li < this.currentElement.length; li++) { var newli = this._getDoc().createElement('li'); newli.innerHTML = this.currentElement[li].innerHTML + '<span class="yui-non">&nbsp;</span>&nbsp;'; list.appendChild(newli); if (li > 0) { this.currentElement[li].parentNode.removeChild(this.currentElement[li]); } } var b_tag = ((this.browser.opera) ? '<BR>' : '<br>'), items = list.firstChild.innerHTML.split(b_tag), i, item; if (items.length > 0) { list.innerHTML = ''; for (i = 0; i < items.length; i++) { item = this._getDoc().createElement('li'); item.innerHTML = items[i]; list.appendChild(item); } } this.currentElement[0].parentNode.replaceChild(list, this.currentElement[0]); this.currentElement[0] = list; var _h = this.currentElement[0].firstChild; _h = Dom.getElementsByClassName('yui-non', 'span', _h)[0]; if (this.browser.webkit) { this._getSelection().setBaseAndExtent(_h, 1, _h, _h.innerText.length); } } exec = false; } else { el = this._getSelectedElement(); YAHOO.log(el.tagName); if (this._isElement(el, 'li') && this._isElement(el.parentNode, tag) || (this.browser.ie && this._isElement(this._getRange().parentElement, 'li')) || (this.browser.ie && this._isElement(el, 'ul')) || (this.browser.ie && this._isElement(el, 'ol'))) { //we are in a list.. YAHOO.log('We already have a list, undo it', 'info', 'SimpleEditor'); if (this.browser.ie) { if ((this.browser.ie && this._isElement(el, 'ul')) || (this.browser.ie && this._isElement(el, 'ol'))) { el = el.getElementsByTagName('li')[0]; } YAHOO.log('Undo IE', 'info', 'SimpleEditor'); str = ''; var lis2 = el.parentNode.getElementsByTagName('li'); for (var j = 0; j < lis2.length; j++) { str += lis2[j].innerHTML + '<br>'; } var newEl = this._getDoc().createElement('span'); newEl.innerHTML = str; el.parentNode.parentNode.replaceChild(newEl, el.parentNode); } else { this.nodeChange(); this._getDoc().execCommand(action, '', el.parentNode); this.nodeChange(); } exec = false; } if (this.browser.opera) { var self = this; window.setTimeout(function() { var liso = self._getDoc().getElementsByTagName('li'); for (var i = 0; i < liso.length; i++) { if (liso[i].innerHTML.toLowerCase() == '<br>') { liso[i].parentNode.parentNode.removeChild(liso[i].parentNode); } } },30); } if (this.browser.ie && exec) { var html = ''; if (this._getRange().html) { html = '<li>' + this._getRange().html+ '</li>'; } else { var t = this._getRange().text.split('\n'); if (t.length > 1) { html = ''; for (var ie = 0; ie < t.length; ie++) { html += '<li>' + t[ie] + '</li>'; } } else { var txt = this._getRange().text; if (txt === '') { html = '<li id="new_list_item">' + txt + '</li>'; } else { html = '<li>' + txt + '</li>'; } } } this._getRange().pasteHTML('<' + tag + '>' + html + '</' + tag + '>'); var new_item = this._getDoc().getElementById('new_list_item'); if (new_item) { var range = this._getDoc().body.createTextRange(); range.moveToElementText(new_item); range.collapse(false); range.select(); new_item.id = ''; } exec = false; } } return exec; }, /** * @method cmd_insertorderedlist * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('insertorderedlist ') is used. */ cmd_insertorderedlist: function(value) { return [this.cmd_list('ol')]; }, /** * @method cmd_insertunorderedlist * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('insertunorderedlist') is used. */ cmd_insertunorderedlist: function(value) { return [this.cmd_list('ul')]; }, /** * @method cmd_fontname * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('fontname') is used. */ cmd_fontname: function(value) { var exec = true, selEl = this._getSelectedElement(); this.currentFont = value; if (selEl && selEl.tagName && !this._hasSelection() && !this._isElement(selEl, 'body') && !this.get('insert')) { YAHOO.util.Dom.setStyle(selEl, 'font-family', value); exec = false; } else if (this.get('insert') && !this._hasSelection()) { YAHOO.log('No selection and no selected element and we are in insert mode', 'info', 'SimpleEditor'); var el = this._createInsertElement({ fontFamily: value }); exec = false; } return [exec]; }, /** * @method cmd_fontsize * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('fontsize') is used. */ cmd_fontsize: function(value) { var el = null, go = true; el = this._getSelectedElement(); if (this.browser.webkit) { if (this.currentElement[0]) { if (el == this.currentElement[0]) { go = false; YAHOO.util.Dom.setStyle(el, 'fontSize', value); this._selectNode(el); this.currentElement[0] = el; } } } if (go) { if (!this._isElement(this._getSelectedElement(), 'body') && (!this._hasSelection())) { el = this._getSelectedElement(); YAHOO.util.Dom.setStyle(el, 'fontSize', value); if (this.get('insert') && this.browser.ie) { var r = this._getRange(); r.collapse(false); r.select(); } else { this._selectNode(el); } } else if (this.currentElement && (this.currentElement.length > 0) && (!this._hasSelection()) && (!this.get('insert'))) { YAHOO.util.Dom.setStyle(this.currentElement, 'fontSize', value); } else { if (this.get('insert') && !this._hasSelection()) { el = this._createInsertElement({ fontSize: value }); this.currentElement[0] = el; this._selectNode(this.currentElement[0]); } else { this._createCurrentElement('span', {'fontSize': value, fontFamily: el.style.fontFamily, color: el.style.color, backgroundColor: el.style.backgroundColor }); this._selectNode(this.currentElement[0]); } } } return [false]; }, /* }}} */ /** * @private * @method _swapEl * @param {HTMLElement} el The element to swap with * @param {String} tagName The tagname of the element that you wish to create * @param {Function} callback (optional) A function to run on the element after it is created, but before it is replaced. An element reference is passed to this function. * @description This function will create a new element in the DOM and populate it with the contents of another element. Then it will assume it's place. */ _swapEl: function(el, tagName, callback) { var _el = this._getDoc().createElement(tagName); if (el) { _el.innerHTML = el.innerHTML; } if (typeof callback == 'function') { callback.call(this, _el); } if (el) { el.parentNode.replaceChild(_el, el); } return _el; }, /** * @private * @method _createInsertElement * @description Creates a new "currentElement" then adds some text (and other things) to make it selectable and stylable. Then the user can continue typing. * @param {Object} css (optional) Object literal containing styles to apply to the new element. * @return {HTMLElement} */ _createInsertElement: function(css) { this._createCurrentElement('span', css); var el = this.currentElement[0]; if (this.browser.webkit) { //Little Safari Hackery here.. el.innerHTML = '<span class="yui-non">&nbsp;</span>'; el = el.firstChild; this._getSelection().setBaseAndExtent(el, 1, el, el.innerText.length); } else if (this.browser.ie || this.browser.opera) { el.innerHTML = '&nbsp;'; } this.focus(); this._selectNode(el, true); return el; }, /** * @private * @method _createCurrentElement * @param {String} tagName (optional defaults to a) The tagname of the element that you wish to create * @param {Object} tagStyle (optional) Object literal containing styles to apply to the new element. * @description This is a work around for the various browser issues with execCommand. This method will run <code>execCommand('fontname', false, 'yui-tmp')</code> on the given selection. * It will then search the document for an element with the font-family set to <strong>yui-tmp</strong> and replace that with another span that has other information in it, then assign the new span to the * <code>this.currentElement</code> array, so we now have element references to the elements that were just modified. At this point we can use standard DOM manipulation to change them as we see fit. */ _createCurrentElement: function(tagName, tagStyle) { tagName = ((tagName) ? tagName : 'a'); var tar = null, el = [], _doc = this._getDoc(); if (this.currentFont) { if (!tagStyle) { tagStyle = {}; } tagStyle.fontFamily = this.currentFont; this.currentFont = null; } this.currentElement = []; var _elCreate = function(tagName, tagStyle) { var el = null; tagName = ((tagName) ? tagName : 'span'); tagName = tagName.toLowerCase(); switch (tagName) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': el = _doc.createElement(tagName); break; default: el = _doc.createElement(tagName); if (tagName === 'span') { YAHOO.util.Dom.addClass(el, 'yui-tag-' + tagName); YAHOO.util.Dom.addClass(el, 'yui-tag'); el.setAttribute('tag', tagName); } for (var k in tagStyle) { if (YAHOO.lang.hasOwnProperty(tagStyle, k)) { el.style[k] = tagStyle[k]; } } break; } return el; }; if (!this._hasSelection()) { if (this._getDoc().queryCommandEnabled('insertimage')) { this._getDoc().execCommand('insertimage', false, 'yui-tmp-img'); var imgs = this._getDoc().getElementsByTagName('img'); for (var j = 0; j < imgs.length; j++) { if (imgs[j].getAttribute('src', 2) == 'yui-tmp-img') { el = _elCreate(tagName, tagStyle); imgs[j].parentNode.replaceChild(el, imgs[j]); this.currentElement[this.currentElement.length] = el; } } } else { if (this.currentEvent) { tar = YAHOO.util.Event.getTarget(this.currentEvent); } else { //For Safari.. tar = this._getDoc().body; } } if (tar) { /* * @knownissue Safari Cursor Position * @browser Safari 2.x * @description The issue here is that we have no way of knowing where the cursor position is * inside of the iframe, so we have to place the newly inserted data in the best place that we can. */ el = _elCreate(tagName, tagStyle); if (this._isElement(tar, 'body') || this._isElement(tar, 'html')) { if (this._isElement(tar, 'html')) { tar = this._getDoc().body; } tar.appendChild(el); } else if (tar.nextSibling) { tar.parentNode.insertBefore(el, tar.nextSibling); } else { tar.parentNode.appendChild(el); } //this.currentElement = el; this.currentElement[this.currentElement.length] = el; this.currentEvent = null; if (this.browser.webkit) { //Force Safari to focus the new element this._getSelection().setBaseAndExtent(el, 0, el, 0); if (this.browser.webkit3) { this._getSelection().collapseToStart(); } else { this._getSelection().collapse(true); } } } } else { //Force CSS Styling for this action... this._setEditorStyle(true); this._getDoc().execCommand('fontname', false, 'yui-tmp'); var _tmp = [], __tmp, __els = ['font', 'span', 'i', 'b', 'u']; if (!this._isElement(this._getSelectedElement(), 'body')) { __els[__els.length] = this._getDoc().getElementsByTagName(this._getSelectedElement().tagName); __els[__els.length] = this._getDoc().getElementsByTagName(this._getSelectedElement().parentNode.tagName); } for (var _els = 0; _els < __els.length; _els++) { var _tmp1 = this._getDoc().getElementsByTagName(__els[_els]); for (var e = 0; e < _tmp1.length; e++) { _tmp[_tmp.length] = _tmp1[e]; } } for (var i = 0; i < _tmp.length; i++) { if ((YAHOO.util.Dom.getStyle(_tmp[i], 'font-family') == 'yui-tmp') || (_tmp[i].face && (_tmp[i].face == 'yui-tmp'))) { if (tagName !== 'span') { el = _elCreate(tagName, tagStyle); } else { el = _elCreate(_tmp[i].tagName, tagStyle); } el.innerHTML = _tmp[i].innerHTML; if (this._isElement(_tmp[i], 'ol') || (this._isElement(_tmp[i], 'ul'))) { var fc = _tmp[i].getElementsByTagName('li')[0]; _tmp[i].style.fontFamily = 'inherit'; fc.style.fontFamily = 'inherit'; el.innerHTML = fc.innerHTML; fc.innerHTML = ''; fc.appendChild(el); this.currentElement[this.currentElement.length] = el; } else if (this._isElement(_tmp[i], 'li')) { _tmp[i].innerHTML = ''; _tmp[i].appendChild(el); _tmp[i].style.fontFamily = 'inherit'; this.currentElement[this.currentElement.length] = el; } else { if (_tmp[i].parentNode) { _tmp[i].parentNode.replaceChild(el, _tmp[i]); this.currentElement[this.currentElement.length] = el; this.currentEvent = null; if (this.browser.webkit) { //Force Safari to focus the new element this._getSelection().setBaseAndExtent(el, 0, el, 0); if (this.browser.webkit3) { this._getSelection().collapseToStart(); } else { this._getSelection().collapse(true); } } if (this.browser.ie && tagStyle && tagStyle.fontSize) { this._getSelection().empty(); } if (this.browser.gecko) { this._getSelection().collapseToStart(); } } } } } var len = this.currentElement.length; for (var o = 0; o < len; o++) { if ((o + 1) != len) { //Skip the last one in the list if (this.currentElement[o] && this.currentElement[o].nextSibling) { if (this._isElement(this.currentElement[o], 'br')) { this.currentElement[this.currentElement.length] = this.currentElement[o].nextSibling; } } } } } }, /** * @method saveHTML * @description Cleans the HTML with the cleanHTML method then places that string back into the textarea. * @return String */ saveHTML: function() { var html = this.cleanHTML(); if (this._textarea) { this.get('element').value = html; } else { this.get('element').innerHTML = html; } if (this.get('saveEl') !== this.get('element')) { var out = this.get('saveEl'); if (Lang.isString(out)) { out = Dom.get(out); } if (out) { if (out.tagName.toLowerCase() === 'textarea') { out.value = html; } else { out.innerHTML = html; } } } return html; }, /** * @method setEditorHTML * @param {String} incomingHTML The html content to load into the editor * @description Loads HTML into the editors body */ setEditorHTML: function(incomingHTML) { var html = this._cleanIncomingHTML(incomingHTML); html = html.replace(/RIGHT_BRACKET/gi, '{'); html = html.replace(/LEFT_BRACKET/gi, '}'); this._getDoc().body.innerHTML = html; this.nodeChange(); }, /** * @method getEditorHTML * @description Gets the unprocessed/unfiltered HTML from the editor */ getEditorHTML: function() { try { var b = this._getDoc().body; if (b === null) { YAHOO.log('Body is null, returning null.', 'error', 'SimpleEditor'); return null; } return this._getDoc().body.innerHTML; } catch (e) { return ''; } }, /** * @method show * @description This method needs to be called if the Editor was hidden (like in a TabView or Panel). It is used to reset the editor after being in a container that was set to display none. */ show: function() { if (this.browser.gecko) { this._setDesignMode('on'); this.focus(); } if (this.browser.webkit) { var self = this; window.setTimeout(function() { self._setInitialContent.call(self); }, 10); } //Adding this will close all other Editor window's when showing this one. if (this.currentWindow) { this.closeWindow(); } //Put the iframe back in place this.get('iframe').setStyle('position', 'static'); this.get('iframe').setStyle('left', ''); }, /** * @method hide * @description This method needs to be called if the Editor is to be hidden (like in a TabView or Panel). It should be called to clear timeouts and close open editor windows. */ hide: function() { //Adding this will close all other Editor window's. if (this.currentWindow) { this.closeWindow(); } if (this._fixNodesTimer) { clearTimeout(this._fixNodesTimer); this._fixNodesTimer = null; } if (this._nodeChangeTimer) { clearTimeout(this._nodeChangeTimer); this._nodeChangeTimer = null; } this._lastNodeChange = 0; //Move the iframe off of the screen, so that in containers with visiblity hidden, IE will not cover other elements. this.get('iframe').setStyle('position', 'absolute'); this.get('iframe').setStyle('left', '-9999px'); }, /** * @method _cleanIncomingHTML * @param {String} html The unfiltered HTML * @description Process the HTML with a few regexes to clean it up and stabilize the input * @return {String} The filtered HTML */ _cleanIncomingHTML: function(html) { html = html.replace(/{/gi, 'RIGHT_BRACKET'); html = html.replace(/}/gi, 'LEFT_BRACKET'); html = html.replace(/<strong([^>]*)>/gi, '<b$1>'); html = html.replace(/<\/strong>/gi, '</b>'); //replace embed before em check html = html.replace(/<embed([^>]*)>/gi, '<YUI_EMBED$1>'); html = html.replace(/<\/embed>/gi, '</YUI_EMBED>'); html = html.replace(/<em([^>]*)>/gi, '<i$1>'); html = html.replace(/<\/em>/gi, '</i>'); html = html.replace(/_moz_dirty=""/gi, ''); //Put embed tags back in.. html = html.replace(/<YUI_EMBED([^>]*)>/gi, '<embed$1>'); html = html.replace(/<\/YUI_EMBED>/gi, '</embed>'); if (this.get('plainText')) { YAHOO.log('Filtering as plain text', 'info', 'SimpleEditor'); html = html.replace(/\n/g, '<br>').replace(/\r/g, '<br>'); html = html.replace(/ /gi, '&nbsp;&nbsp;'); //Replace all double spaces html = html.replace(/\t/gi, '&nbsp;&nbsp;&nbsp;&nbsp;'); //Replace all tabs } //Removing Script Tags from the Editor html = html.replace(/<script([^>]*)>/gi, '<bad>'); html = html.replace(/<\/script([^>]*)>/gi, '</bad>'); html = html.replace(/&lt;script([^>]*)&gt;/gi, '<bad>'); html = html.replace(/&lt;\/script([^>]*)&gt;/gi, '</bad>'); //Replace the line feeds html = html.replace(/\r\n/g, '<YUI_LF>').replace(/\n/g, '<YUI_LF>').replace(/\r/g, '<YUI_LF>'); //Remove Bad HTML elements (used to be script nodes) html = html.replace(new RegExp('<bad([^>]*)>(.*?)<\/bad>', 'gi'), ''); //Replace the lines feeds html = html.replace(/<YUI_LF>/g, '\n'); return html; }, /** * @method cleanHTML * @param {String} html The unfiltered HTML * @description Process the HTML with a few regexes to clean it up and stabilize the output * @return {String} The filtered HTML */ cleanHTML: function(html) { //Start Filtering Output //Begin RegExs.. if (!html) { html = this.getEditorHTML(); } var markup = this.get('markup'); //Make some backups... html = this.pre_filter_linebreaks(html, markup); //Filter MS Word html = this.filter_msword(html); html = html.replace(/<img([^>]*)\/>/gi, '<YUI_IMG$1>'); html = html.replace(/<img([^>]*)>/gi, '<YUI_IMG$1>'); html = html.replace(/<input([^>]*)\/>/gi, '<YUI_INPUT$1>'); html = html.replace(/<input([^>]*)>/gi, '<YUI_INPUT$1>'); html = html.replace(/<ul([^>]*)>/gi, '<YUI_UL$1>'); html = html.replace(/<\/ul>/gi, '<\/YUI_UL>'); html = html.replace(/<blockquote([^>]*)>/gi, '<YUI_BQ$1>'); html = html.replace(/<\/blockquote>/gi, '<\/YUI_BQ>'); html = html.replace(/<embed([^>]*)>/gi, '<YUI_EMBED$1>'); html = html.replace(/<\/embed>/gi, '<\/YUI_EMBED>'); //Convert b and i tags to strong and em tags if ((markup == 'semantic') || (markup == 'xhtml')) { //html = html.replace(/<i(\s+[^>]*)?>/gi, "<em$1>"); html = html.replace(/<i([^>]*)>/gi, "<em$1>"); html = html.replace(/<\/i>/gi, '</em>'); //html = html.replace(/<b(\s+[^>]*)?>/gi, "<strong$1>"); html = html.replace(/<b([^>]*)>/gi, "<strong$1>"); html = html.replace(/<\/b>/gi, '</strong>'); } html = html.replace(/_moz_dirty=""/gi, ''); //normalize strikethrough html = html.replace(/<strike/gi, '<span style="text-decoration: line-through;"'); html = html.replace(/\/strike>/gi, '/span>'); //Case Changing if (this.browser.ie) { html = html.replace(/text-decoration/gi, 'text-decoration'); html = html.replace(/font-weight/gi, 'font-weight'); html = html.replace(/_width="([^>]*)"/gi, ''); html = html.replace(/_height="([^>]*)"/gi, ''); //Cleanup Image URL's var url = this._baseHREF.replace(/\//gi, '\\/'), re = new RegExp('src="' + url, 'gi'); html = html.replace(re, 'src="'); } html = html.replace(/<font/gi, '<font'); html = html.replace(/<\/font>/gi, '</font>'); html = html.replace(/<span/gi, '<span'); html = html.replace(/<\/span>/gi, '</span>'); if ((markup == 'semantic') || (markup == 'xhtml') || (markup == 'css')) { html = html.replace(new RegExp('<font([^>]*)face="([^>]*)">(.*?)<\/font>', 'gi'), '<span $1 style="font-family: $2;">$3</span>'); html = html.replace(/<u/gi, '<span style="text-decoration: underline;"'); if (this.browser.webkit) { html = html.replace(new RegExp('<span class="Apple-style-span" style="font-weight: bold;">([^>]*)<\/span>', 'gi'), '<strong>$1</strong>'); html = html.replace(new RegExp('<span class="Apple-style-span" style="font-style: italic;">([^>]*)<\/span>', 'gi'), '<em>$1</em>'); } html = html.replace(/\/u>/gi, '/span>'); if (markup == 'css') { html = html.replace(/<em([^>]*)>/gi, '<i$1>'); html = html.replace(/<\/em>/gi, '</i>'); html = html.replace(/<strong([^>]*)>/gi, '<b$1>'); html = html.replace(/<\/strong>/gi, '</b>'); html = html.replace(/<b/gi, '<span style="font-weight: bold;"'); html = html.replace(/\/b>/gi, '/span>'); html = html.replace(/<i/gi, '<span style="font-style: italic;"'); html = html.replace(/\/i>/gi, '/span>'); } html = html.replace(/ /gi, ' '); //Replace all double spaces and replace with a single } else { html = html.replace(/<u/gi, '<u'); html = html.replace(/\/u>/gi, '/u>'); } html = html.replace(/<ol([^>]*)>/gi, '<ol$1>'); html = html.replace(/\/ol>/gi, '/ol>'); html = html.replace(/<li/gi, '<li'); html = html.replace(/\/li>/gi, '/li>'); html = this.filter_safari(html); html = this.filter_internals(html); html = this.filter_all_rgb(html); //Replace our backups with the real thing html = this.post_filter_linebreaks(html, markup); if (markup == 'xhtml') { html = html.replace(/<YUI_IMG([^>]*)>/g, '<img $1 />'); html = html.replace(/<YUI_INPUT([^>]*)>/g, '<input $1 />'); } else { html = html.replace(/<YUI_IMG([^>]*)>/g, '<img $1>'); html = html.replace(/<YUI_INPUT([^>]*)>/g, '<input $1>'); } html = html.replace(/<YUI_UL([^>]*)>/g, '<ul$1>'); html = html.replace(/<\/YUI_UL>/g, '<\/ul>'); html = this.filter_invalid_lists(html); html = html.replace(/<YUI_BQ([^>]*)>/g, '<blockquote$1>'); html = html.replace(/<\/YUI_BQ>/g, '<\/blockquote>'); html = html.replace(/<YUI_EMBED([^>]*)>/g, '<embed$1>'); html = html.replace(/<\/YUI_EMBED>/g, '<\/embed>'); //This should fix &amp;'s in URL's html = html.replace(/ &amp; /gi, ' YUI_AMP '); html = html.replace(/ &amp;/gi, ' YUI_AMP_F '); html = html.replace(/&amp; /gi, ' YUI_AMP_R '); html = html.replace(/&amp;/gi, '&'); html = html.replace(/ YUI_AMP /gi, ' &amp; '); html = html.replace(/ YUI_AMP_F /gi, ' &amp;'); html = html.replace(/ YUI_AMP_R /gi, '&amp; '); //Trim the output, removing whitespace from the beginning and end html = YAHOO.lang.trim(html); if (this.get('removeLineBreaks')) { html = html.replace(/\n/g, '').replace(/\r/g, ''); html = html.replace(/ /gi, ' '); //Replace all double spaces and replace with a single } for (var v in this.invalidHTML) { if (YAHOO.lang.hasOwnProperty(this.invalidHTML, v)) { if (Lang.isObject(v) && v.keepContents) { html = html.replace(new RegExp('<' + v + '([^>]*)>(.*?)<\/' + v + '>', 'gi'), '$1'); } else { html = html.replace(new RegExp('<' + v + '([^>]*)>(.*?)<\/' + v + '>', 'gi'), ''); } } } /* LATER -- Add DOM manipulation console.log(html); var frag = document.createDocumentFragment(); frag.innerHTML = html; var ps = frag.getElementsByTagName('p'), len = ps.length; for (var i = 0; i < len; i++) { var ps2 = ps[i].getElementsByTagName('p'); if (ps2.length) { } } html = frag.innerHTML; console.log(html); */ this.fireEvent('cleanHTML', { type: 'cleanHTML', target: this, html: html }); return html; }, /** * @method filter_msword * @param String html The HTML string to filter * @description Filters out msword html attributes and other junk. Activate with filterWord: true in config */ filter_msword: function(html) { if (!this.get('filterWord')) { return html; } //Remove the ms o: tags html = html.replace(/<o:p>\s*<\/o:p>/g, ''); html = html.replace(/<o:p>[\s\S]*?<\/o:p>/g, '&nbsp;'); //Remove the ms w: tags html = html.replace( /<w:[^>]*>[\s\S]*?<\/w:[^>]*>/gi, ''); //Remove mso-? styles. html = html.replace( /\s*mso-[^:]+:[^;"]+;?/gi, ''); //Remove more bogus MS styles. html = html.replace( /\s*MARGIN: 0cm 0cm 0pt\s*;/gi, ''); html = html.replace( /\s*MARGIN: 0cm 0cm 0pt\s*"/gi, "\""); html = html.replace( /\s*TEXT-INDENT: 0cm\s*;/gi, ''); html = html.replace( /\s*TEXT-INDENT: 0cm\s*"/gi, "\""); html = html.replace( /\s*PAGE-BREAK-BEFORE: [^\s;]+;?"/gi, "\""); html = html.replace( /\s*FONT-VARIANT: [^\s;]+;?"/gi, "\"" ); html = html.replace( /\s*tab-stops:[^;"]*;?/gi, ''); html = html.replace( /\s*tab-stops:[^"]*/gi, ''); //Remove XML declarations html = html.replace(/<\\?\?xml[^>]*>/gi, ''); //Remove lang html = html.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3"); //Remove language tags html = html.replace( /<(\w[^>]*) language=([^ |>]*)([^>]*)/gi, "<$1$3"); //Remove onmouseover and onmouseout events (from MS Word comments effect) html = html.replace( /<(\w[^>]*) onmouseover="([^\"]*)"([^>]*)/gi, "<$1$3"); html = html.replace( /<(\w[^>]*) onmouseout="([^\"]*)"([^>]*)/gi, "<$1$3"); return html; }, /** * @method filter_invalid_lists * @param String html The HTML string to filter * @description Filters invalid ol and ul list markup, converts this: <li></li><ol>..</ol> to this: <li></li><li><ol>..</ol></li> */ filter_invalid_lists: function(html) { html = html.replace(/<\/li>\n/gi, '</li>'); html = html.replace(/<\/li><ol>/gi, '</li><li><ol>'); html = html.replace(/<\/ol>/gi, '</ol></li>'); html = html.replace(/<\/ol><\/li>\n/gi, "</ol>"); html = html.replace(/<\/li><ul>/gi, '</li><li><ul>'); html = html.replace(/<\/ul>/gi, '</ul></li>'); html = html.replace(/<\/ul><\/li>\n?/gi, "</ul>"); html = html.replace(/<\/li>/gi, "</li>"); html = html.replace(/<\/ol>/gi, "</ol>"); html = html.replace(/<ol>/gi, "<ol>"); html = html.replace(/<ul>/gi, "<ul>"); return html; }, /** * @method filter_safari * @param String html The HTML string to filter * @description Filters strings specific to Safari * @return String */ filter_safari: function(html) { if (this.browser.webkit) { //<span class="Apple-tab-span" style="white-space:pre"> </span> html = html.replace(/<span class="Apple-tab-span" style="white-space:pre">([^>])<\/span>/gi, '&nbsp;&nbsp;&nbsp;&nbsp;'); html = html.replace(/Apple-style-span/gi, ''); html = html.replace(/style="line-height: normal;"/gi, ''); html = html.replace(/yui-wk-div/gi, ''); html = html.replace(/yui-wk-p/gi, ''); //Remove bogus LI's html = html.replace(/<li><\/li>/gi, ''); html = html.replace(/<li> <\/li>/gi, ''); html = html.replace(/<li> <\/li>/gi, ''); //Remove bogus DIV's - updated from just removing the div's to replacing /div with a break if (this.get('ptags')) { html = html.replace(/<div([^>]*)>/g, '<p$1>'); html = html.replace(/<\/div>/gi, '</p>'); } else { //html = html.replace(/<div>/gi, '<br>'); html = html.replace(/<div([^>]*)>([ tnr]*)<\/div>/gi, '<br>'); html = html.replace(/<\/div>/gi, ''); } } return html; }, /** * @method filter_internals * @param String html The HTML string to filter * @description Filters internal RTE strings and bogus attrs we don't want * @return String */ filter_internals: function(html) { html = html.replace(/\r/g, ''); //Fix stuff we don't want html = html.replace(/<\/?(body|head|html)[^>]*>/gi, ''); //Fix last BR in LI html = html.replace(/<YUI_BR><\/li>/gi, '</li>'); html = html.replace(/yui-tag-span/gi, ''); html = html.replace(/yui-tag/gi, ''); html = html.replace(/yui-non/gi, ''); html = html.replace(/yui-img/gi, ''); html = html.replace(/ tag="span"/gi, ''); html = html.replace(/ class=""/gi, ''); html = html.replace(/ style=""/gi, ''); html = html.replace(/ class=" "/gi, ''); html = html.replace(/ class=" "/gi, ''); html = html.replace(/ target=""/gi, ''); html = html.replace(/ title=""/gi, ''); if (this.browser.ie) { html = html.replace(/ class= /gi, ''); html = html.replace(/ class= >/gi, ''); } return html; }, /** * @method filter_all_rgb * @param String str The HTML string to filter * @description Converts all RGB color strings found in passed string to a hex color, example: style="color: rgb(0, 255, 0)" converts to style="color: #00ff00" * @return String */ filter_all_rgb: function(str) { var exp = new RegExp("rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)", "gi"); var arr = str.match(exp); if (Lang.isArray(arr)) { for (var i = 0; i < arr.length; i++) { var color = this.filter_rgb(arr[i]); str = str.replace(arr[i].toString(), color); } } return str; }, /** * @method filter_rgb * @param String css The CSS string containing rgb(#,#,#); * @description Converts an RGB color string to a hex color, example: rgb(0, 255, 0) converts to #00ff00 * @return String */ filter_rgb: function(css) { if (css.toLowerCase().indexOf('rgb') != -1) { var exp = new RegExp("(.*?)rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)(.*?)", "gi"); var rgb = css.replace(exp, "$1,$2,$3,$4,$5").split(','); if (rgb.length == 5) { var r = parseInt(rgb[1], 10).toString(16); var g = parseInt(rgb[2], 10).toString(16); var b = parseInt(rgb[3], 10).toString(16); r = r.length == 1 ? '0' + r : r; g = g.length == 1 ? '0' + g : g; b = b.length == 1 ? '0' + b : b; css = "#" + r + g + b; } } return css; }, /** * @method pre_filter_linebreaks * @param String html The HTML to filter * @param String markup The markup type to filter to * @description HTML Pre Filter * @return String */ pre_filter_linebreaks: function(html, markup) { if (this.browser.webkit) { html = html.replace(/<br class="khtml-block-placeholder">/gi, '<YUI_BR>'); html = html.replace(/<br class="webkit-block-placeholder">/gi, '<YUI_BR>'); } html = html.replace(/<br>/gi, '<YUI_BR>'); html = html.replace(/<br (.*?)>/gi, '<YUI_BR>'); html = html.replace(/<br\/>/gi, '<YUI_BR>'); html = html.replace(/<br \/>/gi, '<YUI_BR>'); html = html.replace(/<div><YUI_BR><\/div>/gi, '<YUI_BR>'); html = html.replace(/<p>(&nbsp;|&#160;)<\/p>/g, '<YUI_BR>'); html = html.replace(/<p><br>&nbsp;<\/p>/gi, '<YUI_BR>'); html = html.replace(/<p>&nbsp;<\/p>/gi, '<YUI_BR>'); //Fix last BR html = html.replace(/<YUI_BR>$/, ''); //Fix last BR in P html = html.replace(/<YUI_BR><\/p>/g, '</p>'); if (this.browser.ie) { html = html.replace(/&nbsp;&nbsp;&nbsp;&nbsp;/g, '\t'); } return html; }, /** * @method post_filter_linebreaks * @param String html The HTML to filter * @param String markup The markup type to filter to * @description HTML Pre Filter * @return String */ post_filter_linebreaks: function(html, markup) { if (markup == 'xhtml') { html = html.replace(/<YUI_BR>/g, '<br />'); } else { html = html.replace(/<YUI_BR>/g, '<br>'); } return html; }, /** * @method clearEditorDoc * @description Clear the doc of the Editor */ clearEditorDoc: function() { this._getDoc().body.innerHTML = '&nbsp;'; }, /** * @method openWindow * @description Override Method for Advanced Editor */ openWindow: function(win) { }, /** * @method moveWindow * @description Override Method for Advanced Editor */ moveWindow: function() { }, /** * @private * @method _closeWindow * @description Override Method for Advanced Editor */ _closeWindow: function() { }, /** * @method closeWindow * @description Override Method for Advanced Editor */ closeWindow: function() { //this.unsubscribeAll('afterExecCommand'); this.toolbar.resetAllButtons(); this.focus(); }, /** * @method destroy * @description Destroys the editor, all of it's elements and objects. * @return {Boolean} */ destroy: function() { if (this._nodeChangeDelayTimer) { clearTimeout(this._nodeChangeDelayTimer); } this.hide(); YAHOO.log('Destroying Editor', 'warn', 'SimpleEditor'); if (this.resize) { YAHOO.log('Destroying Resize', 'warn', 'SimpleEditor'); this.resize.destroy(); } if (this.dd) { YAHOO.log('Unreg DragDrop Instance', 'warn', 'SimpleEditor'); this.dd.unreg(); } if (this.get('panel')) { YAHOO.log('Destroying Editor Panel', 'warn', 'SimpleEditor'); this.get('panel').destroy(); } this.saveHTML(); this.toolbar.destroy(); YAHOO.log('Restoring TextArea', 'info', 'SimpleEditor'); this.setStyle('visibility', 'visible'); this.setStyle('position', 'static'); this.setStyle('top', ''); this.setStyle('left', ''); var textArea = this.get('element'); this.get('element_cont').get('parentNode').replaceChild(textArea, this.get('element_cont').get('element')); this.get('element_cont').get('element').innerHTML = ''; this.set('handleSubmit', false); //Remove the submit handler return true; }, /** * @method toString * @description Returns a string representing the editor. * @return {String} */ toString: function() { var str = 'SimpleEditor'; if (this.get && this.get('element_cont')) { str = 'SimpleEditor (#' + this.get('element_cont').get('id') + ')' + ((this.get('disabled') ? ' Disabled' : '')); } return str; } }); /** * @event toolbarLoaded * @description Event is fired during the render process directly after the Toolbar is loaded. Allowing you to attach events to the toolbar. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event cleanHTML * @description Event is fired after the cleanHTML method is called. * @type YAHOO.util.CustomEvent */ /** * @event afterRender * @description Event is fired after the render process finishes. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorContentLoaded * @description Event is fired after the editor iframe's document fully loads and fires it's onload event. From here you can start injecting your own things into the document. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event beforeNodeChange * @description Event fires at the beginning of the nodeChange process. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event afterNodeChange * @description Event fires at the end of the nodeChange process. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event beforeExecCommand * @description Event fires at the beginning of the execCommand process. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event afterExecCommand * @description Event fires at the end of the execCommand process. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorMouseUp * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorMouseDown * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorDoubleClick * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorClick * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorKeyUp * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorKeyPress * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorKeyDown * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorMouseUp * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorMouseDown * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorDoubleClick * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorClick * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorKeyUp * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorKeyPress * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorKeyDown * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event editorWindowFocus * @description Fires when the iframe is focused. Note, this is window focus event, not an Editor focus event. * @type YAHOO.util.CustomEvent */ /** * @event editorWindowBlur * @description Fires when the iframe is blurred. Note, this is window blur event, not an Editor blur event. * @type YAHOO.util.CustomEvent */ /** * @description Singleton object used to track the open window objects and panels across the various open editors * @class EditorInfo * @static */ YAHOO.widget.EditorInfo = { /** * @private * @property _instances * @description A reference to all editors on the page. * @type Object */ _instances: {}, /** * @private * @property blankImage * @description A reference to the blankImage url * @type String */ blankImage: '', /** * @private * @property window * @description A reference to the currently open window object in any editor on the page. * @type Object <a href="YAHOO.widget.EditorWindow.html">YAHOO.widget.EditorWindow</a> */ window: {}, /** * @private * @property panel * @description A reference to the currently open panel in any editor on the page. * @type Object <a href="YAHOO.widget.Overlay.html">YAHOO.widget.Overlay</a> */ panel: null, /** * @method getEditorById * @description Returns a reference to the Editor object associated with the given textarea * @param {String/HTMLElement} id The id or reference of the textarea to return the Editor instance of * @return Object <a href="YAHOO.widget.Editor.html">YAHOO.widget.Editor</a> */ getEditorById: function(id) { if (!YAHOO.lang.isString(id)) { //Not a string, assume a node Reference id = id.id; } if (this._instances[id]) { return this._instances[id]; } return false; }, /** * @method saveAll * @description Saves all Editor instances on the page. If a form reference is passed, only Editor's bound to this form will be saved. * @param {HTMLElement} form The form to check if this Editor instance belongs to */ saveAll: function(form) { var i, e, items = YAHOO.widget.EditorInfo._instances; if (form) { for (i in items) { if (Lang.hasOwnProperty(items, i)) { e = items[i]; if (e.get('element').form && (e.get('element').form == form)) { e.saveHTML(); } } } } else { for (i in items) { if (Lang.hasOwnProperty(items, i)) { items[i].saveHTML(); } } } }, /** * @method toString * @description Returns a string representing the EditorInfo. * @return {String} */ toString: function() { var len = 0; for (var i in this._instances) { if (Lang.hasOwnProperty(this._instances, i)) { len++; } } return 'Editor Info (' + len + ' registered intance' + ((len > 1) ? 's' : '') + ')'; } }; })(); YAHOO.register("simpleeditor", YAHOO.widget.SimpleEditor, {version: "2.9.0", build: "2800"}); }, '2.9.0' ,{"requires": ["yui2-yahoo", "yui2-dom", "yui2-skin-sam-simpleeditor", "yui2-event", "yui2-element"], "optional": ["yui2-containercore", "yui2-dragdrop", "yui2-skin-sam-button", "yui2-skin-sam-menu", "yui2-menu", "yui2-button", "yui2-animation"]});
sorted2323/msi
testauthorize/lib/yuilib/2in3/2.9.0/build/yui2-simpleeditor/yui2-simpleeditor-debug.js
JavaScript
gpl-3.0
316,908
/* * leds-ns2.c - Driver for the Network Space v2 (and parents) dual-GPIO LED * * Copyright (C) 2010 LaCie * * Author: Simon Guinot <[email protected]> * * Based on leds-gpio.c by Raphael Assenat <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/gpio.h> #include <linux/leds.h> #include <mach/leds-ns2.h> /* * The Network Space v2 dual-GPIO LED is wired to a CPLD and can blink in * relation with the SATA activity. This capability is exposed through the * "sata" sysfs attribute. * * The following array detail the different LED registers and the combination * of their possible values: * * cmd_led | slow_led | /SATA active | LED state * | | | * 1 | 0 | x | off * - | 1 | x | on * 0 | 0 | 1 | on * 0 | 0 | 0 | blink (rate 300ms) */ enum ns2_led_modes { NS_V2_LED_OFF, NS_V2_LED_ON, NS_V2_LED_SATA, }; struct ns2_led_mode_value { enum ns2_led_modes mode; int cmd_level; int slow_level; }; static struct ns2_led_mode_value ns2_led_modval[] = { { NS_V2_LED_OFF , 1, 0 }, { NS_V2_LED_ON , 0, 1 }, { NS_V2_LED_ON , 1, 1 }, { NS_V2_LED_SATA, 0, 0 }, }; struct ns2_led_data { struct led_classdev cdev; unsigned cmd; unsigned slow; unsigned char sata; /* True when SATA mode active. */ rwlock_t rw_lock; /* Lock GPIOs. */ }; static int ns2_led_get_mode(struct ns2_led_data *led_dat, enum ns2_led_modes *mode) { int i; int ret = -EINVAL; int cmd_level; int slow_level; read_lock_irq(&led_dat->rw_lock); cmd_level = gpio_get_value(led_dat->cmd); slow_level = gpio_get_value(led_dat->slow); for (i = 0; i < ARRAY_SIZE(ns2_led_modval); i++) { if (cmd_level == ns2_led_modval[i].cmd_level && slow_level == ns2_led_modval[i].slow_level) { *mode = ns2_led_modval[i].mode; ret = 0; break; } } read_unlock_irq(&led_dat->rw_lock); return ret; } static void ns2_led_set_mode(struct ns2_led_data *led_dat, enum ns2_led_modes mode) { int i; unsigned long flags; write_lock_irqsave(&led_dat->rw_lock, flags); for (i = 0; i < ARRAY_SIZE(ns2_led_modval); i++) { if (mode == ns2_led_modval[i].mode) { gpio_set_value(led_dat->cmd, ns2_led_modval[i].cmd_level); gpio_set_value(led_dat->slow, ns2_led_modval[i].slow_level); } } write_unlock_irqrestore(&led_dat->rw_lock, flags); } static void ns2_led_set(struct led_classdev *led_cdev, enum led_brightness value) { struct ns2_led_data *led_dat = container_of(led_cdev, struct ns2_led_data, cdev); enum ns2_led_modes mode; if (value == LED_OFF) mode = NS_V2_LED_OFF; else if (led_dat->sata) mode = NS_V2_LED_SATA; else mode = NS_V2_LED_ON; ns2_led_set_mode(led_dat, mode); } static ssize_t ns2_led_sata_store(struct device *dev, struct device_attribute *attr, const char *buff, size_t count) { struct led_classdev *led_cdev = dev_get_drvdata(dev); struct ns2_led_data *led_dat = container_of(led_cdev, struct ns2_led_data, cdev); int ret; unsigned long enable; enum ns2_led_modes mode; ret = strict_strtoul(buff, 10, &enable); if (ret < 0) return ret; enable = !!enable; if (led_dat->sata == enable) return count; ret = ns2_led_get_mode(led_dat, &mode); if (ret < 0) return ret; if (enable && mode == NS_V2_LED_ON) ns2_led_set_mode(led_dat, NS_V2_LED_SATA); if (!enable && mode == NS_V2_LED_SATA) ns2_led_set_mode(led_dat, NS_V2_LED_ON); led_dat->sata = enable; return count; } static ssize_t ns2_led_sata_show(struct device *dev, struct device_attribute *attr, char *buf) { struct led_classdev *led_cdev = dev_get_drvdata(dev); struct ns2_led_data *led_dat = container_of(led_cdev, struct ns2_led_data, cdev); return sprintf(buf, "%d\n", led_dat->sata); } static DEVICE_ATTR(sata, 0644, ns2_led_sata_show, ns2_led_sata_store); static int __devinit create_ns2_led(struct platform_device *pdev, struct ns2_led_data *led_dat, const struct ns2_led *template) { int ret; enum ns2_led_modes mode; ret = gpio_request(template->cmd, template->name); if (ret == 0) { ret = gpio_direction_output(template->cmd, gpio_get_value(template->cmd)); if (ret) gpio_free(template->cmd); } if (ret) { dev_err(&pdev->dev, "%s: failed to setup command GPIO\n", template->name); } ret = gpio_request(template->slow, template->name); if (ret == 0) { ret = gpio_direction_output(template->slow, gpio_get_value(template->slow)); if (ret) gpio_free(template->slow); } if (ret) { dev_err(&pdev->dev, "%s: failed to setup slow GPIO\n", template->name); goto err_free_cmd; } rwlock_init(&led_dat->rw_lock); led_dat->cdev.name = template->name; led_dat->cdev.default_trigger = template->default_trigger; led_dat->cdev.blink_set = NULL; led_dat->cdev.brightness_set = ns2_led_set; led_dat->cdev.flags |= LED_CORE_SUSPENDRESUME; led_dat->cmd = template->cmd; led_dat->slow = template->slow; ret = ns2_led_get_mode(led_dat, &mode); if (ret < 0) goto err_free_slow; /* Set LED initial state. */ led_dat->sata = (mode == NS_V2_LED_SATA) ? 1 : 0; led_dat->cdev.brightness = (mode == NS_V2_LED_OFF) ? LED_OFF : LED_FULL; ret = led_classdev_register(&pdev->dev, &led_dat->cdev); if (ret < 0) goto err_free_slow; ret = device_create_file(led_dat->cdev.dev, &dev_attr_sata); if (ret < 0) goto err_free_cdev; return 0; err_free_cdev: led_classdev_unregister(&led_dat->cdev); err_free_slow: gpio_free(led_dat->slow); err_free_cmd: gpio_free(led_dat->cmd); return ret; } static void __devexit delete_ns2_led(struct ns2_led_data *led_dat) { device_remove_file(led_dat->cdev.dev, &dev_attr_sata); led_classdev_unregister(&led_dat->cdev); gpio_free(led_dat->cmd); gpio_free(led_dat->slow); } static int __devinit ns2_led_probe(struct platform_device *pdev) { struct ns2_led_platform_data *pdata = pdev->dev.platform_data; struct ns2_led_data *leds_data; int i; int ret; if (!pdata) return -EINVAL; leds_data = kzalloc(sizeof(struct ns2_led_data) * pdata->num_leds, GFP_KERNEL); if (!leds_data) return -ENOMEM; for (i = 0; i < pdata->num_leds; i++) { ret = create_ns2_led(pdev, &leds_data[i], &pdata->leds[i]); if (ret < 0) goto err; } platform_set_drvdata(pdev, leds_data); return 0; err: for (i = i - 1; i >= 0; i--) delete_ns2_led(&leds_data[i]); kfree(leds_data); return ret; } static int __devexit ns2_led_remove(struct platform_device *pdev) { int i; struct ns2_led_platform_data *pdata = pdev->dev.platform_data; struct ns2_led_data *leds_data; leds_data = platform_get_drvdata(pdev); for (i = 0; i < pdata->num_leds; i++) delete_ns2_led(&leds_data[i]); kfree(leds_data); platform_set_drvdata(pdev, NULL); return 0; } static struct platform_driver ns2_led_driver = { .probe = ns2_led_probe, .remove = __devexit_p(ns2_led_remove), .driver = { .name = "leds-ns2", .owner = THIS_MODULE, }, }; MODULE_ALIAS("platform:leds-ns2"); static int __init ns2_led_init(void) { return platform_driver_register(&ns2_led_driver); } static void __exit ns2_led_exit(void) { platform_driver_unregister(&ns2_led_driver); } module_init(ns2_led_init); module_exit(ns2_led_exit); MODULE_AUTHOR("Simon Guinot <[email protected]>"); MODULE_DESCRIPTION("Network Space v2 LED driver"); MODULE_LICENSE("GPL");
JijonHyuni/HyperKernel-JB
virt/drivers/leds/leds-ns2.c
C
gpl-2.0
8,245
<!DOCTYPE html> <html> <head> <meta charset="utf8"> <title>Flurry sample | Angulartics</title> <link rel="stylesheet" href="//bootswatch.com/cosmo/bootstrap.min.css"> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> <script src="../src/angulartics.js"></script> <script src="../src/angulartics-flurry.js"></script> <script src="https://cdn.flurry.com/js/flurry.js"></script> <script>FlurryAgent.startSession("D9XSHYVM45KQ8BDJY3YF");</script> </head> <body ng-app="sample"> <div class="navbar navbar-default"> <div class="navbar-header"> <a class="navbar-brand" href="#/">My App</a> </div> <div> <ul class="nav navbar-nav"> <li><a analytics-on analytics-event="Page A" analytics-category="Navigation" href="#/a">Page A</a></li> <li><a analytics-on analytics-event="Page B" analytics-category="Navigation" href="#/b">Page B</a></li> <li><a analytics-on analytics-event="Page C" analytics-category="Navigation" href="#/c">Page C</a></li> </ul> </div> </div> <div class="container"> <div ng-view></div> <hr> <button analytics-on="click" analytics-event="Button 1" analytics-category="Commands" class="btn btn-default">Button 1</button> <!-- same as analytics-on="click", because 'click' is the default --> <button analytics-on analytics-event="Button 2" analytics-category="Commands" class="btn btn-primary">Button 2</button> <!-- same as analytics-event="Button 3", because is inferred from innerText --> <button analytics-on analytics-category="Commands" class="btn btn-success">Button 3</button> <button analytics-on analytics-label="Button4 label" analytics-value="1" class="btn btn-info">Button 4</button> <hr> <p class="alert alert-success"> Open the network inspector in your browser, click any of the nav options or buttons above and you'll see the analytics request being executed. Then check <a class="alert-link" href="http://flurry.com">your Flurry dashboard</a>. </p> </div> <script> angular.module('sample', ['angulartics', 'angulartics.flurry']) .config(function ($routeProvider, $analyticsProvider) { $routeProvider .when('/', { templateUrl: '/samples/partials/root.tpl.html', controller: 'SampleCtrl' }) .when('/a', { templateUrl: '/samples/partials/a.tpl.html', controller: 'SampleCtrl' }) .when('/b', { templateUrl: '/samples/partials/b.tpl.html', controller: 'SampleCtrl' }) .when('/c', { templateUrl: '/samples/partials/c.tpl.html', controller: 'SampleCtrl' }) .otherwise({ redirectTo: '/' }); }) .controller('SampleCtrl', function () {}); </script> </body> </html>
gabe-untapt/angulartics
samples/flurry.html
HTML
mit
2,598
# Umbraco c# API reference ## Quick Links: ### [Umbraco.Core](api/Umbraco.Core.html) docs ### [Umbraco.Web](api/Umbraco.Web.html) docs
lars-erik/Umbraco-CMS
src/ApiDocs/index.md
Markdown
mit
138
package filenotify import ( "errors" "fmt" "os" "sync" "time" "github.com/Sirupsen/logrus" "gopkg.in/fsnotify.v1" ) var ( // errPollerClosed is returned when the poller is closed errPollerClosed = errors.New("poller is closed") // errNoSuchPoller is returned when trying to remove a watch that doesn't exist errNoSuchWatch = errors.New("poller does not exist") ) // watchWaitTime is the time to wait between file poll loops const watchWaitTime = 200 * time.Millisecond // filePoller is used to poll files for changes, especially in cases where fsnotify // can't be run (e.g. when inotify handles are exhausted) // filePoller satifies the FileWatcher interface type filePoller struct { // watches is the list of files currently being polled, close the associated channel to stop the watch watches map[string]chan struct{} // events is the channel to listen to for watch events events chan fsnotify.Event // errors is the channel to listen to for watch errors errors chan error // mu locks the poller for modification mu sync.Mutex // closed is used to specify when the poller has already closed closed bool } // Add adds a filename to the list of watches // once added the file is polled for changes in a separate goroutine func (w *filePoller) Add(name string) error { w.mu.Lock() defer w.mu.Unlock() if w.closed == true { return errPollerClosed } f, err := os.Open(name) if err != nil { return err } fi, err := os.Stat(name) if err != nil { return err } if w.watches == nil { w.watches = make(map[string]chan struct{}) } if _, exists := w.watches[name]; exists { return fmt.Errorf("watch exists") } chClose := make(chan struct{}) w.watches[name] = chClose go w.watch(f, fi, chClose) return nil } // Remove stops and removes watch with the specified name func (w *filePoller) Remove(name string) error { w.mu.Lock() defer w.mu.Unlock() return w.remove(name) } func (w *filePoller) remove(name string) error { if w.closed == true { return errPollerClosed } chClose, exists := w.watches[name] if !exists { return errNoSuchWatch } close(chClose) delete(w.watches, name) return nil } // Events returns the event channel // This is used for notifications on events about watched files func (w *filePoller) Events() <-chan fsnotify.Event { return w.events } // Errors returns the errors channel // This is used for notifications about errors on watched files func (w *filePoller) Errors() <-chan error { return w.errors } // Close closes the poller // All watches are stopped, removed, and the poller cannot be added to func (w *filePoller) Close() error { w.mu.Lock() defer w.mu.Unlock() if w.closed { return nil } w.closed = true for name := range w.watches { w.remove(name) delete(w.watches, name) } close(w.events) close(w.errors) return nil } // sendEvent publishes the specified event to the events channel func (w *filePoller) sendEvent(e fsnotify.Event, chClose <-chan struct{}) error { select { case w.events <- e: case <-chClose: return fmt.Errorf("closed") } return nil } // sendErr publishes the specified error to the errors channel func (w *filePoller) sendErr(e error, chClose <-chan struct{}) error { select { case w.errors <- e: case <-chClose: return fmt.Errorf("closed") } return nil } // watch is responsible for polling the specified file for changes // upon finding changes to a file or errors, sendEvent/sendErr is called func (w *filePoller) watch(f *os.File, lastFi os.FileInfo, chClose chan struct{}) { for { time.Sleep(watchWaitTime) select { case <-chClose: logrus.Debugf("watch for %s closed", f.Name()) return default: } fi, err := os.Stat(f.Name()) if err != nil { // if we got an error here and lastFi is not set, we can presume that nothing has changed // This should be safe since before `watch()` is called, a stat is performed, there is any error `watch` is not called if lastFi == nil { continue } // If it doesn't exist at this point, it must have been removed // no need to send the error here since this is a valid operation if os.IsNotExist(err) { if err := w.sendEvent(fsnotify.Event{Op: fsnotify.Remove, Name: f.Name()}, chClose); err != nil { return } lastFi = nil continue } // at this point, send the error if err := w.sendErr(err, chClose); err != nil { return } continue } if lastFi == nil { if err := w.sendEvent(fsnotify.Event{Op: fsnotify.Create, Name: fi.Name()}, chClose); err != nil { return } lastFi = fi continue } if fi.Mode() != lastFi.Mode() { if err := w.sendEvent(fsnotify.Event{Op: fsnotify.Chmod, Name: fi.Name()}, chClose); err != nil { return } lastFi = fi continue } if fi.ModTime() != lastFi.ModTime() || fi.Size() != lastFi.Size() { if err := w.sendEvent(fsnotify.Event{Op: fsnotify.Write, Name: fi.Name()}, chClose); err != nil { return } lastFi = fi continue } } }
ulrichSchreiner/dockmon
vendor/github.com/docker/docker/pkg/filenotify/poller.go
GO
mit
5,000
//===------------------------- chrono.cpp ---------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "chrono" #include <sys/time.h> //for gettimeofday and timeval #ifdef __APPLE__ #include <mach/mach_time.h> // mach_absolute_time, mach_timebase_info_data_t #else /* !__APPLE__ */ #include <cerrno> // errno #include <system_error> // __throw_system_error #include <time.h> // clock_gettime, CLOCK_MONOTONIC #endif // __APPLE__ _LIBCPP_BEGIN_NAMESPACE_STD namespace chrono { // system_clock const bool system_clock::is_steady; system_clock::time_point system_clock::now() _NOEXCEPT { timeval tv; gettimeofday(&tv, 0); return time_point(seconds(tv.tv_sec) + microseconds(tv.tv_usec)); } time_t system_clock::to_time_t(const time_point& t) _NOEXCEPT { return time_t(duration_cast<seconds>(t.time_since_epoch()).count()); } system_clock::time_point system_clock::from_time_t(time_t t) _NOEXCEPT { return system_clock::time_point(seconds(t)); } // steady_clock const bool steady_clock::is_steady; #ifdef __APPLE__ // mach_absolute_time() * MachInfo.numer / MachInfo.denom is the number of // nanoseconds since the computer booted up. MachInfo.numer and MachInfo.denom // are run time constants supplied by the OS. This clock has no relationship // to the Gregorian calendar. It's main use is as a high resolution timer. // MachInfo.numer / MachInfo.denom is often 1 on the latest equipment. Specialize // for that case as an optimization. #pragma GCC visibility push(hidden) static steady_clock::rep steady_simplified() { return static_cast<steady_clock::rep>(mach_absolute_time()); } static double compute_steady_factor() { mach_timebase_info_data_t MachInfo; mach_timebase_info(&MachInfo); return static_cast<double>(MachInfo.numer) / MachInfo.denom; } static steady_clock::rep steady_full() { static const double factor = compute_steady_factor(); return static_cast<steady_clock::rep>(mach_absolute_time() * factor); } typedef steady_clock::rep (*FP)(); static FP init_steady_clock() { mach_timebase_info_data_t MachInfo; mach_timebase_info(&MachInfo); if (MachInfo.numer == MachInfo.denom) return &steady_simplified; return &steady_full; } #pragma GCC visibility pop steady_clock::time_point steady_clock::now() _NOEXCEPT { static FP fp = init_steady_clock(); return time_point(duration(fp())); } #else // __APPLE__ // FIXME: We assume that clock_gettime(CLOCK_MONOTONIC) works on // non-apple systems. Instead, we should check _POSIX_TIMERS and // _POSIX_MONOTONIC_CLOCK and fall back to something else if those // don't exist. // Warning: If this is not truly steady, then it is non-conforming. It is // better for it to not exist and have the rest of libc++ use system_clock // instead. steady_clock::time_point steady_clock::now() _NOEXCEPT { struct timespec tp; if (0 != clock_gettime(CLOCK_MONOTONIC, &tp)) __throw_system_error(errno, "clock_gettime(CLOCK_MONOTONIC) failed"); return time_point(seconds(tp.tv_sec) + nanoseconds(tp.tv_nsec)); } #endif // __APPLE__ } _LIBCPP_END_NAMESPACE_STD
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/buildtools/third_party/libc++/trunk/src/chrono.cpp
C++
mit
3,416
/* Language: RenderMan RIB Author: Konstantin Evdokimenko <[email protected]> Contributors: Shuen-Huei Guan <[email protected]> */ function(hljs) { return { defaultMode: { keywords: 'ArchiveRecord AreaLightSource Atmosphere Attribute AttributeBegin AttributeEnd Basis ' + 'Begin Blobby Bound Clipping ClippingPlane Color ColorSamples ConcatTransform Cone ' + 'CoordinateSystem CoordSysTransform CropWindow Curves Cylinder DepthOfField Detail ' + 'DetailRange Disk Displacement Display End ErrorHandler Exposure Exterior Format ' + 'FrameAspectRatio FrameBegin FrameEnd GeneralPolygon GeometricApproximation Geometry ' + 'Hider Hyperboloid Identity Illuminate Imager Interior LightSource ' + 'MakeCubeFaceEnvironment MakeLatLongEnvironment MakeShadow MakeTexture Matte ' + 'MotionBegin MotionEnd NuPatch ObjectBegin ObjectEnd ObjectInstance Opacity Option ' + 'Orientation Paraboloid Patch PatchMesh Perspective PixelFilter PixelSamples ' + 'PixelVariance Points PointsGeneralPolygons PointsPolygons Polygon Procedural Projection ' + 'Quantize ReadArchive RelativeDetail ReverseOrientation Rotate Scale ScreenWindow ' + 'ShadingInterpolation ShadingRate Shutter Sides Skew SolidBegin SolidEnd Sphere ' + 'SubdivisionMesh Surface TextureCoordinates Torus Transform TransformBegin TransformEnd ' + 'TransformPoints Translate TrimCurve WorldBegin WorldEnd', illegal: '</', contains: [ hljs.HASH_COMMENT_MODE, hljs.C_NUMBER_MODE, hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE ] } }; }
sandro-k/sandro-k.github.io
talk/jug-goe-2015-06/bower_components/highlight.js/src/languages/rib.js
JavaScript
mit
1,664
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //----------------------------------------------------------------------- // </copyright> // <summary>Definition of ProjectTaskElement class.</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Xml; using System.Diagnostics; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Collections; using ProjectXmlUtilities = Microsoft.Build.Internal.ProjectXmlUtilities; namespace Microsoft.Build.Construction { /// <summary> /// ProjectTaskElement represents the Task element in the MSBuild project. /// </summary> [DebuggerDisplay("{Name} Condition={Condition} ContinueOnError={ContinueOnError} MSBuildRuntime={MSBuildRuntime} MSBuildArchitecture={MSBuildArchitecture} #Outputs={Count}")] public class ProjectTaskElement : ProjectElementContainer { /// <summary> /// The parameters (excepting condition and continue-on-error) /// </summary> private CopyOnWriteDictionary<string, Tuple<string, ElementLocation>> _parameters; /// <summary> /// Protection for the parameters cache /// </summary> private Object _locker = new Object(); /// <summary> /// Initialize a parented ProjectTaskElement /// </summary> internal ProjectTaskElement(XmlElementWithLocation xmlElement, ProjectTargetElement parent, ProjectRootElement containingProject) : base(xmlElement, parent, containingProject) { ErrorUtilities.VerifyThrowArgumentNull(parent, "parent"); } /// <summary> /// Initialize an unparented ProjectTaskElement /// </summary> private ProjectTaskElement(XmlElementWithLocation xmlElement, ProjectRootElement containingProject) : base(xmlElement, null, containingProject) { } /// <summary> /// Gets or sets the continue on error value. /// Returns empty string if it is not present. /// Removes the attribute if the value to set is empty. /// </summary> public string ContinueOnError { [DebuggerStepThrough] get { return ProjectXmlUtilities.GetAttributeValue(XmlElement, XMakeAttributes.continueOnError); } [DebuggerStepThrough] set { ProjectXmlUtilities.SetOrRemoveAttribute(XmlElement, XMakeAttributes.continueOnError, value); MarkDirty("Set task ContinueOnError {0}", value); } } /// <summary> /// Gets or sets the runtime value for the task. /// Returns empty string if it is not present. /// Removes the attribute if the value to set is empty. /// </summary> public string MSBuildRuntime { [DebuggerStepThrough] get { return ProjectXmlUtilities.GetAttributeValue(XmlElement, XMakeAttributes.msbuildRuntime); } [DebuggerStepThrough] set { ProjectXmlUtilities.SetOrRemoveAttribute(XmlElement, XMakeAttributes.msbuildRuntime, value); MarkDirty("Set task MSBuildRuntime {0}", value); } } /// <summary> /// Gets or sets the architecture value for the task. /// Returns empty string if it is not present. /// Removes the attribute if the value to set is empty. /// </summary> public string MSBuildArchitecture { [DebuggerStepThrough] get { return ProjectXmlUtilities.GetAttributeValue(XmlElement, XMakeAttributes.msbuildArchitecture); } [DebuggerStepThrough] set { ProjectXmlUtilities.SetOrRemoveAttribute(XmlElement, XMakeAttributes.msbuildArchitecture, value); MarkDirty("Set task MSBuildArchitecture {0}", value); } } /// <summary> /// Gets the task name /// </summary> public string Name { get { return XmlElement.Name; } } /// <summary> /// Gets any output children. /// </summary> public ICollection<ProjectOutputElement> Outputs { get { return new Microsoft.Build.Collections.ReadOnlyCollection<ProjectOutputElement> ( new FilteringEnumerable<ProjectElement, ProjectOutputElement>(Children) ); } } /// <summary> /// Enumerable over the unevaluated parameters on the task. /// Attributes with their own properties, such as ContinueOnError, are not included in this collection. /// If parameters differ only by case only the last one will be returned. MSBuild uses only this one. /// Hosts can still remove the other parameters by using RemoveAllParameters(). /// </summary> public IDictionary<string, string> Parameters { get { lock (_locker) { EnsureParametersInitialized(); Dictionary<string, string> parametersClone = new Dictionary<string, string>(_parameters.Count, StringComparer.OrdinalIgnoreCase); foreach (var entry in _parameters) { parametersClone[entry.Key] = entry.Value.Item1; } return new ReadOnlyDictionary<string, string>(parametersClone); } } } /// <summary> /// Enumerable over the locations of parameters on the task. /// Condition and ContinueOnError, which have their own properties, are not included in this collection. /// If parameters differ only by case only the last one will be returned. MSBuild uses only this one. /// Hosts can still remove the other parameters by using RemoveAllParameters(). /// </summary> public IEnumerable<KeyValuePair<string, ElementLocation>> ParameterLocations { get { lock (_locker) { EnsureParametersInitialized(); var parameterLocations = new List<KeyValuePair<string, ElementLocation>>(); foreach (var entry in _parameters) { parameterLocations.Add(new KeyValuePair<string, ElementLocation>(entry.Key, entry.Value.Item2)); } return parameterLocations; } } } /// <summary> /// Location of the "ContinueOnError" attribute on this element, if any. /// If there is no such attribute, returns null; /// </summary> public ElementLocation ContinueOnErrorLocation { get { return XmlElement.GetAttributeLocation(XMakeAttributes.continueOnError); } } /// <summary> /// Location of the "MSBuildRuntime" attribute on this element, if any. /// If there is no such attribute, returns null; /// </summary> public ElementLocation MSBuildRuntimeLocation { get { return XmlElement.GetAttributeLocation(XMakeAttributes.msbuildRuntime); } } /// <summary> /// Location of the "MSBuildArchitecture" attribute on this element, if any. /// If there is no such attribute, returns null; /// </summary> public ElementLocation MSBuildArchitectureLocation { get { return XmlElement.GetAttributeLocation(XMakeAttributes.msbuildArchitecture); } } /// <summary> /// Retrieves a copy of the parameters as used during evaluation. /// </summary> internal CopyOnWriteDictionary<string, Tuple<string, ElementLocation>> ParametersForEvaluation { get { lock (_locker) { EnsureParametersInitialized(); return _parameters.Clone(); // copy on write! } } } /// <summary> /// Convenience method to add an Output Item to this task. /// Adds after the last child. /// </summary> public ProjectOutputElement AddOutputItem(string taskParameter, string itemType) { ErrorUtilities.VerifyThrowArgumentLength(taskParameter, "taskParameter"); ErrorUtilities.VerifyThrowArgumentLength(itemType, "itemType"); return AddOutputItem(taskParameter, itemType, null); } /// <summary> /// Convenience method to add a conditioned Output Item to this task. /// Adds after the last child. /// </summary> public ProjectOutputElement AddOutputItem(string taskParameter, string itemType, string condition) { ProjectOutputElement outputItem = ContainingProject.CreateOutputElement(taskParameter, itemType, null); if (condition != null) { outputItem.Condition = condition; } AppendChild(outputItem); return outputItem; } /// <summary> /// Convenience method to add an Output Property to this task. /// Adds after the last child. /// </summary> public ProjectOutputElement AddOutputProperty(string taskParameter, string propertyName) { ErrorUtilities.VerifyThrowArgumentLength(taskParameter, "taskParameter"); ErrorUtilities.VerifyThrowArgumentLength(propertyName, "propertyName"); return AddOutputProperty(taskParameter, propertyName, null); } /// <summary> /// Convenience method to add a conditioned Output Property to this task. /// Adds after the last child. /// </summary> public ProjectOutputElement AddOutputProperty(string taskParameter, string propertyName, string condition) { ProjectOutputElement outputProperty = ContainingProject.CreateOutputElement(taskParameter, null, propertyName); if (condition != null) { outputProperty.Condition = condition; } AppendChild(outputProperty); return outputProperty; } /// <summary> /// Gets the value of the parameter with the specified name, /// or empty string if it is not present. /// </summary> public string GetParameter(string name) { lock (_locker) { ErrorUtilities.VerifyThrowArgumentLength(name, "name"); EnsureParametersInitialized(); Tuple<string, ElementLocation> parameter; if (_parameters.TryGetValue(name, out parameter)) { return parameter.Item1; } return String.Empty; } } /// <summary> /// Adds (or modifies the value of) a parameter on this task /// </summary> public void SetParameter(string name, string unevaluatedValue) { lock (_locker) { ErrorUtilities.VerifyThrowArgumentLength(name, "name"); ErrorUtilities.VerifyThrowArgumentNull(unevaluatedValue, "unevaluatedValue"); ErrorUtilities.VerifyThrowArgument(!XMakeAttributes.IsSpecialTaskAttribute(name), "CannotAccessKnownAttributes", name); _parameters = null; XmlElement.SetAttribute(name, unevaluatedValue); MarkDirty("Set task parameter {0}", name); } } /// <summary> /// Removes any parameter on this task with the specified name. /// If there is no such parameter, does nothing. /// </summary> public void RemoveParameter(string name) { lock (_locker) { _parameters = null; XmlElement.RemoveAttribute(name); MarkDirty("Remove task parameter {0}", name); } } /// <summary> /// Removes all parameters from the task. /// Does not remove any "special" parameters: ContinueOnError, Condition, etc. /// </summary> public void RemoveAllParameters() { lock (_locker) { _parameters = null; foreach (XmlAttribute attribute in XmlElement.Attributes) { if (!XMakeAttributes.IsSpecialTaskAttribute(attribute.Name)) { XmlElement.RemoveAttributeNode(attribute); } } MarkDirty("Remove all task parameters on {0}", Name); } } /// <inheritdoc /> public override void CopyFrom(ProjectElement element) { base.CopyFrom(element); // Clear caching fields _parameters = null; } /// <summary> /// Creates an unparented ProjectTaskElement, wrapping an unparented XmlElement. /// Caller should then ensure the element is added to the XmlDocument in the appropriate location. /// </summary> /// <remarks> /// Any legal XML element name is allowed. We can't easily verify if the name is a legal XML element name, /// so this will specifically throw XmlException if it isn't. /// </remarks> internal static ProjectTaskElement CreateDisconnected(string name, ProjectRootElement containingProject) { ErrorUtilities.VerifyThrowArgumentLength(name, "name"); XmlElementWithLocation element = containingProject.CreateElement(name); return new ProjectTaskElement(element, containingProject); } /// <summary> /// Overridden to verify that the potential parent and siblings /// are acceptable. Throws InvalidOperationException if they are not. /// </summary> internal override void VerifyThrowInvalidOperationAcceptableLocation(ProjectElementContainer parent, ProjectElement previousSibling, ProjectElement nextSibling) { ErrorUtilities.VerifyThrowInvalidOperation(parent is ProjectTargetElement, "OM_CannotAcceptParent"); } /// <inheritdoc /> protected override ProjectElement CreateNewInstance(ProjectRootElement owner) { return owner.CreateTaskElement(this.Name); } /// <summary> /// Initialize parameters cache. /// Must be called within the lock. /// </summary> private void EnsureParametersInitialized() { if (_parameters == null) { _parameters = new CopyOnWriteDictionary<string, Tuple<string, ElementLocation>>(XmlElement.Attributes.Count, StringComparer.OrdinalIgnoreCase); foreach (XmlAttributeWithLocation attribute in XmlElement.Attributes) { if (!XMakeAttributes.IsSpecialTaskAttribute(attribute.Name)) { // By pulling off and caching the Location early here, it becomes frozen for the life of this object. // That means that if the name of the file is changed after first load (possibly from null) it will // remain the old value here. Correctly, this should cache the attribute not the location. Fixing // that will need profiling, though, as this cache was added for performance. _parameters[attribute.Name] = new Tuple<string, ElementLocation>(attribute.Value, attribute.Location); } } } } } }
luiseduardohdbackup/msbuild
src/XMakeBuildEngine/Construction/ProjectTaskElement.cs
C#
mit
16,333
/** * Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ /* * generated by Xtext */ package org.eclipse.smarthome.model.script.ui; import org.eclipse.smarthome.model.script.ui.contentassist.ActionEObjectHoverProvider; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.eclipse.xtext.ui.editor.hover.IEObjectHoverProvider; /** * Use this class to register components to be used within the IDE. */ @SuppressWarnings("restriction") public class ScriptUiModule extends org.eclipse.smarthome.model.script.ui.AbstractScriptUiModule { public ScriptUiModule(AbstractUIPlugin plugin) { super(plugin); } @Override public Class<? extends IEObjectHoverProvider> bindIEObjectHoverProvider() { return ActionEObjectHoverProvider.class; } }
markusmazurczak/smarthome
bundles/model/org.eclipse.smarthome.model.script.ui/src/org/eclipse/smarthome/model/script/ui/ScriptUiModule.java
Java
epl-1.0
1,044
/* linux/arch/arm/mach-exynos4/init.c * * Copyright (c) 2010 Samsung Electronics Co., Ltd. * http://www.samsung.com/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/serial_core.h> #include <plat/cpu.h> #include <plat/devs.h> #include <plat/regs-serial.h> static struct s3c24xx_uart_clksrc exynos4_serial_clocks[] = { [0] = { .name = "uclk1", .divisor = 1, .min_baud = 0, .max_baud = 0, }, }; /* uart registration process */ void __init exynos4_common_init_uarts(struct s3c2410_uartcfg *cfg, int no) { struct s3c2410_uartcfg *tcfg = cfg; u32 ucnt; for (ucnt = 0; ucnt < no; ucnt++, tcfg++) { if (!tcfg->clocks) { tcfg->has_fracval = 1; tcfg->clocks = exynos4_serial_clocks; tcfg->clocks_size = ARRAY_SIZE(exynos4_serial_clocks); } } s3c24xx_init_uartdevs("s5pv210-uart", s5p_uart_resources, cfg, no); }
chaoling/test123
linux-2.6.39/arch/arm/mach-exynos4/init.c
C
gpl-2.0
1,002
/* * include/asm-parisc/serial.h */ #include <linux/config.h> #include <asm/gsc.h> /* * This assumes you have a 7.272727 MHz clock for your UART. * The documentation implies a 40Mhz clock, and elsewhere a 7Mhz clock * Clarified: 7.2727MHz on LASI. Not yet clarified for DINO */ #define LASI_BASE_BAUD ( 7272727 / 16 ) #define BASE_BAUD LASI_BASE_BAUD #ifdef CONFIG_SERIAL_DETECT_IRQ #define STD_COM_FLAGS (ASYNC_BOOT_AUTOCONF | ASYNC_SKIP_TEST | ASYNC_AUTO_IRQ) #define STD_COM4_FLAGS (ASYNC_BOOT_AUTOCONF | ASYNC_AUTO_IRQ) #else #define STD_COM_FLAGS (ASYNC_BOOT_AUTOCONF | ASYNC_SKIP_TEST) #define STD_COM4_FLAGS ASYNC_BOOT_AUTOCONF #endif #ifdef CONFIG_SERIAL_MANY_PORTS #define FOURPORT_FLAGS ASYNC_FOURPORT #define ACCENT_FLAGS 0 #define BOCA_FLAGS 0 #define HUB6_FLAGS 0 #define RS_TABLE_SIZE 64 #else #define RS_TABLE_SIZE 4 #endif /* * The base is relative to the LASI base. We can fix that * up later. We could also virtually map LASI so that we get * nice constants all over our kernel... */ #define STD_SERIAL_PORT_DEFNS \ /* UART CLK PORT IRQ FLAGS */ \ { 0, LASI_BASE_BAUD, -1, 4, ASYNC_SKIP_TEST, 0, PORT_UNKNOWN,}, /* ttyS0 */ #define SERIAL_PORT_DFNS \ STD_SERIAL_PORT_DEFNS
sensysnetworks/uClinux
linux-2.4.x/include/asm-parisc/serial.h
C
gpl-2.0
1,236
/* Copyright (c) 2003, 2005 MySQL AB Use is subject to license terms This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ //#define DEBUG_ON extern "C" { #include "user_transaction.h" }; #include "macros.h" #include "ndb_schema.hpp" #include "ndb_error.hpp" #include <time.h> #include <NdbApi.hpp> /** * Transaction 1 - T1 * * Update location and changed by/time on a subscriber * * Input: * SubscriberNumber, * Location, * ChangedBy, * ChangedTime * * Output: */ int T1(void * obj, const SubscriberNumber number, const Location new_location, const ChangedBy changed_by, const ChangedTime changed_time, BenchmarkTime * transaction_time){ Ndb * pNDB = (Ndb *) obj; DEBUG2("T1(%.*s):\n", SUBSCRIBER_NUMBER_LENGTH, number); BenchmarkTime start; get_time(&start); int check; NdbRecAttr * check2; NdbConnection * MyTransaction = pNDB->startTransaction(); if (MyTransaction == NULL) error_handler("T1-1: startTranscation", pNDB->getNdbErrorString(), 0); NdbOperation *MyOperation = MyTransaction->getNdbOperation(SUBSCRIBER_TABLE); CHECK_NULL(MyOperation, "T1: getNdbOperation", MyTransaction); check = MyOperation->updateTuple(); CHECK_MINUS_ONE(check, "T1: updateTuple", MyTransaction); check = MyOperation->equal(IND_SUBSCRIBER_NUMBER, number); CHECK_MINUS_ONE(check, "T1: equal subscriber", MyTransaction); check = MyOperation->setValue(IND_SUBSCRIBER_LOCATION, (char *)&new_location); CHECK_MINUS_ONE(check, "T1: setValue location", MyTransaction); check = MyOperation->setValue(IND_SUBSCRIBER_CHANGED_BY, changed_by); CHECK_MINUS_ONE(check, "T1: setValue changed_by", MyTransaction); check = MyOperation->setValue(IND_SUBSCRIBER_CHANGED_TIME, changed_time); CHECK_MINUS_ONE(check, "T1: setValue changed_time", MyTransaction); check = MyTransaction->execute( Commit ); CHECK_MINUS_ONE(check, "T1: Commit", MyTransaction); pNDB->closeTransaction(MyTransaction); get_time(transaction_time); time_diff(transaction_time, &start); return 0; } /** * Transaction 2 - T2 * * Read from Subscriber: * * Input: * SubscriberNumber * * Output: * Location * Changed by * Changed Timestamp * Name */ int T2(void * obj, const SubscriberNumber number, Location * readLocation, ChangedBy changed_by, ChangedTime changed_time, SubscriberName subscriberName, BenchmarkTime * transaction_time){ Ndb * pNDB = (Ndb *) obj; DEBUG2("T2(%.*s):\n", SUBSCRIBER_NUMBER_LENGTH, number); BenchmarkTime start; get_time(&start); int check; NdbRecAttr * check2; NdbConnection * MyTransaction = pNDB->startTransaction(); if (MyTransaction == NULL) error_handler("T2-1: startTranscation", pNDB->getNdbErrorString(), 0); NdbOperation *MyOperation= MyTransaction->getNdbOperation(SUBSCRIBER_TABLE); CHECK_NULL(MyOperation, "T2: getNdbOperation", MyTransaction); check = MyOperation->readTuple(); CHECK_MINUS_ONE(check, "T2: readTuple", MyTransaction); check = MyOperation->equal(IND_SUBSCRIBER_NUMBER, number); CHECK_MINUS_ONE(check, "T2: equal subscriber", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_LOCATION, (char *)readLocation); CHECK_NULL(check2, "T2: getValue location", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_CHANGED_BY, changed_by); CHECK_NULL(check2, "T2: getValue changed_by", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_CHANGED_TIME, changed_time); CHECK_NULL(check2, "T2: getValue changed_time", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_NAME, subscriberName); CHECK_NULL(check2, "T2: getValue name", MyTransaction); check = MyTransaction->execute( Commit ); CHECK_MINUS_ONE(check, "T2: Commit", MyTransaction); pNDB->closeTransaction(MyTransaction); get_time(transaction_time); time_diff(transaction_time, &start); return 0; } /** * Transaction 3 - T3 * * Read session details * * Input: * SubscriberNumber * ServerId * ServerBit * * Output: * BranchExecuted * SessionDetails * ChangedBy * ChangedTime * Location */ int T3(void * obj, const SubscriberNumber inNumber, const SubscriberSuffix inSuffix, const ServerId inServerId, const ServerBit inServerBit, SessionDetails outSessionDetails, ChangedBy outChangedBy, ChangedTime outChangedTime, Location * outLocation, BranchExecuted * outBranchExecuted, BenchmarkTime * outTransactionTime){ Ndb * pNDB = (Ndb *) obj; GroupId groupId; ActiveSessions sessions; Permission permission; BenchmarkTime start; get_time(&start); int check; NdbRecAttr * check2; NdbConnection * MyTransaction = pNDB->startTransaction(); if (MyTransaction == NULL) error_handler("T3-1: startTranscation", pNDB->getNdbErrorString(), 0); NdbOperation *MyOperation= MyTransaction->getNdbOperation(SUBSCRIBER_TABLE); CHECK_NULL(MyOperation, "T3-1: getNdbOperation", MyTransaction); check = MyOperation->readTuple(); CHECK_MINUS_ONE(check, "T3-1: readTuple", MyTransaction); check = MyOperation->equal(IND_SUBSCRIBER_NUMBER, inNumber); CHECK_MINUS_ONE(check, "T3-1: equal subscriber", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_LOCATION, (char *)outLocation); CHECK_NULL(check2, "T3-1: getValue location", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_CHANGED_BY, outChangedBy); CHECK_NULL(check2, "T3-1: getValue changed_by", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_CHANGED_TIME, outChangedTime); CHECK_NULL(check2, "T3-1: getValue changed_time", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_GROUP, (char *)&groupId); CHECK_NULL(check2, "T3-1: getValue group", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_SESSIONS, (char *)&sessions); CHECK_NULL(check2, "T3-1: getValue sessions", MyTransaction); check = MyTransaction->execute( NoCommit ); CHECK_MINUS_ONE(check, "T3-1: NoCommit", MyTransaction); /* Operation 2 */ MyOperation = MyTransaction->getNdbOperation(GROUP_TABLE); CHECK_NULL(MyOperation, "T3-2: getNdbOperation", MyTransaction); check = MyOperation->readTuple(); CHECK_MINUS_ONE(check, "T3-2: readTuple", MyTransaction); check = MyOperation->equal(IND_GROUP_ID, (char*)&groupId); CHECK_MINUS_ONE(check, "T3-2: equal group", MyTransaction); check2 = MyOperation->getValue(IND_GROUP_ALLOW_READ, (char *)&permission); CHECK_NULL(check2, "T3-2: getValue allow_read", MyTransaction); check = MyTransaction->execute( NoCommit ); CHECK_MINUS_ONE(check, "T3-2: NoCommit", MyTransaction); DEBUG3("T3(%.*s, %.2d): ", SUBSCRIBER_NUMBER_LENGTH, inNumber, inServerId); if(((permission & inServerBit) == inServerBit) && ((sessions & inServerBit) == inServerBit)){ DEBUG("reading - "); /* Operation 3 */ MyOperation = MyTransaction->getNdbOperation(SESSION_TABLE); CHECK_NULL(MyOperation, "T3-3: getNdbOperation", MyTransaction); check = MyOperation->simpleRead(); CHECK_MINUS_ONE(check, "T3-3: readTuple", MyTransaction); check = MyOperation->equal(IND_SESSION_SUBSCRIBER, (char*)inNumber); CHECK_MINUS_ONE(check, "T3-3: equal number", MyTransaction); check = MyOperation->equal(IND_SESSION_SERVER, (char*)&inServerId); CHECK_MINUS_ONE(check, "T3-3: equal server id", MyTransaction); check2 = MyOperation->getValue(IND_SESSION_DATA, (char *)outSessionDetails); CHECK_NULL(check2, "T3-3: getValue session details", MyTransaction); /* Operation 4 */ MyOperation = MyTransaction->getNdbOperation(SERVER_TABLE); CHECK_NULL(MyOperation, "T3-4: getNdbOperation", MyTransaction); check = MyOperation->interpretedUpdateTuple(); CHECK_MINUS_ONE(check, "T3-4: interpretedUpdateTuple", MyTransaction); check = MyOperation->equal(IND_SERVER_ID, (char*)&inServerId); CHECK_MINUS_ONE(check, "T3-4: equal serverId", MyTransaction); check = MyOperation->equal(IND_SERVER_SUBSCRIBER_SUFFIX, (char*)inSuffix); CHECK_MINUS_ONE(check, "T3-4: equal suffix", MyTransaction); check = MyOperation->incValue(IND_SERVER_READS, (uint32)1); CHECK_MINUS_ONE(check, "T3-4: inc value", MyTransaction); (* outBranchExecuted) = 1; } else { (* outBranchExecuted) = 0; } DEBUG("commit..."); check = MyTransaction->execute( Commit ); CHECK_MINUS_ONE(check, "T3: Commit", MyTransaction); pNDB->closeTransaction(MyTransaction); DEBUG("done\n"); get_time(outTransactionTime); time_diff(outTransactionTime, &start); return 0; } /** * Transaction 4 - T4 * * Create session * * Input: * SubscriberNumber * ServerId * ServerBit * SessionDetails, * DoRollback * Output: * ChangedBy * ChangedTime * Location * BranchExecuted */ int T4(void * obj, const SubscriberNumber inNumber, const SubscriberSuffix inSuffix, const ServerId inServerId, const ServerBit inServerBit, const SessionDetails inSessionDetails, ChangedBy outChangedBy, ChangedTime outChangedTime, Location * outLocation, DoRollback inDoRollback, BranchExecuted * outBranchExecuted, BenchmarkTime * outTransactionTime){ Ndb * pNDB = (Ndb *) obj; GroupId groupId; ActiveSessions sessions; Permission permission; BenchmarkTime start; get_time(&start); int check; NdbRecAttr * check2; NdbConnection * MyTransaction = pNDB->startTransaction(); if (MyTransaction == NULL) error_handler("T4-1: startTranscation", pNDB->getNdbErrorString(), 0); NdbOperation *MyOperation= MyTransaction->getNdbOperation(SUBSCRIBER_TABLE); CHECK_NULL(MyOperation, "T4-1: getNdbOperation", MyTransaction); check = MyOperation->interpretedUpdateTuple(); CHECK_MINUS_ONE(check, "T4-1: readTuple", MyTransaction); check = MyOperation->equal(IND_SUBSCRIBER_NUMBER, inNumber); CHECK_MINUS_ONE(check, "T4-1: equal subscriber", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_LOCATION, (char *)outLocation); CHECK_NULL(check2, "T4-1: getValue location", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_CHANGED_BY, outChangedBy); CHECK_NULL(check2, "T4-1: getValue changed_by", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_CHANGED_TIME, outChangedTime); CHECK_NULL(check2, "T4-1: getValue changed_time", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_GROUP, (char *)&groupId); CHECK_NULL(check2, "T4-1: getValue group", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_SESSIONS, (char *)&sessions); CHECK_NULL(check2, "T4-1: getValue sessions", MyTransaction); check = MyOperation->incValue(IND_SUBSCRIBER_SESSIONS, (uint32)inServerBit); CHECK_MINUS_ONE(check, "T4-4: inc value", MyTransaction); check = MyTransaction->execute( NoCommit ); CHECK_MINUS_ONE(check, "T4-1: NoCommit", MyTransaction); /* Operation 2 */ MyOperation = MyTransaction->getNdbOperation(GROUP_TABLE); CHECK_NULL(MyOperation, "T4-2: getNdbOperation", MyTransaction); check = MyOperation->readTuple(); CHECK_MINUS_ONE(check, "T4-2: readTuple", MyTransaction); check = MyOperation->equal(IND_GROUP_ID, (char*)&groupId); CHECK_MINUS_ONE(check, "T4-2: equal group", MyTransaction); check2 = MyOperation->getValue(IND_GROUP_ALLOW_INSERT, (char *)&permission); CHECK_NULL(check2, "T4-2: getValue allow_insert", MyTransaction); check = MyTransaction->execute( NoCommit ); CHECK_MINUS_ONE(check, "T4-2: NoCommit", MyTransaction); DEBUG3("T4(%.*s, %.2d): ", SUBSCRIBER_NUMBER_LENGTH, inNumber, inServerId); if(((permission & inServerBit) == inServerBit) && ((sessions & inServerBit) == 0)){ DEBUG("inserting - "); /* Operation 3 */ MyOperation = MyTransaction->getNdbOperation(SESSION_TABLE); CHECK_NULL(MyOperation, "T4-3: getNdbOperation", MyTransaction); check = MyOperation->insertTuple(); CHECK_MINUS_ONE(check, "T4-3: insertTuple", MyTransaction); check = MyOperation->equal(IND_SESSION_SUBSCRIBER, (char*)inNumber); CHECK_MINUS_ONE(check, "T4-3: equal number", MyTransaction); check = MyOperation->equal(IND_SESSION_SERVER, (char*)&inServerId); CHECK_MINUS_ONE(check, "T4-3: equal server id", MyTransaction); check = MyOperation->setValue(SESSION_DATA, (char *)inSessionDetails); CHECK_MINUS_ONE(check, "T4-3: setValue session details", MyTransaction); /* Operation 4 */ /* Operation 5 */ MyOperation = MyTransaction->getNdbOperation(SERVER_TABLE); CHECK_NULL(MyOperation, "T4-5: getNdbOperation", MyTransaction); check = MyOperation->interpretedUpdateTuple(); CHECK_MINUS_ONE(check, "T4-5: interpretedUpdateTuple", MyTransaction); check = MyOperation->equal(IND_SERVER_ID, (char*)&inServerId); CHECK_MINUS_ONE(check, "T4-5: equal serverId", MyTransaction); check = MyOperation->equal(IND_SERVER_SUBSCRIBER_SUFFIX, (char*)inSuffix); CHECK_MINUS_ONE(check, "T4-5: equal suffix", MyTransaction); check = MyOperation->incValue(IND_SERVER_INSERTS, (uint32)1); CHECK_MINUS_ONE(check, "T4-5: inc value", MyTransaction); (* outBranchExecuted) = 1; } else { DEBUG1("%s", ((permission & inServerBit) ? "permission - " : "no permission - ")); DEBUG1("%s", ((sessions & inServerBit) ? "in session - " : "no in session - ")); (* outBranchExecuted) = 0; } if(!inDoRollback && (* outBranchExecuted)){ DEBUG("commit\n"); check = MyTransaction->execute( Commit ); CHECK_MINUS_ONE(check, "T4: Commit", MyTransaction); } else { DEBUG("rollback\n"); check = MyTransaction->execute(Rollback); CHECK_MINUS_ONE(check, "T4:Rollback", MyTransaction); } pNDB->closeTransaction(MyTransaction); get_time(outTransactionTime); time_diff(outTransactionTime, &start); return 0; } /** * Transaction 5 - T5 * * Delete session * * Input: * SubscriberNumber * ServerId * ServerBit * DoRollback * Output: * ChangedBy * ChangedTime * Location * BranchExecuted */ int T5(void * obj, const SubscriberNumber inNumber, const SubscriberSuffix inSuffix, const ServerId inServerId, const ServerBit inServerBit, ChangedBy outChangedBy, ChangedTime outChangedTime, Location * outLocation, DoRollback inDoRollback, BranchExecuted * outBranchExecuted, BenchmarkTime * outTransactionTime){ Ndb * pNDB = (Ndb *) obj; NdbConnection * MyTransaction = 0; NdbOperation * MyOperation = 0; GroupId groupId; ActiveSessions sessions; Permission permission; BenchmarkTime start; get_time(&start); int check; NdbRecAttr * check2; MyTransaction = pNDB->startTransaction(); if (MyTransaction == NULL) error_handler("T5-1: startTranscation", pNDB->getNdbErrorString(), 0); MyOperation= MyTransaction->getNdbOperation(SUBSCRIBER_TABLE); CHECK_NULL(MyOperation, "T5-1: getNdbOperation", MyTransaction); check = MyOperation->interpretedUpdateTuple(); CHECK_MINUS_ONE(check, "T5-1: readTuple", MyTransaction); check = MyOperation->equal(IND_SUBSCRIBER_NUMBER, inNumber); CHECK_MINUS_ONE(check, "T5-1: equal subscriber", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_LOCATION, (char *)outLocation); CHECK_NULL(check2, "T5-1: getValue location", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_CHANGED_BY, outChangedBy); CHECK_NULL(check2, "T5-1: getValue changed_by", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_CHANGED_TIME, outChangedTime); CHECK_NULL(check2, "T5-1: getValue changed_time", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_GROUP, (char *)&groupId); CHECK_NULL(check2, "T5-1: getValue group", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_SESSIONS, (char *)&sessions); CHECK_NULL(check2, "T5-1: getValue sessions", MyTransaction); check = MyOperation->subValue(IND_SUBSCRIBER_SESSIONS, (uint32)inServerBit); CHECK_MINUS_ONE(check, "T5-4: dec value", MyTransaction); check = MyTransaction->execute( NoCommit ); CHECK_MINUS_ONE(check, "T5-1: NoCommit", MyTransaction); /* Operation 2 */ MyOperation = MyTransaction->getNdbOperation(GROUP_TABLE); CHECK_NULL(MyOperation, "T5-2: getNdbOperation", MyTransaction); check = MyOperation->readTuple(); CHECK_MINUS_ONE(check, "T5-2: readTuple", MyTransaction); check = MyOperation->equal(IND_GROUP_ID, (char*)&groupId); CHECK_MINUS_ONE(check, "T5-2: equal group", MyTransaction); check2 = MyOperation->getValue(IND_GROUP_ALLOW_DELETE, (char *)&permission); CHECK_NULL(check2, "T5-2: getValue allow_delete", MyTransaction); check = MyTransaction->execute( NoCommit ); CHECK_MINUS_ONE(check, "T5-2: NoCommit", MyTransaction); DEBUG3("T5(%.*s, %.2d): ", SUBSCRIBER_NUMBER_LENGTH, inNumber, inServerId); if(((permission & inServerBit) == inServerBit) && ((sessions & inServerBit) == inServerBit)){ DEBUG("deleting - "); /* Operation 3 */ MyOperation = MyTransaction->getNdbOperation(SESSION_TABLE); CHECK_NULL(MyOperation, "T5-3: getNdbOperation", MyTransaction); check = MyOperation->deleteTuple(); CHECK_MINUS_ONE(check, "T5-3: deleteTuple", MyTransaction); check = MyOperation->equal(IND_SESSION_SUBSCRIBER, (char*)inNumber); CHECK_MINUS_ONE(check, "T5-3: equal number", MyTransaction); check = MyOperation->equal(IND_SESSION_SERVER, (char*)&inServerId); CHECK_MINUS_ONE(check, "T5-3: equal server id", MyTransaction); /* Operation 4 */ /* Operation 5 */ MyOperation = MyTransaction->getNdbOperation(SERVER_TABLE); CHECK_NULL(MyOperation, "T5-5: getNdbOperation", MyTransaction); check = MyOperation->interpretedUpdateTuple(); CHECK_MINUS_ONE(check, "T5-5: interpretedUpdateTuple", MyTransaction); check = MyOperation->equal(IND_SERVER_ID, (char*)&inServerId); CHECK_MINUS_ONE(check, "T5-5: equal serverId", MyTransaction); check = MyOperation->equal(IND_SERVER_SUBSCRIBER_SUFFIX, (char*)inSuffix); CHECK_MINUS_ONE(check, "T5-5: equal suffix", MyTransaction); check = MyOperation->incValue(IND_SERVER_DELETES, (uint32)1); CHECK_MINUS_ONE(check, "T5-5: inc value", MyTransaction); (* outBranchExecuted) = 1; } else { DEBUG1("%s", ((permission & inServerBit) ? "permission - " : "no permission - ")); DEBUG1("%s", ((sessions & inServerBit) ? "in session - " : "no in session - ")); (* outBranchExecuted) = 0; } if(!inDoRollback && (* outBranchExecuted)){ DEBUG("commit\n"); check = MyTransaction->execute( Commit ); CHECK_MINUS_ONE(check, "T5: Commit", MyTransaction); } else { DEBUG("rollback\n"); check = MyTransaction->execute(Rollback); CHECK_MINUS_ONE(check, "T5:Rollback", MyTransaction); } pNDB->closeTransaction(MyTransaction); get_time(outTransactionTime); time_diff(outTransactionTime, &start); return 0; }
fengshao0907/mysql
storage/ndb/test/ndbapi/bench/ndb_user_transaction5.cpp
C++
gpl-2.0
21,054
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/STIX/General/BoldItalic/BoxDrawing.js * * Copyright (c) 2009-2013 The MathJax Consortium * * 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. * */ MathJax.Hub.Insert( MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['STIXGeneral-bold-italic'], { 0x2500: [340,-267,708,-11,719], // BOX DRAWINGS LIGHT HORIZONTAL 0x2502: [910,303,696,312,385], // BOX DRAWINGS LIGHT VERTICAL 0x250C: [340,303,708,318,720], // BOX DRAWINGS LIGHT DOWN AND RIGHT 0x2510: [340,303,708,-11,390], // BOX DRAWINGS LIGHT DOWN AND LEFT 0x2514: [910,-267,708,318,720], // BOX DRAWINGS LIGHT UP AND RIGHT 0x2518: [910,-267,708,-11,390], // BOX DRAWINGS LIGHT UP AND LEFT 0x251C: [910,303,708,318,720], // BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x2524: [910,303,708,-11,390], // BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x252C: [340,303,708,-11,719], // BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x2534: [910,-267,708,-11,719], // BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x253C: [910,303,708,-11,719], // BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x2550: [433,-174,708,-11,719], // BOX DRAWINGS DOUBLE HORIZONTAL 0x2551: [910,303,708,225,484], // BOX DRAWINGS DOUBLE VERTICAL 0x2552: [433,303,708,318,720], // BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x2553: [340,303,708,225,720], // BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE 0x2554: [433,303,708,225,719], // BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x2555: [433,303,708,-11,390], // BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE 0x2556: [340,303,708,-11,483], // BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE 0x2557: [433,303,708,-11,483], // BOX DRAWINGS DOUBLE DOWN AND LEFT 0x2558: [910,-174,708,318,720], // BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE 0x2559: [910,-267,708,225,720], // BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE 0x255A: [910,-174,708,225,719], // BOX DRAWINGS DOUBLE UP AND RIGHT 0x255B: [910,-174,708,-11,390], // BOX DRAWINGS UP SINGLE AND LEFT DOUBLE 0x255C: [910,-267,708,-11,483], // BOX DRAWINGS UP DOUBLE AND LEFT SINGLE 0x255D: [910,-174,708,-11,483], // BOX DRAWINGS DOUBLE UP AND LEFT 0x255E: [910,303,708,318,720], // BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE 0x255F: [910,303,708,225,720], // BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE 0x2560: [910,303,708,225,720], // BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x2561: [910,303,708,-11,390], // BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE 0x2562: [910,303,708,-11,483], // BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE 0x2563: [910,303,708,-11,483], // BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x2564: [433,303,708,-11,719], // BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE 0x2565: [340,303,708,-11,719], // BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE 0x2566: [433,303,708,-11,719], // BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x2567: [910,-174,708,-11,719], // BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE 0x2568: [910,-267,708,-11,719], // BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE 0x2569: [910,-174,708,-11,719], // BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x256A: [910,303,708,-11,719], // BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x256B: [910,303,708,-11,719], // BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x256C: [910,303,708,-11,719] // BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL } ); MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/General/BoldItalic/BoxDrawing.js");
shayzluf/lazoozweb
wiki/extensions/Math/modules/MathJax/unpacked/jax/output/HTML-CSS/fonts/STIX/General/BoldItalic/BoxDrawing.js
JavaScript
gpl-2.0
4,228
/* *Copyright(c)2004,Cisco URP imburses and Network Information Center in Beijing University of Posts and Telecommunications researches. * *All right reserved * *File Name:pingResultsTable.h *File Description:The head file of pingResultsTable.c * *Current Version:1.0 *Author:ChenJing *Date:2004.8.20 */ #ifndef PINGRESULTSTABLE_H #define PINGRESULTSTABLE_H config_require(header_complex); /* * function declarations */ void init_pingResultsTable(void); FindVarMethod var_pingResultsTable; void parse_pingResultsTable(const char *, char *); SNMPCallback store_pingResultsTable; /* * column number definitions for table pingResultsTable */ #define COLUMN_PINGRESULTSOPERSTATUS 1 #define COLUMN_PINGRESULTSIPTARGETADDRESSTYPE 2 #define COLUMN_PINGRESULTSIPTARGETADDRESS 3 #define COLUMN_PINGRESULTSMINRTT 4 #define COLUMN_PINGRESULTSMAXRTT 5 #define COLUMN_PINGRESULTSAVERAGERTT 6 #define COLUMN_PINGRESULTSPROBERESPONSES 7 #define COLUMN_PINGRESULTSSENTPROBES 8 #define COLUMN_PINGRESULTSRTTSUMOFSQUARES 9 #define COLUMN_PINGRESULTSLASTGOODPROBE 10 #endif /* PINGRESULTSTABLE_H */
ZHAW-INES/rioxo-uClinux-dist
user/net-snmp/net-snmp-5.7.1/agent/mibgroup/disman/ping/pingResultsTable.h
C
gpl-2.0
1,165
// Boost.Geometry // Copyright (c) 2018, Oracle and/or its affiliates. // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_PROJECTIONS_FACTORY_KEY_HPP #define BOOST_GEOMETRY_PROJECTIONS_FACTORY_KEY_HPP #include <string> #include <boost/geometry/srs/projections/dpar.hpp> #include <boost/geometry/srs/projections/proj4.hpp> namespace boost { namespace geometry { namespace projections { namespace detail { template <typename Params> struct factory_key_util { BOOST_MPL_ASSERT_MSG((false), INVALID_PARAMETERS_TYPE, (Params)); }; template <> struct factory_key_util<srs::detail::proj4_parameters> { typedef std::string type; template <typename ProjParams> static type const& get(ProjParams const& par) { return par.id.name; } }; template <typename T> struct factory_key_util<srs::dpar::parameters<T> > { typedef srs::dpar::value_proj type; template <typename ProjParams> static type const& get(ProjParams const& par) { return par.id.id; } }; struct factory_key { factory_key(const char* name, srs::dpar::value_proj id) : m_name(name), m_id(id) {} operator const char*() const { return m_name; } operator std::string() const { return std::string(m_name); } operator srs::dpar::value_proj() const { return m_id; } private: const char* m_name; srs::dpar::value_proj m_id; }; } // namespace detail }}} // namespace boost::geometry::projections #endif // BOOST_GEOMETRY_PROJECTIONS_FACTORY_KEY_HPP
Palm-Studios/sh3redux
libs/boost_1_69_0/boost/geometry/srs/projections/factory_key.hpp
C++
gpl-3.0
1,782
----------------------------------- -- -- Zone: Metalworks (237) -- ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/zone"); require("scripts/globals/settings"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-9.168,0,0.001,128); end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
hooksta4/darkstar
scripts/zones/zones/Metalworks/Zone.lua
Lua
gpl-3.0
1,616
/* * %CopyrightBegin% * * Copyright Ericsson AB 1998-2016. 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. * * %CopyrightEnd% * */ #include "hash.h" /* this is a general prime factoring function * we get one prime factor each time we call it * we only use it here to determine if n is prime, * by checking if factor(n) == n . */ static int factor(int n) { /* FIXME problem for threaded?! */ static int a[] = { 0, 4, 1, 2, 0, 2 }; static int m = 0; static int d = 0; if (n) { m = n; d = 2; } while ((d*d) <= m) { if (!(m%d)) { m /= d; return d; } d += a[d%6]; } n = m; m = 0; return n; } /* true if n prime */ int ei_isprime(int n) { return (n == factor(n)); }
RoadRunnr/otp
lib/erl_interface/src/registry/hash_isprime.c
C
apache-2.0
1,271
// "Extract variable 'y' to 'mapToInt' operation" "true" import java.util.*; import java.util.stream.*; public class Test { void testFlatMap() { Stream.of("xyz").flatMapToInt(x -> { int <caret>y = x.length(); return IntStream.range(0, y); }).forEach(System.out::println); } }
jwren/intellij-community
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/extractStreamMap/beforeFlatMap.java
Java
apache-2.0
300
package liquibase.change.core; import liquibase.change.*; import liquibase.database.Database; import liquibase.snapshot.SnapshotGeneratorFactory; import liquibase.statement.SqlStatement; import liquibase.statement.core.CreateIndexStatement; import liquibase.structure.core.Column; import liquibase.structure.core.Index; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Creates an index on an existing column. */ @DatabaseChange(name="createIndex", description = "Creates an index on an existing column or set of columns.", priority = ChangeMetaData.PRIORITY_DEFAULT, appliesTo = "index") public class CreateIndexChange extends AbstractChange implements ChangeWithColumns<AddColumnConfig> { private String catalogName; private String schemaName; private String tableName; private String indexName; private Boolean unique; private String tablespace; private List<AddColumnConfig> columns; // Contain associations of index // for example: foreignKey, primaryKey or uniqueConstraint private String associatedWith; private Boolean clustered; public CreateIndexChange() { columns = new ArrayList<AddColumnConfig>(); } @DatabaseChangeProperty(mustEqualExisting = "index", description = "Name of the index to create") public String getIndexName() { return indexName; } public void setIndexName(String indexName) { this.indexName = indexName; } @DatabaseChangeProperty(mustEqualExisting ="index.schema") public String getSchemaName() { return schemaName; } public void setSchemaName(String schemaName) { this.schemaName = schemaName; } @DatabaseChangeProperty(mustEqualExisting = "index.table", description = "Name of the table to add the index to", exampleValue = "person") public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } @Override @DatabaseChangeProperty(mustEqualExisting = "index.column", description = "Column(s) to add to the index", requiredForDatabase = "all") public List<AddColumnConfig> getColumns() { if (columns == null) { return new ArrayList<AddColumnConfig>(); } return columns; } @Override public void setColumns(List<AddColumnConfig> columns) { this.columns = columns; } @Override public void addColumn(AddColumnConfig column) { columns.add(column); } @DatabaseChangeProperty(description = "Tablepace to create the index in.") public String getTablespace() { return tablespace; } public void setTablespace(String tablespace) { this.tablespace = tablespace; } @Override public SqlStatement[] generateStatements(Database database) { return new SqlStatement[]{ new CreateIndexStatement( getIndexName(), getCatalogName(), getSchemaName(), getTableName(), this.isUnique(), getAssociatedWith(), getColumns().toArray(new AddColumnConfig[getColumns().size()])) .setTablespace(getTablespace()) .setClustered(getClustered()) }; } @Override protected Change[] createInverses() { DropIndexChange inverse = new DropIndexChange(); inverse.setSchemaName(getSchemaName()); inverse.setTableName(getTableName()); inverse.setIndexName(getIndexName()); return new Change[]{ inverse }; } @Override public ChangeStatus checkStatus(Database database) { ChangeStatus result = new ChangeStatus(); try { Index example = new Index(getIndexName(), getCatalogName(), getSchemaName(), getTableName()); if (getColumns() != null) { for (ColumnConfig column : getColumns() ) { example.addColumn(new Column(column)); } } Index snapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(example, database); result.assertComplete(snapshot != null, "Index does not exist"); if (snapshot != null) { if (isUnique() != null) { result.assertCorrect(isUnique().equals(snapshot.isUnique()), "Unique does not match"); } } return result; } catch (Exception e) { return result.unknown(e); } } @Override public String getConfirmationMessage() { return "Index " + getIndexName() + " created"; } /** * @param isUnique the isUnique to set */ public void setUnique(Boolean isUnique) { this.unique = isUnique; } @DatabaseChangeProperty(description = "Unique values index", since = "1.8") public Boolean isUnique() { return this.unique; } /** * @return Index associations. Valid values:<br> * <li>primaryKey</li> * <li>foreignKey</li> * <li>uniqueConstraint</li> * <li>none</li> * */ @DatabaseChangeProperty(isChangeProperty = false) public String getAssociatedWith() { return associatedWith; } public void setAssociatedWith(String associatedWith) { this.associatedWith = associatedWith; } @DatabaseChangeProperty(since = "3.0") public String getCatalogName() { return catalogName; } public void setCatalogName(String catalogName) { this.catalogName = catalogName; } public Boolean getClustered() { return clustered; } public void setClustered(Boolean clustered) { this.clustered = clustered; } @Override public String getSerializedObjectNamespace() { return STANDARD_CHANGELOG_NAMESPACE; } @Override public Object getSerializableFieldValue(String field) { Object value = super.getSerializableFieldValue(field); if (value != null && field.equals("columns")) { for (ColumnConfig config : (Collection<ColumnConfig>) value) { config.setType(null); config.setAutoIncrement(null); config.setConstraints(null); config.setDefaultValue(null); config.setValue(null); config.setStartWith(null); config.setIncrementBy(null); config.setEncoding(null); config.setRemarks(null); } } return value; } }
syncron/liquibase
liquibase-core/src/main/java/liquibase/change/core/CreateIndexChange.java
Java
apache-2.0
6,569
from importlib import _bootstrap import sys import time import unittest import weakref from test import support try: import threading except ImportError: threading = None else: from test import lock_tests LockType = _bootstrap._ModuleLock DeadlockError = _bootstrap._DeadlockError if threading is not None: class ModuleLockAsRLockTests(lock_tests.RLockTests): locktype = staticmethod(lambda: LockType("some_lock")) # _is_owned() unsupported test__is_owned = None # acquire(blocking=False) unsupported test_try_acquire = None test_try_acquire_contended = None # `with` unsupported test_with = None # acquire(timeout=...) unsupported test_timeout = None # _release_save() unsupported test_release_save_unacquired = None else: class ModuleLockAsRLockTests(unittest.TestCase): pass @unittest.skipUnless(threading, "threads needed for this test") class DeadlockAvoidanceTests(unittest.TestCase): def setUp(self): try: self.old_switchinterval = sys.getswitchinterval() sys.setswitchinterval(0.000001) except AttributeError: self.old_switchinterval = None def tearDown(self): if self.old_switchinterval is not None: sys.setswitchinterval(self.old_switchinterval) def run_deadlock_avoidance_test(self, create_deadlock): NLOCKS = 10 locks = [LockType(str(i)) for i in range(NLOCKS)] pairs = [(locks[i], locks[(i+1)%NLOCKS]) for i in range(NLOCKS)] if create_deadlock: NTHREADS = NLOCKS else: NTHREADS = NLOCKS - 1 barrier = threading.Barrier(NTHREADS) results = [] def _acquire(lock): """Try to acquire the lock. Return True on success, False on deadlock.""" try: lock.acquire() except DeadlockError: return False else: return True def f(): a, b = pairs.pop() ra = _acquire(a) barrier.wait() rb = _acquire(b) results.append((ra, rb)) if rb: b.release() if ra: a.release() lock_tests.Bunch(f, NTHREADS).wait_for_finished() self.assertEqual(len(results), NTHREADS) return results def test_deadlock(self): results = self.run_deadlock_avoidance_test(True) # At least one of the threads detected a potential deadlock on its # second acquire() call. It may be several of them, because the # deadlock avoidance mechanism is conservative. nb_deadlocks = results.count((True, False)) self.assertGreaterEqual(nb_deadlocks, 1) self.assertEqual(results.count((True, True)), len(results) - nb_deadlocks) def test_no_deadlock(self): results = self.run_deadlock_avoidance_test(False) self.assertEqual(results.count((True, False)), 0) self.assertEqual(results.count((True, True)), len(results)) class LifetimeTests(unittest.TestCase): def test_lock_lifetime(self): name = "xyzzy" self.assertNotIn(name, _bootstrap._module_locks) lock = _bootstrap._get_module_lock(name) self.assertIn(name, _bootstrap._module_locks) wr = weakref.ref(lock) del lock support.gc_collect() self.assertNotIn(name, _bootstrap._module_locks) self.assertIsNone(wr()) def test_all_locks(self): support.gc_collect() self.assertEqual(0, len(_bootstrap._module_locks), _bootstrap._module_locks) @support.reap_threads def test_main(): support.run_unittest(ModuleLockAsRLockTests, DeadlockAvoidanceTests, LifetimeTests) if __name__ == '__main__': test_main()
firmlyjin/brython
www/tests/unittests/test/test_importlib/test_locks.py
Python
bsd-3-clause
3,909
from __future__ import absolute_import, print_function __all__ = ['SourceCache', 'SourceMapCache'] class SourceCache(object): def __init__(self): self._cache = {} self._errors = {} self._aliases = {} def __contains__(self, url): url = self._get_canonical_url(url) return url in self._cache def _get_canonical_url(self, url): if url in self._aliases: url = self._aliases[url] return url def get(self, url): url = self._get_canonical_url(url) return self._cache.get(url) def get_errors(self, url): url = self._get_canonical_url(url) return self._errors.get(url, []) def alias(self, u1, u2): if u1 == u2: return if u1 in self._cache or u1 not in self._aliases: self._aliases[u1] = u1 else: self._aliases[u2] = u1 def add(self, url, source): url = self._get_canonical_url(url) self._cache[url] = source def add_error(self, url, error): url = self._get_canonical_url(url) self._errors.setdefault(url, []) self._errors[url].append(error) class SourceMapCache(object): def __init__(self): self._cache = {} self._mapping = {} def __contains__(self, sourcemap_url): return sourcemap_url in self._cache def link(self, url, sourcemap_url): self._mapping[url] = sourcemap_url def add(self, sourcemap_url, sourcemap_index): self._cache[sourcemap_url] = sourcemap_index def get(self, sourcemap_url): return self._cache.get(sourcemap_url) def get_link(self, url): sourcemap_url = self._mapping.get(url) if sourcemap_url: sourcemap = self.get(sourcemap_url) return (sourcemap_url, sourcemap) return (None, None)
imankulov/sentry
src/sentry/lang/javascript/cache.py
Python
bsd-3-clause
1,866
module ActiveRecord module ReadonlyAttributes extend ActiveSupport::Concern included do class_attribute :_attr_readonly, instance_accessor: false self._attr_readonly = [] end module ClassMethods # Attributes listed as readonly will be used to create a new record but update operations will # ignore these fields. def attr_readonly(*attributes) self._attr_readonly = Set.new(attributes.map(&:to_s)) + (_attr_readonly || []) end # Returns an array of all the attributes that have been specified as readonly. def readonly_attributes _attr_readonly end end end end
lrosskamp/makealist-public
vendor/cache/ruby/2.3.0/gems/activerecord-5.1.2/lib/active_record/readonly_attributes.rb
Ruby
mit
658
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Tests { public partial class BooleanTests { [Fact] public void TrueString_Get_ReturnsTrue() { Assert.Equal("True", bool.TrueString); } [Fact] public void FalseString_Get_ReturnsFalse() { Assert.Equal("False", bool.FalseString); } public static IEnumerable<object[]> Parse_Valid_TestData() { yield return new object[] { "True", true }; yield return new object[] { "true", true }; yield return new object[] { "TRUE", true }; yield return new object[] { "tRuE", true }; yield return new object[] { " True ", true }; yield return new object[] { "True\0", true }; yield return new object[] { " \0 \0 True \0 ", true }; yield return new object[] { "False", false }; yield return new object[] { "false", false }; yield return new object[] { "FALSE", false }; yield return new object[] { "fAlSe", false }; yield return new object[] { "False ", false }; yield return new object[] { "False\0", false }; yield return new object[] { " False \0\0\0 ", false }; } [Theory] [MemberData(nameof(Parse_Valid_TestData))] public void Parse_ValidValue_ReturnsExpected(string value, bool expected) { Assert.True(bool.TryParse(value, out bool result)); Assert.Equal(expected, result); Assert.Equal(expected, bool.Parse(value)); } public static IEnumerable<object[]> Parse_Invalid_TestData() { yield return new object[] { null, typeof(ArgumentNullException) }; yield return new object[] { "", typeof(FormatException) }; yield return new object[] { " ", typeof(FormatException) }; yield return new object[] { "Garbage", typeof(FormatException) }; yield return new object[] { "True\0Garbage", typeof(FormatException) }; yield return new object[] { "True\0True", typeof(FormatException) }; yield return new object[] { "True True", typeof(FormatException) }; yield return new object[] { "True False", typeof(FormatException) }; yield return new object[] { "False True", typeof(FormatException) }; yield return new object[] { "Fa lse", typeof(FormatException) }; yield return new object[] { "T", typeof(FormatException) }; yield return new object[] { "0", typeof(FormatException) }; yield return new object[] { "1", typeof(FormatException) }; } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public void Parse_InvalidValue_ThrowsException(string value, Type exceptionType) { Assert.Throws(exceptionType, () => bool.Parse(value)); Assert.False(bool.TryParse(value, out bool result)); Assert.False(result); } [Theory] [InlineData(true, "True")] [InlineData(false, "False")] public void ToString_Invoke_ReturnsExpected(bool value, string expected) { Assert.Equal(expected, value.ToString()); } [Theory] [InlineData(true, true, 0)] [InlineData(true, false, 1)] [InlineData(true, null, 1)] [InlineData(false, false, 0)] [InlineData(false, true, -1)] [InlineData(false, null, 1)] public void CompareTo_Other_ReturnsExpected(bool b, object obj, int expected) { if (obj is bool boolValue) { Assert.Equal(expected, Math.Sign(b.CompareTo(boolValue))); } Assert.Equal(expected, Math.Sign(b.CompareTo(obj))); } [Theory] [InlineData(true, 1)] [InlineData(true, "true")] [InlineData(false, 0)] [InlineData(false, "false")] public void CompareTo_ObjectNotBool_ThrowsArgumentException(bool b, object obj) { AssertExtensions.Throws<ArgumentException>(null, () => b.CompareTo(obj)); } [Theory] [InlineData(true, true, true)] [InlineData(true, false, false)] [InlineData(true, "1", false)] [InlineData(true, "True", false)] [InlineData(true, null, false)] [InlineData(false, false, true)] [InlineData(false, true, false)] [InlineData(false, "0", false)] [InlineData(false, "False", false)] [InlineData(false, null, false)] public void Equals_Other_ReturnsExpected(bool b1, object obj, bool expected) { if (obj is bool boolValue) { Assert.Equal(expected, b1.Equals(boolValue)); Assert.Equal(expected, b1.GetHashCode().Equals(obj.GetHashCode())); } Assert.Equal(expected, b1.Equals(obj)); } [Theory] [InlineData(true, 1)] [InlineData(false, 0)] public void GetHashCode_Invoke_ReturnsExpected(bool value, int expected) { Assert.Equal(expected, value.GetHashCode()); } [Fact] public void GetTypeCode_Invoke_ReturnsBoolean() { Assert.Equal(TypeCode.Boolean, true.GetTypeCode()); } } }
BrennanConroy/corefx
src/System.Runtime/tests/System/BooleanTests.cs
C#
mit
5,627
module Fog module AWS class Elasticache < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods class IdentifierTaken < Fog::Errors::Error; end class InvalidInstance < Fog::Errors::Error; end class AuthorizationAlreadyExists < Fog::Errors::Error; end requires :aws_access_key_id, :aws_secret_access_key recognizes :region, :host, :path, :port, :scheme, :persistent, :use_iam_profile, :aws_session_token, :aws_credentials_expire_at, :instrumentor, :instrumentor_name request_path 'fog/aws/requests/elasticache' request :create_cache_cluster request :delete_cache_cluster request :describe_cache_clusters request :modify_cache_cluster request :reboot_cache_cluster request :create_cache_parameter_group request :delete_cache_parameter_group request :describe_cache_parameter_groups request :modify_cache_parameter_group request :reset_cache_parameter_group request :describe_engine_default_parameters request :describe_cache_parameters request :describe_reserved_cache_nodes request :create_cache_security_group request :delete_cache_security_group request :describe_cache_security_groups request :authorize_cache_security_group_ingress request :revoke_cache_security_group_ingress request :create_cache_subnet_group request :describe_cache_subnet_groups request :delete_cache_subnet_group request :describe_events model_path 'fog/aws/models/elasticache' model :cluster collection :clusters model :security_group collection :security_groups model :parameter_group collection :parameter_groups model :subnet_group collection :subnet_groups class Real include Fog::AWS::CredentialFetcher::ConnectionMethods def initialize(options={}) @use_iam_profile = options[:use_iam_profile] @instrumentor = options[:instrumentor] @instrumentor_name = options[:instrumentor_name] || 'fog.aws.elasticache' options[:region] ||= 'us-east-1' @region = options[:region] @host = options[:host] || "elasticache.#{options[:region]}.amazonaws.com" @path = options[:path] || '/' @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::XML::Connection.new( "#{@scheme}://#{@host}:#{@port}#{@path}", options[:persistent] ) setup_credentials(options) end def reload @connection.reset end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @signer = Fog::AWS::SignatureV4.new( @aws_access_key_id, @aws_secret_access_key, @region, 'elasticache') end def request(params) refresh_credentials_if_expired idempotent = params.delete(:idempotent) parser = params.delete(:parser) body, headers = Fog::AWS.signed_params_v4( params, { 'Content-Type' => 'application/x-www-form-urlencoded' }, { :signer => @signer, :aws_session_token => @aws_session_token, :method => 'POST', :host => @host, :path => @path, :port => @port, :version => '2013-06-15' } ) if @instrumentor @instrumentor.instrument("#{@instrumentor_name}.request", params) do _request(body, headers, idempotent, parser) end else _request(body, headers, idempotent, parser) end end def _request(body, headers, idempotent, parser) @connection.request({ :body => body, :expects => 200, :headers => headers, :idempotent => idempotent, :method => 'POST', :parser => parser }) rescue Excon::Errors::HTTPStatusError => error match = Fog::AWS::Errors.match_error(error) raise if match.empty? raise case match[:code] when 'CacheSecurityGroupNotFound', 'CacheParameterGroupNotFound', 'CacheClusterNotFound' Fog::AWS::Elasticache::NotFound.slurp(error, match[:message]) when 'CacheSecurityGroupAlreadyExists' Fog::AWS::Elasticache::IdentifierTaken.slurp(error, match[:message]) when 'InvalidParameterValue' Fog::AWS::Elasticache::InvalidInstance.slurp(error, match[:message]) else Fog::AWS::Elasticache::Error.slurp(error, "#{match[:code]} => #{match[:message]}") end end end class Mock include Fog::AWS::CredentialFetcher::ConnectionMethods def self.data @data ||= Hash.new do |hash, region| hash[region] = Hash.new do |region_hash, key| region_hash[key] = { :clusters => {}, # cache cluster data, indexed by cluster ID :security_groups => {}, # security groups :subnet_groups => {}, :parameter_groups => {"default.memcached1.4" => { "CacheParameterGroupFamily"=>"memcached1.4", "Description"=>"Default parameter group for memcached1.4", "CacheParameterGroupName"=>"default.memcached1.4" }, "default.redis2.6" => {"CacheParameterGroupFamily"=>"redis2.6", "Description"=>"Default parameter group for redis2.6", "CacheParameterGroupName"=>"default.redis2.6" } } } end end end def self.reset @data = nil end def initialize(options={}) @aws_credentials_expire_at = Time::now + 20 setup_credentials(options) @region = options[:region] || 'us-east-1' unless ['ap-northeast-1', 'ap-southeast-1', 'eu-west-1', 'us-east-1', 'us-west-1', 'us-west-2', 'sa-east-1'].include?(@region) raise ArgumentError, "Unknown region: #{@region.inspect}" end end def region_data self.class.data[@region] end def data self.region_data[@aws_access_key_id] end def reset_data self.region_data.delete(@aws_access_key_id) end def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] end # returns an Array of (Mock) elasticache nodes, representated as Hashes def create_cache_nodes(cluster_id, num_nodes = 1, port = '11211') (1..num_nodes).map do |node_number| node_id = "%04d" % node_number { # each hash represents a cache cluster node "CacheNodeId" => node_id, "Port" => port, "ParameterGroupStatus" => "in-sync", "CacheNodeStatus" => "available", "CacheNodeCreateTime" => Time.now.utc.to_s, "Address" => "#{cluster_id}.#{node_id}.use1.cache.amazonaws.com" } end end end end end end
jonpstone/portfolio-project-rails-mean-movie-reviews
vendor/bundle/ruby/2.3.0/gems/fog-aws-2.0.0/lib/fog/aws/elasticache.rb
Ruby
mit
8,109
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Pdf * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Png.php 20096 2010-01-06 02:05:09Z bkarwin $ */ /** Internally used classes */ require_once 'Zend/Pdf/Element/Array.php'; require_once 'Zend/Pdf/Element/Dictionary.php'; require_once 'Zend/Pdf/Element/Name.php'; require_once 'Zend/Pdf/Element/Numeric.php'; require_once 'Zend/Pdf/Element/String/Binary.php'; /** Zend_Pdf_Resource_Image */ require_once 'Zend/Pdf/Resource/Image.php'; /** * PNG image * * @package Zend_Pdf * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Pdf_Resource_Image_Png extends Zend_Pdf_Resource_Image { const PNG_COMPRESSION_DEFAULT_STRATEGY = 0; const PNG_COMPRESSION_FILTERED = 1; const PNG_COMPRESSION_HUFFMAN_ONLY = 2; const PNG_COMPRESSION_RLE = 3; const PNG_FILTER_NONE = 0; const PNG_FILTER_SUB = 1; const PNG_FILTER_UP = 2; const PNG_FILTER_AVERAGE = 3; const PNG_FILTER_PAETH = 4; const PNG_INTERLACING_DISABLED = 0; const PNG_INTERLACING_ENABLED = 1; const PNG_CHANNEL_GRAY = 0; const PNG_CHANNEL_RGB = 2; const PNG_CHANNEL_INDEXED = 3; const PNG_CHANNEL_GRAY_ALPHA = 4; const PNG_CHANNEL_RGB_ALPHA = 6; protected $_width; protected $_height; protected $_imageProperties; /** * Object constructor * * @param string $imageFileName * @throws Zend_Pdf_Exception * @todo Add compression conversions to support compression strategys other than PNG_COMPRESSION_DEFAULT_STRATEGY. * @todo Add pre-compression filtering. * @todo Add interlaced image handling. * @todo Add support for 16-bit images. Requires PDF version bump to 1.5 at least. * @todo Add processing for all PNG chunks defined in the spec. gAMA etc. * @todo Fix tRNS chunk support for Indexed Images to a SMask. */ public function __construct($imageFileName) { if (($imageFile = @fopen($imageFileName, 'rb')) === false ) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception( "Can not open '$imageFileName' file for reading." ); } parent::__construct(); //Check if the file is a PNG fseek($imageFile, 1, SEEK_CUR); //First signature byte (%) if ('PNG' != fread($imageFile, 3)) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Image is not a PNG'); } fseek($imageFile, 12, SEEK_CUR); //Signature bytes (Includes the IHDR chunk) IHDR processed linerarly because it doesnt contain a variable chunk length $wtmp = unpack('Ni',fread($imageFile, 4)); //Unpack a 4-Byte Long $width = $wtmp['i']; $htmp = unpack('Ni',fread($imageFile, 4)); $height = $htmp['i']; $bits = ord(fread($imageFile, 1)); //Higher than 8 bit depths are only supported in later versions of PDF. $color = ord(fread($imageFile, 1)); $compression = ord(fread($imageFile, 1)); $prefilter = ord(fread($imageFile,1)); if (($interlacing = ord(fread($imageFile,1))) != Zend_Pdf_Resource_Image_Png::PNG_INTERLACING_DISABLED) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception( "Only non-interlaced images are currently supported." ); } $this->_width = $width; $this->_height = $height; $this->_imageProperties = array(); $this->_imageProperties['bitDepth'] = $bits; $this->_imageProperties['pngColorType'] = $color; $this->_imageProperties['pngFilterType'] = $prefilter; $this->_imageProperties['pngCompressionType'] = $compression; $this->_imageProperties['pngInterlacingType'] = $interlacing; fseek($imageFile, 4, SEEK_CUR); //4 Byte Ending Sequence $imageData = ''; /* * The following loop processes PNG chunks. 4 Byte Longs are packed first give the chunk length * followed by the chunk signature, a four byte code. IDAT and IEND are manditory in any PNG. */ while(($chunkLengthBytes = fread($imageFile, 4)) !== false) { $chunkLengthtmp = unpack('Ni', $chunkLengthBytes); $chunkLength = $chunkLengthtmp['i']; $chunkType = fread($imageFile, 4); switch($chunkType) { case 'IDAT': //Image Data /* * Reads the actual image data from the PNG file. Since we know at this point that the compression * strategy is the default strategy, we also know that this data is Zip compressed. We will either copy * the data directly to the PDF and provide the correct FlateDecode predictor, or decompress the data * decode the filters and output the data as a raw pixel map. */ $imageData .= fread($imageFile, $chunkLength); fseek($imageFile, 4, SEEK_CUR); break; case 'PLTE': //Palette $paletteData = fread($imageFile, $chunkLength); fseek($imageFile, 4, SEEK_CUR); break; case 'tRNS': //Basic (non-alpha channel) transparency. $trnsData = fread($imageFile, $chunkLength); switch ($color) { case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_GRAY: $baseColor = ord(substr($trnsData, 1, 1)); $transparencyData = array(new Zend_Pdf_Element_Numeric($baseColor), new Zend_Pdf_Element_Numeric($baseColor)); break; case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_RGB: $red = ord(substr($trnsData,1,1)); $green = ord(substr($trnsData,3,1)); $blue = ord(substr($trnsData,5,1)); $transparencyData = array(new Zend_Pdf_Element_Numeric($red), new Zend_Pdf_Element_Numeric($red), new Zend_Pdf_Element_Numeric($green), new Zend_Pdf_Element_Numeric($green), new Zend_Pdf_Element_Numeric($blue), new Zend_Pdf_Element_Numeric($blue)); break; case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_INDEXED: //Find the first transparent color in the index, we will mask that. (This is a bit of a hack. This should be a SMask and mask all entries values). if(($trnsIdx = strpos($trnsData, chr(0))) !== false) { $transparencyData = array(new Zend_Pdf_Element_Numeric($trnsIdx), new Zend_Pdf_Element_Numeric($trnsIdx)); } break; case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_GRAY_ALPHA: // Fall through to the next case case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_RGB_ALPHA: require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception( "tRNS chunk illegal for Alpha Channel Images" ); break; } fseek($imageFile, 4, SEEK_CUR); //4 Byte Ending Sequence break; case 'IEND'; break 2; //End the loop too default: fseek($imageFile, $chunkLength + 4, SEEK_CUR); //Skip the section break; } } fclose($imageFile); $compressed = true; $imageDataTmp = ''; $smaskData = ''; switch ($color) { case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_RGB: $colorSpace = new Zend_Pdf_Element_Name('DeviceRGB'); break; case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_GRAY: $colorSpace = new Zend_Pdf_Element_Name('DeviceGray'); break; case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_INDEXED: if(empty($paletteData)) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception( "PNG Corruption: No palette data read for indexed type PNG." ); } $colorSpace = new Zend_Pdf_Element_Array(); $colorSpace->items[] = new Zend_Pdf_Element_Name('Indexed'); $colorSpace->items[] = new Zend_Pdf_Element_Name('DeviceRGB'); $colorSpace->items[] = new Zend_Pdf_Element_Numeric((strlen($paletteData)/3-1)); $paletteObject = $this->_objectFactory->newObject(new Zend_Pdf_Element_String_Binary($paletteData)); $colorSpace->items[] = $paletteObject; break; case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_GRAY_ALPHA: /* * To decode PNG's with alpha data we must create two images from one. One image will contain the Gray data * the other will contain the Gray transparency overlay data. The former will become the object data and the latter * will become the Shadow Mask (SMask). */ if($bits > 8) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception("Alpha PNGs with bit depth > 8 are not yet supported"); } $colorSpace = new Zend_Pdf_Element_Name('DeviceGray'); require_once 'Zend/Pdf/ElementFactory.php'; $decodingObjFactory = Zend_Pdf_ElementFactory::createFactory(1); $decodingStream = $decodingObjFactory->newStreamObject($imageData); $decodingStream->dictionary->Filter = new Zend_Pdf_Element_Name('FlateDecode'); $decodingStream->dictionary->DecodeParms = new Zend_Pdf_Element_Dictionary(); $decodingStream->dictionary->DecodeParms->Predictor = new Zend_Pdf_Element_Numeric(15); $decodingStream->dictionary->DecodeParms->Columns = new Zend_Pdf_Element_Numeric($width); $decodingStream->dictionary->DecodeParms->Colors = new Zend_Pdf_Element_Numeric(2); //GreyAlpha $decodingStream->dictionary->DecodeParms->BitsPerComponent = new Zend_Pdf_Element_Numeric($bits); $decodingStream->skipFilters(); $pngDataRawDecoded = $decodingStream->value; //Iterate every pixel and copy out gray data and alpha channel (this will be slow) for($pixel = 0, $pixelcount = ($width * $height); $pixel < $pixelcount; $pixel++) { $imageDataTmp .= $pngDataRawDecoded[($pixel*2)]; $smaskData .= $pngDataRawDecoded[($pixel*2)+1]; } $compressed = false; $imageData = $imageDataTmp; //Overwrite image data with the gray channel without alpha break; case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_RGB_ALPHA: /* * To decode PNG's with alpha data we must create two images from one. One image will contain the RGB data * the other will contain the Gray transparency overlay data. The former will become the object data and the latter * will become the Shadow Mask (SMask). */ if($bits > 8) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception("Alpha PNGs with bit depth > 8 are not yet supported"); } $colorSpace = new Zend_Pdf_Element_Name('DeviceRGB'); require_once 'Zend/Pdf/ElementFactory.php'; $decodingObjFactory = Zend_Pdf_ElementFactory::createFactory(1); $decodingStream = $decodingObjFactory->newStreamObject($imageData); $decodingStream->dictionary->Filter = new Zend_Pdf_Element_Name('FlateDecode'); $decodingStream->dictionary->DecodeParms = new Zend_Pdf_Element_Dictionary(); $decodingStream->dictionary->DecodeParms->Predictor = new Zend_Pdf_Element_Numeric(15); $decodingStream->dictionary->DecodeParms->Columns = new Zend_Pdf_Element_Numeric($width); $decodingStream->dictionary->DecodeParms->Colors = new Zend_Pdf_Element_Numeric(4); //RGBA $decodingStream->dictionary->DecodeParms->BitsPerComponent = new Zend_Pdf_Element_Numeric($bits); $decodingStream->skipFilters(); $pngDataRawDecoded = $decodingStream->value; //Iterate every pixel and copy out rgb data and alpha channel (this will be slow) for($pixel = 0, $pixelcount = ($width * $height); $pixel < $pixelcount; $pixel++) { $imageDataTmp .= $pngDataRawDecoded[($pixel*4)+0] . $pngDataRawDecoded[($pixel*4)+1] . $pngDataRawDecoded[($pixel*4)+2]; $smaskData .= $pngDataRawDecoded[($pixel*4)+3]; } $compressed = false; $imageData = $imageDataTmp; //Overwrite image data with the RGB channel without alpha break; default: require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception( "PNG Corruption: Invalid color space." ); } if(empty($imageData)) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception( "Corrupt PNG Image. Mandatory IDAT chunk not found." ); } $imageDictionary = $this->_resource->dictionary; if(!empty($smaskData)) { /* * Includes the Alpha transparency data as a Gray Image, then assigns the image as the Shadow Mask for the main image data. */ $smaskStream = $this->_objectFactory->newStreamObject($smaskData); $smaskStream->dictionary->Type = new Zend_Pdf_Element_Name('XObject'); $smaskStream->dictionary->Subtype = new Zend_Pdf_Element_Name('Image'); $smaskStream->dictionary->Width = new Zend_Pdf_Element_Numeric($width); $smaskStream->dictionary->Height = new Zend_Pdf_Element_Numeric($height); $smaskStream->dictionary->ColorSpace = new Zend_Pdf_Element_Name('DeviceGray'); $smaskStream->dictionary->BitsPerComponent = new Zend_Pdf_Element_Numeric($bits); $imageDictionary->SMask = $smaskStream; // Encode stream with FlateDecode filter $smaskStreamDecodeParms = array(); $smaskStreamDecodeParms['Predictor'] = new Zend_Pdf_Element_Numeric(15); $smaskStreamDecodeParms['Columns'] = new Zend_Pdf_Element_Numeric($width); $smaskStreamDecodeParms['Colors'] = new Zend_Pdf_Element_Numeric(1); $smaskStreamDecodeParms['BitsPerComponent'] = new Zend_Pdf_Element_Numeric(8); $smaskStream->dictionary->DecodeParms = new Zend_Pdf_Element_Dictionary($smaskStreamDecodeParms); $smaskStream->dictionary->Filter = new Zend_Pdf_Element_Name('FlateDecode'); } if(!empty($transparencyData)) { //This is experimental and not properly tested. $imageDictionary->Mask = new Zend_Pdf_Element_Array($transparencyData); } $imageDictionary->Width = new Zend_Pdf_Element_Numeric($width); $imageDictionary->Height = new Zend_Pdf_Element_Numeric($height); $imageDictionary->ColorSpace = $colorSpace; $imageDictionary->BitsPerComponent = new Zend_Pdf_Element_Numeric($bits); $imageDictionary->Filter = new Zend_Pdf_Element_Name('FlateDecode'); $decodeParms = array(); $decodeParms['Predictor'] = new Zend_Pdf_Element_Numeric(15); // Optimal prediction $decodeParms['Columns'] = new Zend_Pdf_Element_Numeric($width); $decodeParms['Colors'] = new Zend_Pdf_Element_Numeric((($color==Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_RGB || $color==Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_RGB_ALPHA)?(3):(1))); $decodeParms['BitsPerComponent'] = new Zend_Pdf_Element_Numeric($bits); $imageDictionary->DecodeParms = new Zend_Pdf_Element_Dictionary($decodeParms); //Include only the image IDAT section data. $this->_resource->value = $imageData; //Skip double compression if ($compressed) { $this->_resource->skipFilters(); } } /** * Image width */ public function getPixelWidth() { return $this->_width; } /** * Image height */ public function getPixelHeight() { return $this->_height; } /** * Image properties */ public function getProperties() { return $this->_imageProperties; } }
serviom/mobd
vendor/zend/lib/Zend/Pdf/Resource/Image/Png.php
PHP
mit
18,278
# Glyphicons for Bootstrap The official Bootstrap icon font, featuring 160 glyphs from [Glyphicons](http://glyphicons.com), ready for use in any Bootstrap project. Includes support for IE8+. To get started, check out [http://glyphicons.getbootstrap.com](http://glyphicons.getbootstrap.com)! ### Bugs and feature requests Have a bug or a feature request? [Please open a new issue](https://github.com/twitter/bootstrap/issues). Before opening any issue, please search for existing issues and read the [Issue Guidelines](https://github.com/necolas/issue-guidelines), written by [Nicolas Gallagher](https://github.com/necolas/). ### Contributing Please read through our guidelines for contributing to Bootstrap. Included are directions for opening issues, coding standards, and notes on development. All HTML and CSS should conform to the [Code Guide](http://github.com/mdo/code-guide), maintained by [Mark Otto](http://github.com/mdo). ### Community Keep track of development and community news. * Follow [@twbootstrap on Twitter](http://twitter.com/twbootstrap). * Read and subscribe to the [The Official Twitter Bootstrap Blog](http://blog.getbootstrap.com). * Have a question that's not a feature request or bug report? [Ask on the mailing list.](http://groups.google.com/group/twitter-bootstrap) * Chat with fellow Bootstrappers in IRC. On the `irc.freenode.net` server, in the `##twitter-bootstrap` channel. ### Versioning For transparency and insight into our release cycle, and for striving to maintain backward compatibility, bootstrap-glyphicons will be maintained under the Semantic Versioning guidelines as much as possible. Releases will be numbered with the following format: `<major>.<minor>.<patch>` And constructed with the following guidelines: * Breaking backward compatibility bumps the major (and resets the minor and patch) * New additions without breaking backward compatibility bumps the minor (and resets the patch) * Bug fixes and misc changes bumps the patch For more information on SemVer, please visit [http://semver.org/](http://semver.org/). ### Authors **Mark Otto** + [http://twitter.com/mdo](http://twitter.com/mdo) + [http://github.com/mdo](http://github.com/mdo) ### Copyright and license Copyright 2013 Mark Otto, Inc under [the MIT license](LICENSE).
trung85/giasu
wp-content/themes/writerstrap/includes/resources/glyphicons/README.md
Markdown
gpl-2.0
2,318
UPDATE `creature_template` SET `mechanic_immune_mask`=`mechanic_immune_mask`|617299839 WHERE `entry` IN(34171,34166);
Effec7/Adamantium
sql/updates/world/3.3.5/2017_09_09_00_world.sql
SQL
gpl-2.0
118
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Strings for component 'tool_langimport', language 'en', branch 'MOODLE_22_STABLE' * * @package tool * @subpackage langimport * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ $string['downloadnotavailable'] = 'Unable to connect to the download server. It is not possible to install or update the language packs automatically. Please download the appropriate ZIP file(s) from <a href="{$a->src}">{$a->src}</a> and unzip them manually to your data directory <code>{$a->dest}</code>'; $string['install'] = 'Install selected language pack(s)'; $string['installedlangs'] = 'Installed language packs'; $string['langimport'] = 'Language import utility'; $string['langimportdisabled'] = 'Language import feature has been disabled. You have to update your language packs manually at the file-system level. Do not forget to purge string caches after you do so.'; $string['langpackinstalled'] = 'Language pack \'{$a}\' was successfully installed'; $string['langpackinstalledevent'] = 'Language pack installed'; $string['langpackremoved'] = 'Language pack \'{$a}\' was uninstalled'; $string['langpacknotremoved'] = 'An error has occurred; language pack \'{$a}\' is not completely uninstalled. Please check file permissions.'; $string['langpackremovedevent'] = 'Language pack uninstalled'; $string['langpackupdateskipped'] = 'Update of \'{$a}\' language pack skipped'; $string['langpackuptodate'] = 'Language pack \'{$a}\' is up-to-date'; $string['langpackupdated'] = 'Language pack \'{$a}\' was successfully updated'; $string['langpackupdatedevent'] = 'Language pack updated'; $string['langunsupported'] = '<p>Your server does not seem to fully support the following languages:</p><ul>{$a->missinglocales}</ul><p>Instead, the global locale ({$a->globallocale}) will be used to format certain strings such as dates or numbers.</p>'; $string['langupdatecomplete'] = 'Language pack update completed'; $string['missingcfglangotherroot'] = 'Missing configuration value $CFG->langotherroot'; $string['missinglangparent'] = 'Missing parent language <em>{$a->parent}</em> of <em>{$a->lang}</em>.'; $string['noenglishuninstall'] = 'The English language pack cannot be uninstalled.'; $string['nolangupdateneeded'] = 'All your language packs are up to date, no update is needed'; $string['pluginname'] = 'Language packs'; $string['purgestringcaches'] = 'Purge string caches'; $string['selectlangs'] = 'Select languages to uninstall'; $string['uninstall'] = 'Uninstall selected language pack(s)'; $string['uninstallconfirm'] = 'You are about to completely uninstall these language packs: <strong>{$a}</strong>. Are you sure?'; $string['updatelangs'] = 'Update all installed language packs'; $string['privacy:metadata'] = 'The Language packs plugin does not store any personal data.';
marcusboon/moodle
admin/tool/langimport/lang/en/tool_langimport.php
PHP
gpl-3.0
3,562
import decimal from unittest import TestCase from simplejson import decoder, encoder, scanner def has_speedups(): return encoder.c_make_encoder is not None class TestDecode(TestCase): def test_make_scanner(self): if not has_speedups(): return self.assertRaises(AttributeError, scanner.c_make_scanner, 1) def test_make_encoder(self): if not has_speedups(): return self.assertRaises(TypeError, encoder.c_make_encoder, None, "\xCD\x7D\x3D\x4E\x12\x4C\xF9\x79\xD7\x52\xBA\x82\xF2\x27\x4A\x7D\xA0\xCA\x75", None)
AloneRoad/Inforlearn
vendor/simplejson/tests/test_speedups.py
Python
apache-2.0
616
#include "Segment.h" #include <iostream> namespace AprilTags { const float Segment::minimumLineLength = 4; Segment::Segment() : children(), x0(0), y0(0), x1(0), y1(0), theta(0), length(0), segmentId(++idCounter) {} float Segment::segmentLength() { return std::sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)); } void Segment::printSegment() { std::cout <<"("<< x0 <<","<< y0 <<"), "<<"("<< x1 <<","<< y1 <<")" << std::endl; } int Segment::idCounter = 0; } // namespace
arthuralee/tether
tether-cam/src/Segment.cc
C++
apache-2.0
474
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.webapp.dao; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.apache.hadoop.yarn.api.records.ApplicationTimeoutType; /** * DAO object to display Application timeout information. */ @XmlRootElement(name = "timeout") @XmlAccessorType(XmlAccessType.FIELD) public class AppTimeoutInfo { @XmlElement(name = "type") private ApplicationTimeoutType timeoutType; @XmlElement(name = "expiryTime") private String expiryTime; @XmlElement(name = "remainingTimeInSeconds") private long remainingTimeInSec; public AppTimeoutInfo() { expiryTime = "UNLIMITED"; remainingTimeInSec = -1; } public ApplicationTimeoutType getTimeoutType() { return timeoutType; } public String getExpireTime() { return expiryTime; } public long getRemainingTimeInSec() { return remainingTimeInSec; } public void setTimeoutType(ApplicationTimeoutType type) { this.timeoutType = type; } public void setExpiryTime(String expiryTime) { this.expiryTime = expiryTime; } public void setRemainingTime(long remainingTime) { this.remainingTimeInSec = remainingTime; } }
dennishuo/hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/AppTimeoutInfo.java
Java
apache-2.0
2,123
@media (min-width: 16 + 1) { .foo { bar: 1; } } @media (min-width: 16 / 9) { .foo { bar: 1; } }
BigBoss424/portfolio
v7/development/node_modules/less/test/css/math/strict/media-math.css
CSS
apache-2.0
112
package com.twitter.finagle.http.codec import com.twitter.finagle.ChannelBufferUsageException import com.twitter.conversions.storage._ import org.jboss.netty.channel._ import org.jboss.netty.buffer.ChannelBuffers import org.junit.runner.RunWith import org.mockito.Mockito._ import org.scalatest.mock.MockitoSugar import org.mockito.Matchers._ import org.scalatest.FunSuite import org.scalatest.junit.JUnitRunner @RunWith(classOf[JUnitRunner]) class ChannelBufferManagerTest extends FunSuite with MockitoSugar { val me = mock[MessageEvent] val c = mock[Channel] val ctx = mock[ChannelHandlerContext] val e = mock[ChannelStateEvent] val wce = mock[WriteCompletionEvent] when(me.getChannel).thenReturn(c) def makeGetMessage(channelCapacity: Int): Unit = { val channelBuffer = ChannelBuffers.directBuffer(channelCapacity) doReturn(channelBuffer).when(me).getMessage } def usageTrackerFactory() = { val usageTracker = new ChannelBufferUsageTracker(1000.bytes) assert(usageTracker.usageLimit === (1000.bytes)) usageTracker } def handlerFactory(usageTracker: ChannelBufferUsageTracker) = new ChannelBufferManager(usageTracker) test("track the capacity of the channel buffer") { val usageTracker = usageTrackerFactory() val handler = handlerFactory(usageTracker) makeGetMessage(256) handler.messageReceived(ctx, me) assert(usageTracker.currentUsage === (256.bytes)) makeGetMessage(512) handler.messageReceived(ctx, me) assert(usageTracker.currentUsage === (768.bytes)) handler.writeComplete(ctx, wce) usageTracker.currentUsage === (0.bytes) makeGetMessage(128) handler.messageReceived(ctx, me) usageTracker.currentUsage === (128.bytes) handler.channelClosed(ctx, e) usageTracker.currentUsage === (0.bytes) usageTracker.maxUsage === (768.bytes) } test("throw exception if usage exceeds limit at the beginning of the request") { val usageTracker = usageTrackerFactory() val handler = handlerFactory(usageTracker) usageTracker.setUsageLimit(10.bytes) assert(usageTracker.usageLimit === (10.bytes)) assert(usageTracker.currentUsage === (0.bytes)) makeGetMessage(20) intercept[ChannelBufferUsageException] { handler.messageReceived(ctx, me) } assert(usageTracker.currentUsage === (0.bytes)) handler.channelClosed(ctx, e) assert(usageTracker.currentUsage === (0.bytes)) assert(usageTracker.maxUsage === (0.bytes)) } test("throw exception if usage exceeds limit in the middle of the request") { val usageTracker = usageTrackerFactory() val handler = handlerFactory(usageTracker) usageTracker.setUsageLimit(300.bytes) assert(usageTracker.usageLimit === (300.bytes)) assert(usageTracker.currentUsage === (0.bytes)) makeGetMessage(100) handler.messageReceived(ctx, me) assert(usageTracker.currentUsage === (100.bytes)) makeGetMessage(350) intercept[ChannelBufferUsageException] { handler.messageReceived(ctx, me) } assert(usageTracker.currentUsage === (100.bytes)) assert(usageTracker.maxUsage === (100.bytes)) makeGetMessage(50) handler.messageReceived(ctx, me) assert(usageTracker.currentUsage === (150.bytes)) assert(usageTracker.maxUsage === (150.bytes)) makeGetMessage(150) handler.messageReceived(ctx, me) assert(usageTracker.currentUsage === (300.bytes)) handler.channelClosed(ctx, e) assert(usageTracker.currentUsage === (0.bytes)) assert(usageTracker.maxUsage === (300.bytes)) } }
LithiumTD/finagle
finagle-http/src/test/scala/com/twitter/finagle/http/codec/ChannelBufferManagerTest.scala
Scala
apache-2.0
3,563
require "formula" class Libpointing < Formula homepage "http://pointing.org" url "http://libpointing.org/homebrew/libpointing-0.92.tar.gz" sha1 "a7f20c405e87a4b6fae369f977c0615a621ab143" bottle do cellar :any revision 1 sha1 "02be7b605af13fbc724fd0d7df55577a81441b54" => :yosemite sha1 "5b97a2c58b9101aba98f43de0b7e4753dd32b85b" => :mavericks sha1 "402cb8cf65ea6712ad9b0dca43361bdf3fabc9a4" => :mountain_lion end def install system "make" system "make", "install", "PREFIX=#{prefix}" end test do (testpath/"test.cpp").write <<-EOS.undent #include <pointing/pointing.h> #include <iostream> int main() { std::cout << LIBPOINTING_VER_STRING << " |" ; std::list<std::string> schemes = pointing::TransferFunction::schemes() ; for (std::list<std::string>::iterator i=schemes.begin(); i!=schemes.end(); ++i) { std::cout << " " << (*i) ; } std::cout << std::endl ; return 0; } EOS system ENV.cxx, "test.cpp", "-lpointing", "-o", "test" system "./test" end end
telamonian/linuxbrew
Library/Formula/libpointing.rb
Ruby
bsd-2-clause
1,100
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_COPRESENCE_PUBLIC_COPRESENCE_MANAGER_H_ #define COMPONENTS_COPRESENCE_PUBLIC_COPRESENCE_MANAGER_H_ #include <string> #include "components/copresence/public/copresence_delegate.h" namespace copresence { class CopresenceState; class ReportRequest; // The CopresenceManager class is the central interface for Copresence // functionality. This class handles all the initialization and delegation // of copresence tasks. Any user of copresence only needs to interact // with this class. class CopresenceManager { public: CopresenceManager() {} virtual ~CopresenceManager() {} // Accessor for the CopresenceState instance that tracks debug info. virtual CopresenceState* state() = 0; // This method will execute a report request. Each report request can have // multiple (un)publishes, (un)subscribes. This will ensure that once the // manager is initialized, it sends all request to the server and handles // the response. If an error is encountered, the status callback is used // to relay it to the requester. virtual void ExecuteReportRequest(const ReportRequest& request, const std::string& app_id, const std::string& auth_token, const StatusCallback& callback) = 0; private: DISALLOW_COPY_AND_ASSIGN(CopresenceManager); }; } // namespace copresence #endif // COMPONENTS_COPRESENCE_PUBLIC_COPRESENCE_MANAGER_H_
guorendong/iridium-browser-ubuntu
components/copresence/public/copresence_manager.h
C
bsd-3-clause
1,639
/* * Sprint JavaScript Library v0.5.1 * http://sprintjs.com * * Copyright (c) 2014, 2015 Benjamin De Cock * Released under the MIT license * http://sprintjs.com/license */ var Sprint; (function() { "use strict" var d = document var domMethods = { afterbegin: function(el) { this.insertBefore(el, this.firstChild) }, afterend: function(el) { this.parentNode.insertBefore(el, this.nextSibling) }, beforebegin: function(el) { this.parentNode.insertBefore(el, this) }, beforeend: function(el) { this.appendChild(el) } } var matches = (function() { var names = [ "mozMatchesSelector", "webkitMatchesSelector", "msMatchesSelector", "matches" ] var i = names.length while (i--) { var name = names[i] if (!Element.prototype[name]) continue return name } })() var noPx = [ "animation-delay", "animation-duration", "animation-iteration-count", "column-count", "flex-grow", "flex-shrink", "font-weight", "line-height", "opacity", "order", "orphans", "transition", "transition-delay", "transition-duration", "widows", "z-index" ] var root = d.documentElement function addEventListeners(listeners, el) { var sprintClone = Sprint(el) var events = Object.keys(listeners) var eventsLen = events.length for (var i = 0; i < eventsLen; i++) { var event = events[i] var handlers = listeners[event] var handlersLen = handlers.length for (var j = 0; j < handlersLen; j++) { sprintClone.on(event, handlers[j]) } } } function addPx(cssProperty, value) { var i = noPx.length while (i--) { if (noPx[i] == cssProperty) { return value } } var stringValue = typeof value == "string" ? value : value.toString() if (value && !/\D/.test(stringValue)) { stringValue += "px" } return stringValue } function duplicateEventListeners(el, clone) { // Ignore text nodes if (el.nodeType == 3) return // Duplicate event listeners for the parent element... var listeners = el.sprintEventListeners listeners && addEventListeners(listeners, clone) // ... and its descendants. var descendants = selectElements("*", el) var descendantsLen = descendants.length // cloneDescendants is defined later to avoid calling selectElements() if not needed var cloneDescendants for (var i = 0; i < descendantsLen; i++) { var listeners = descendants[i].sprintEventListeners if (!listeners) continue if (!cloneDescendants) { cloneDescendants = selectElements("*", clone) } addEventListeners(listeners, cloneDescendants[i]) } } function findAncestors(startAtParent, limitToParent, limitToFirstMatch, selector, context) { var dom = [] var self = this this.each(function() { var prt = startAtParent ? this.parentElement : this while (prt) { if (context && context == prt) break if (!selector || self.is(selector, prt)) { dom.push(prt) if (limitToFirstMatch) break } if (limitToParent) break prt = prt.parentElement } }) return Sprint(removeDuplicates(dom)) } function findDomElements(elementsToFind, returnParent) { elementsToFind = elementsToFind instanceof Init ? elementsToFind.get() : [elementsToFind] var elementsToFindLen = elementsToFind.length var dom = [] for (var i = 0; i < this.length; i++) { var descendants = selectElements("*", this.get(i)) var descendantsLen = descendants.length for (var j = 0; j < descendantsLen; j++) { for (var k = 0; k < elementsToFindLen; k++) { if (descendants[j] == elementsToFind[k]) { var returnedElement = returnParent ? this.get(i) : elementsToFind[k] if (elementsToFindLen < 2) { return Sprint(returnedElement) } dom.push(returnedElement) } } } } return Sprint(removeDuplicates(dom)) } function insertHTML(position, args) { var argsLen = args.length var contents = args // reverse argument list for afterbegin and afterend if (argsLen > 1 && position.indexOf("after") > -1) { contents = [] var i = argsLen while (i--) { contents.push(args[i]) } } for (var i = 0; i < argsLen; i++) { var content = contents[i] if (typeof content == "string") { this.each(function() { this.insertAdjacentHTML(position, content) }) } else if (typeof content == "function") { this.each(function(index) { var callbackValue = content.call(this, index, this.innerHTML) insertHTML.call(Sprint(this), position, [callbackValue]) }) } else { var isSprintObj = content instanceof Init var clonedElements = [] var elementsToInsert = (function() { if (isSprintObj) { return content.get() } // [node1, node2] if (Array.isArray(content)) { return content } // Existing DOM node, createTextNode(), createElement() if (content.nodeType) { return [content] } // getElementsByTagName, getElementsByClassName, querySelectorAll return toArray(content) })() var elementsToInsertLen = elementsToInsert.length if (elementsToInsertLen > 1 && position.indexOf("after") > -1) { elementsToInsert.reverse() } this.each(function(index) { for (var i = 0; i < elementsToInsertLen; i++) { var element = elementsToInsert[i] var elementToInsert if (index) { elementToInsert = element.cloneNode(true) duplicateEventListeners(element, elementToInsert) } else { elementToInsert = element } domMethods[position].call(this, elementToInsert) clonedElements.push(elementToInsert) } }) if (isSprintObj) { content.dom = clonedElements content.length = clonedElements.length } if (i < argsLen-1) continue return clonedElements } } } function manipulateClass(method, className, bool) { if (className == null) { if (method == "add") { return this } return this.removeAttr("class") } var isString var classNames var classNamesLen if (typeof className == "string") { isString = true classNames = className.trim().split(" ") classNamesLen = classNames.length } return this.each(function(i, el) { if (!isString) { // className is a function var callbackValue = className.call(el, i, el.className) if (!callbackValue) return classNames = callbackValue.trim().split(" ") classNamesLen = classNames.length } for (var j = 0; j < classNamesLen; j++) { var name = classNames[j] if (!name) continue bool == null ? el.classList[method](name) : el.classList.toggle(name, bool) } }) } function removeDuplicates(arr) { var cleanDom = [] var cleanDomLen = 0 var arrLen = arr.length for (var i = 0; i < arrLen; i++) { var el = arr[i] var duplicate = false for (var j = 0; j < cleanDomLen; j++) { if (el !== cleanDom[j]) continue duplicate = true break } if (duplicate) continue cleanDom[cleanDomLen++] = el } return cleanDom } function selectAdjacentSiblings(position, selector) { var dom = [] var self = this this.each(function() { var el = this[position + "ElementSibling"] if (!el) return if (!selector || self.is(selector, el)) { dom.push(el) } }) return Sprint(dom) } function selectElements(selector, context) { context = context || d // class, id, tag name or universal selector if (/^[\#.]?[\w-]+$/.test(selector)) { var firstChar = selector[0] if (firstChar == ".") { return toArray(context.getElementsByClassName(selector.slice(1))) } if (firstChar == "#") { var el = context.getElementById(selector.slice(1)) return el ? [el] : [] } if (selector == "body") { return [d.body] } return toArray(context.getElementsByTagName(selector)) } return toArray(context.querySelectorAll(selector)) } function toArray(obj) { var arr = [] var i = obj.length while (i--) { arr[i] = obj[i] } return arr } function wrap(wrappingElement, variant) { if (typeof wrappingElement == "function") { this.each(function(i) { Sprint(this)[variant == "inner" ? "wrapInner" : "wrap"](wrappingElement.call(this, i)) }) } else { variant == "all" ? callback.call(this) : this.each(callback) } function callback() { var wrap = Sprint(wrappingElement).clone(true).get(0) var innerWrap = wrap while (innerWrap.firstChild) { innerWrap = innerWrap.firstChild } if (variant == "inner") { while (this.firstChild) { innerWrap.appendChild(this.firstChild) } this.appendChild(wrap) } else { var el = variant == "all" ? this.get(0) : this var prt = el.parentNode var next = el.nextSibling variant == "all" ? this.each(function() { innerWrap.appendChild(this) }) : innerWrap.appendChild(el) prt.insertBefore(wrap, next) } } return this } // constructor function Init(selector, context) { switch (typeof selector) { case "string": if (selector[0] == "<") { var tmp = d.createElement("div") tmp.innerHTML = selector.trim() this.dom = [tmp.firstChild.cloneNode(true)] } else { if (context && context instanceof Init) { this.dom = context.find(selector).get() } else { this.dom = selectElements(selector, context) } } this.length = this.dom.length break case "function": this.dom = [d] this.length = 1 this.on("DOMContentLoaded", selector) break default: if (selector instanceof Init) { return selector } if (Array.isArray(selector)) { this.dom = selector } else if ( selector instanceof NodeList || selector instanceof HTMLCollection ) { this.dom = toArray(selector) } else { this.dom = [selector] } this.length = this.dom.length } } Init.prototype = { add: function(selector) { var added = Sprint(selector) var dom = added.get() this.each(function() { dom.push(this) }) added.length = dom.length return added }, addClass: function(className) { return manipulateClass.call(this, "add", className) }, after: function() { insertHTML.call(this, "afterend", arguments) return this }, append: function() { insertHTML.call(this, "beforeend", arguments) return this }, appendTo: function(target) { return Sprint(insertHTML.call(Sprint(target), "beforeend", [this])) }, attr: function(name, value) { var stringValue = typeof value == "string" if (stringValue || typeof value == "function") { return this.each(function(i) { this.setAttribute( name, stringValue ? value : value.call(this, i, this.getAttribute(name)) ) }) } if (typeof name == "object") { var attrNames = Object.keys(name) var attrNamesLen = attrNames.length return this.each(function() { for (var i = 0; i < attrNamesLen; i++) { var attribute = attrNames[i] this.setAttribute(attribute, name[attribute]) } }) } var attrValue = this.get(0).getAttribute(name) if (attrValue == null) { return undefined } if (!attrValue) { return name } return attrValue }, before: function() { insertHTML.call(this, "beforebegin", arguments) return this }, children: function(selector) { var dom = [] var self = this this.each(function() { var nodes = this.children var nodesLen = nodes.length for (var i = 0; i < nodesLen; i++) { var node = nodes[i] if (!selector || self.is(selector, node)) { dom.push(node) } } }) return Sprint(dom) }, clone: function(withEvents) { var cloned = [] this.each(function() { var clone = this.cloneNode(true) withEvents && duplicateEventListeners(this, clone) cloned.push(clone) }) return Sprint(cloned) }, closest: function(selector, context) { return findAncestors.call(this, false, false, true, selector, context) }, css: function(property, value) { var valueType = typeof value var isString = valueType == "string" // set if (isString || valueType == "number") { var isRelativeValue = isString && /=/.test(value) if (isRelativeValue) { var relativeValue = parseInt(value[0] + value.slice(2)) } return this.each(function() { if (isRelativeValue) { var current = parseInt(getComputedStyle(this).getPropertyValue(property)) var result = current + relativeValue } this.style[property] = addPx(property, isRelativeValue ? result : value) }) } // set if (valueType == "function") { return this.each(function(index) { var oldValue = getComputedStyle(this).getPropertyValue(property) this.style[property] = value.call(this, index, oldValue) }) } // read if (typeof property == "string") { return getComputedStyle(this.get(0)).getPropertyValue(property) } // read if (Array.isArray(property)) { var o = {} var styles = getComputedStyle(this.get(0)) var propertyLen = property.length for (var i = 0; i < propertyLen; i++) { var prop = property[i] o[prop] = styles.getPropertyValue(prop) } return o } // set var properties = Object.keys(property) var propertiesLen = properties.length return this.each(function() { for (var i = 0; i < propertiesLen; i++) { var prop = properties[i] this.style[prop] = addPx(prop, property[prop]) } }) }, each: function(callback) { // callback(index, element) where element == this var dom = this.dom var len = this.length for (var i = 0; i < len; i++) { var node = dom[i] callback.call(node, i, node) } return this }, empty: function() { return this.each(function() { this.innerHTML = "" }) }, eq: function(index) { return Sprint(this.get(index)) }, filter: function(selector) { var dom = [] switch (typeof selector) { case "string": var self = this this.each(function() { self.is(selector, this) && dom.push(this) }) break case "function": this.each(function(index, el) { selector.call(this, index, el) && dom.push(this) }) break default: return this } return Sprint(dom) }, find: function(selector) { // .find(selector) if (typeof selector == "string") { var dom = [] this.each(function() { var elements = selectElements(selector, this) var elementsLen = elements.length for (var i = 0; i < elementsLen; i++) { dom.push(elements[i]) } }) return Sprint(removeDuplicates(dom)) } // .find(element) return findDomElements.call(this, selector) }, first: function() { return this.eq(0) }, get: function(index) { if (index == null) { return this.dom } if (index < 0) { index += this.length } return this.dom[index] }, has: function(selector) { // .has(selector) if (typeof selector == "string") { var dom = [] this.each(function() { selectElements(selector, this)[0] && dom.push(this) }) return Sprint(dom) } // .has(contained) return findDomElements.call(this, selector, true) }, hasClass: function(name) { var i = this.length while (i--) { if (this.get(i).classList.contains(name)) { return true } } return false }, height: function(value) { // read if (value == null) { var el = this.get(0) switch (el) { // height of HTML document case d: var offset = root.offsetHeight var inner = window.innerHeight return offset > inner ? offset : inner // height of the viewport case window: return window.innerHeight // height of an element default: return el.getBoundingClientRect().height } } // set var isFunction = typeof value == "function" var stringValue = isFunction ? "" : addPx("height", value) return this.each(function(index) { if (isFunction) { stringValue = addPx("height", value.call(this, index, Sprint(this).height())) } this.style.height = stringValue }) }, html: function(htmlString) { if (htmlString == null) { return this.get(0).innerHTML } if (typeof htmlString == "string") { return this.each(function() { this.innerHTML = htmlString }) } if (typeof htmlString == "function") { return this.each(function(i) { var content = htmlString.call(this, i, this.innerHTML) Sprint(this).html(content) }) } }, index: function(el) { var toFind var sprintElements if (!el) { toFind = this.get(0) sprintElements = this.first().parent().children() } else if (typeof el == "string") { toFind = this.get(0) sprintElements = Sprint(el) } else { toFind = el instanceof Init ? el.get(0) : el sprintElements = this } var elements = sprintElements.get() var i = elements.length while (i--) { if (elements[i] == toFind) { return i } } return -1 }, insertAfter: function(target) { Sprint(target).after(this) return this }, insertBefore: function(target) { Sprint(target).before(this) return this }, is: function(selector, element) { // element is undocumented, internal-use only. // It gives better perfs as it prevents the creation of many objects in internal methods. var set = element ? [element] : this.get() var setLen = set.length if (typeof selector == "string") { for (var i = 0; i < setLen; i++) { if (set[i][matches](selector)) { return true } } return false } if (typeof selector == "object") { // Sprint object or DOM element(s) var obj if (selector instanceof Init) { obj = selector.get() } else { obj = selector.length ? selector : [selector] } var objLen = obj.length for (var i = 0; i < setLen; i++) { for (var j = 0; j < objLen; j++) { if (set[i] === obj[j]) { return true } } } return false } if (typeof selector == "function") { for (var i = 0; i < setLen; i++) { if (selector.call(this, i, this)) { return true } } return false } }, last: function() { return this.eq(-1) }, map: function(callback) { var values = [] this.each(function(i) { var val = callback.call(this, i, this) if (Array.isArray(val)) { var len = val.length for (var j = 0; j < len; j++) { values.push(val[j]) } } else { val == null || values.push(val) } }) return Sprint(values) }, next: function(selector) { return selectAdjacentSiblings.call(this, "next", selector) }, not: function(selector) { var isFunc = typeof selector == "function" var filtered = [] var self = this this.each(function(i) { if (isFunc) { if (selector.call(this, i, this)) return } else { if (self.is(selector, this)) return } filtered.push(this) }) return Sprint(filtered) }, off: function(type, callback) { switch (arguments.length) { // .off() case 0: return this.each(function() { if (!this.sprintEventListeners) return var events = Object.keys(this.sprintEventListeners) var eventsLen = events.length for (var i = 0; i < eventsLen; i++) { var event = events[i] var handlers = this.sprintEventListeners[event] var handlersLen = handlers.length for (var j = 0; j < handlersLen; j++) { this.removeEventListener(event, handlers[j]) } } this.sprintEventListeners = {} }) // .off(event) case 1: return this.each(function() { if (!this.sprintEventListeners) return var handlers = this.sprintEventListeners[type] var handlersLen = handlers.length for (var i = 0; i < handlersLen; i++) { this.removeEventListener(type, handlers[i]) } this.sprintEventListeners[type] = [] }) // .off(event, handler) case 2: return this.each(function() { if (!this.sprintEventListeners) return var updatedSprintEventListeners = [] var handlers = this.sprintEventListeners[type] var handlersLen = handlers.length for (var i = 0; i < handlersLen; i++) { var handler = handlers[i] callback != handler && updatedSprintEventListeners.push(handler) } this.removeEventListener(type, callback) this.sprintEventListeners[type] = updatedSprintEventListeners }) } }, offset: function(coordinates) { if (!coordinates) { var pos = this.get(0).getBoundingClientRect() return { top: pos.top, left: pos.left } } if (typeof coordinates == "object") { return this.each(function() { var $this = Sprint(this) $this.css("position") == "static" ? $this.css("position", "relative") : $this.css({ top: 0, left: 0 }) var pos = $this.offset() $this.css({ top: coordinates.top - pos.top + "px", left: coordinates.left - pos.left + "px" }) }) } if (typeof coordinates == "function") { return this.each(function(i) { var $this = Sprint(this) var posObj = coordinates.call(this, i, $this.offset()) $this.offset(posObj) }) } }, offsetParent: function() { var dom = [] this.each(function() { var prt = this while (prt != root) { prt = prt.parentNode var pos = getComputedStyle(prt).getPropertyValue("position") if (!pos) break if (pos != "static") { dom.push(prt) return } } dom.push(root) }) return Sprint(dom) }, on: function(type, callback) { return this.each(function() { if (!this.sprintEventListeners) { this.sprintEventListeners = {} } if (!this.sprintEventListeners[type]) { this.sprintEventListeners[type] = [] } this.sprintEventListeners[type].push(callback) this.addEventListener(type, callback) }) }, parent: function(selector) { return findAncestors.call(this, true, true, false, selector) }, parents: function(selector) { /* Differences with jQuery: * 1. $("html").parent() and $("html").parents() return an empty set. * 2. The returned set won't be in reverse order. */ return findAncestors.call(this, true, false, false, selector) }, position: function() { var pos = { first: this.offset(), prt: this.parent().offset() } return { top: pos.first.top - pos.prt.top, left: pos.first.left - pos.prt.left } }, prop: function(propertyName, value) { if (typeof propertyName == "object") { var props = Object.keys(propertyName) var propsLen = props.length return this.each(function() { for (var i = 0; i < propsLen; i++) { var prop = props[i] this[prop] = propertyName[prop] } }) } if (value == null) { return this.get(0)[propertyName] } var isFunc = typeof value == "function" return this.each(function(i) { this[propertyName] = isFunc ? value.call(this, i, this[propertyName]) : value }) }, prepend: function() { insertHTML.call(this, "afterbegin", arguments) return this }, prev: function(selector) { return selectAdjacentSiblings.call(this, "previous", selector) }, remove: function(selector) { var self = this return this.each(function() { if (!selector || self.is(selector, this)) { this.parentNode.removeChild(this) } }) }, removeAttr: function(attributeName) { if (attributeName) { var attributes = attributeName.trim().split(" ") var attributesLen = attributes.length this.each(function() { for (var i = 0; i < attributesLen; i++) { this.removeAttribute(attributes[i]) } }) } return this }, removeClass: function(className) { return manipulateClass.call(this, "remove", className) }, removeProp: function(propertyName) { return this.each(function() { this[propertyName] = undefined }) }, replaceAll: function(target) { Sprint(target).replaceWith(this) return this }, replaceWith: function(newContent) { if (typeof newContent == "function") { return this.each(function(i) { Sprint(this).replaceWith(newContent.call(this, i, this)) }) } return this.before(newContent).remove() }, siblings: function(selector) { var siblings = [] var self = this this.each(function(i, el) { Sprint(this).parent().children().each(function() { if (this == el || (selector && !self.is(selector, this))) return siblings.push(this) }) }) return Sprint(siblings) }, size: function() { return this.length }, slice: function(start, end) { var dom = this.get() var range = [] var i = start >= 0 ? start : start + this.length var l = this.length if (end < 0) { l += end } else if (end >= 0) { l = end > this.length ? this.length : end } for (; i < l; i++) { range.push(dom[i]) } return Sprint(range) }, text: function(content) { if (content == null) { var textContents = [] this.each(function() { textContents.push(this.textContent) }) return textContents.join("") } var isFunc = typeof content == "function" return this.each(function(i) { this.textContent = isFunc ? content.call(this, i, this.textContent) : content }) }, toggleClass: function(className, bool) { return manipulateClass.call(this, "toggle", className, bool) }, val: function(value) { if (value == null) { var el = this.get(0) if (el.multiple) { var values = [] this.first().children(":checked").each(function() { values.push(this.value) }) return values } return el.value } if (typeof value == "string") { return this.each(function() { this.value = value }) } if (Array.isArray(value)) { var self = this return this.each(function() { if (this.multiple) { self.children().each(function() { selectMatchedValues(this, "selected") }) return } selectMatchedValues(this, "checked") }) } if (typeof value == "function") { return this.each(function(i) { Sprint(this).val(value.call(this, i, this.value)) }) } function selectMatchedValues(domEl, attr) { domEl[attr] = value.indexOf(domEl.value) < 0 ? false : true } }, wrap: function(wrappingElement) { return wrap.call(this, wrappingElement) }, wrapAll: function(wrappingElement) { return wrap.call(this, wrappingElement, "all") }, wrapInner: function(wrappingElement) { return wrap.call(this, wrappingElement, "inner") } } // public Sprint = function(selector, context) { return new Init(selector, context) } if (window.$ == null) { window.$ = Sprint } })();
jdh8/cdnjs
ajax/libs/sprint/0.5.1/sprint.js
JavaScript
mit
30,521
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../../../../favicon.ico"> <title>Grid Template for Bootstrap</title> <!-- Bootstrap core CSS --> <link href="../../../../dist/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="grid.css" rel="stylesheet"> </head> <body> <div class="container"> <h1>Bootstrap grid examples</h1> <p class="lead">Basic grid layouts to get you familiar with building within the Bootstrap grid system.</p> <h3>Five grid tiers</h3> <p>There are five tiers to the Bootstrap grid system, one for each range of devices we support. Each tier starts at a minimum viewport size and automatically applies to the larger devices unless overridden.</p> <div class="row"> <div class="col-4">.col-4</div> <div class="col-4">.col-4</div> <div class="col-4">.col-4</div> </div> <div class="row"> <div class="col-sm-4">.col-sm-4</div> <div class="col-sm-4">.col-sm-4</div> <div class="col-sm-4">.col-sm-4</div> </div> <div class="row"> <div class="col-md-4">.col-md-4</div> <div class="col-md-4">.col-md-4</div> <div class="col-md-4">.col-md-4</div> </div> <div class="row"> <div class="col-lg-4">.col-lg-4</div> <div class="col-lg-4">.col-lg-4</div> <div class="col-lg-4">.col-lg-4</div> </div> <div class="row"> <div class="col-xl-4">.col-xl-4</div> <div class="col-xl-4">.col-xl-4</div> <div class="col-xl-4">.col-xl-4</div> </div> <h3>Three equal columns</h3> <p>Get three equal-width columns <strong>starting at desktops and scaling to large desktops</strong>. On mobile devices, tablets and below, the columns will automatically stack.</p> <div class="row"> <div class="col-md-4">.col-md-4</div> <div class="col-md-4">.col-md-4</div> <div class="col-md-4">.col-md-4</div> </div> <h3>Three unequal columns</h3> <p>Get three columns <strong>starting at desktops and scaling to large desktops</strong> of various widths. Remember, grid columns should add up to twelve for a single horizontal block. More than that, and columns start stacking no matter the viewport.</p> <div class="row"> <div class="col-md-3">.col-md-3</div> <div class="col-md-6">.col-md-6</div> <div class="col-md-3">.col-md-3</div> </div> <h3>Two columns</h3> <p>Get two columns <strong>starting at desktops and scaling to large desktops</strong>.</p> <div class="row"> <div class="col-md-8">.col-md-8</div> <div class="col-md-4">.col-md-4</div> </div> <h3>Full width, single column</h3> <p class="text-warning">No grid classes are necessary for full-width elements.</p> <hr> <h3>Two columns with two nested columns</h3> <p>Per the documentation, nesting is easy—just put a row of columns within an existing column. This gives you two columns <strong>starting at desktops and scaling to large desktops</strong>, with another two (equal widths) within the larger column.</p> <p>At mobile device sizes, tablets and down, these columns and their nested columns will stack.</p> <div class="row"> <div class="col-md-8"> .col-md-8 <div class="row"> <div class="col-md-6">.col-md-6</div> <div class="col-md-6">.col-md-6</div> </div> </div> <div class="col-md-4">.col-md-4</div> </div> <hr> <h3>Mixed: mobile and desktop</h3> <p>The Bootstrap v4 grid system has five tiers of classes: xs (extra small), sm (small), md (medium), lg (large), and xl (extra large). You can use nearly any combination of these classes to create more dynamic and flexible layouts.</p> <p>Each tier of classes scales up, meaning if you plan on setting the same widths for xs and sm, you only need to specify xs.</p> <div class="row"> <div class="col-12 col-md-8">.col-12 .col-md-8</div> <div class="col-6 col-md-4">.col-6 .col-md-4</div> </div> <div class="row"> <div class="col-6 col-md-4">.col-6 .col-md-4</div> <div class="col-6 col-md-4">.col-6 .col-md-4</div> <div class="col-6 col-md-4">.col-6 .col-md-4</div> </div> <div class="row"> <div class="col-6">.col-6</div> <div class="col-6">.col-6</div> </div> <hr> <h3>Mixed: mobile, tablet, and desktop</h3> <p></p> <div class="row"> <div class="col-12 col-sm-6 col-lg-8">.col-12 .col-sm-6 .col-lg-8</div> <div class="col-6 col-lg-4">.col-6 .col-lg-4</div> </div> <div class="row"> <div class="col-6 col-sm-4">.col-6 .col-sm-4</div> <div class="col-6 col-sm-4">.col-6 .col-sm-4</div> <div class="col-6 col-sm-4">.col-6 .col-sm-4</div> </div> </div> <!-- /container --> </body> </html>
Rodomantsev/angularTemp
src/styles/libs/bootstrap-4.0.0-beta.2/docs/4.0/examples/grid/index.html
HTML
mit
5,271
require 'spec_helper' describe Forem::FormattingHelper do # This formatter uses the simple_format helper, which will um.. # simply format things. Yes, that'll do. describe "as_formatted_html(text)" do let(:raw_html) {"<p>html</p>"} let(:text) {'three blind mice'} before { Forem.formatter = nil } describe "unsafe html" do subject { helper.as_formatted_html(raw_html) } it "is escaped" do subject.should == "<p>" + ERB::Util.h(raw_html) + "</p>" end it {should be_html_safe} end describe "safe html" do subject { helper.as_formatted_html(raw_html.html_safe) } specify "is not escaped" do subject.should == "<p>" + raw_html + "</p>" end it {should be_html_safe} end end describe "as_quoted_text" do let(:raw_html) {"<p>html</p>"} describe "default formatter" do before { Forem.formatter = nil } describe "unsafe html" do subject { helper.as_quoted_text(raw_html) } it "is escaped" do subject.should == "<blockquote>" + ERB::Util.h(raw_html) + "</blockquote>\n\n" end it {should be_html_safe} end describe "safe html" do subject { helper.as_quoted_text(raw_html.html_safe) } specify "is not escaped" do subject.should == "<blockquote>" + raw_html + "</blockquote>\n\n" end it {should be_html_safe} end end describe "Redcarpet" do let(:markdown) { "**strong text**" } before { Forem.formatter = Forem::Formatters::Redcarpet } describe "uses <blockquote> if no blockquote method" do subject { helper.as_quoted_text(markdown) } before { Forem.formatter.stub('respond_to?').with(:blockquote).and_return(false) } it "wraps the content in blockquotes" do subject.should == "<blockquote>#{markdown}</blockquote>\n\n" end it {should be_html_safe} end describe "uses formatter quoting method if exists" do subject { helper.as_quoted_text(raw_html) } before { Forem.formatter.stub('respond_to?').with(:blockquote).and_return(true) Forem.formatter.stub('respond_to?').with(:sanitize).and_return(false) Forem.formatter.stub(:blockquote).and_return("> #{markdown}") } it "quotes the original content" do subject.should == "> #{markdown}" end it {should be_html_safe} end describe "uses formatter sanitize method if exists" do subject { helper.as_formatted_html(markdown) } before { Forem.formatter.stub('respond_to?').with(:blockquote).and_return(false) Forem.formatter.stub('respond_to?').with(:sanitize).and_return(true) Forem.formatter.stub(:sanitize).and_return("sanitized it") } it {subject.should == "<p>sanitized it</p>"} end end end end
railsdev/forem
spec/helpers/formatting_helper_spec.rb
Ruby
mit
2,968
/* * adonisuniv_wm5102.c * * Copyright (c) 2012 Samsung Electronics Co. Ltd * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/platform_device.h> #include <linux/clk.h> #include <linux/io.h> #include <linux/gpio.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/workqueue.h> #include <linux/input.h> #include <linux/wakelock.h> #include <linux/suspend.h> #include <sound/soc.h> #include <sound/soc-dapm.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/jack.h> #include <linux/regmap.h> #include <mach/regs-clock.h> #include <mach/pmu.h> #include <mach/gpio.h> #include <mach/gpio-exynos.h> #include <mach/exynos5-audio.h> #include <linux/mfd/arizona/registers.h> #include <linux/mfd/arizona/core.h> #include "i2s.h" #include "i2s-regs.h" #include "../codecs/wm5102.h" #define USE_BIAS_LEVEL_POST #define ADONISUNIV_DEFAULT_MCLK1 24000000 #define ADONISUNIV_DEFAULT_MCLK2 32768 #define ADONISUNIV_TELCLK_RATE (48000 * 512) #define CLK_MODE_MEDIA 0 #define CLK_MODE_TELEPHONY 1 typedef enum { MICBIAS1ON, MICBIAS2ON, MICBIAS3ON, MICBIAS1OFF, MICBIAS2OFF, MICBIAS3OFF } micbias_type; struct wm5102_machine_priv { int clock_mode; struct snd_soc_jack jack; struct snd_soc_codec *codec; struct snd_soc_dai *aif[3]; struct delayed_work mic_work; struct wake_lock jackdet_wake_lock; int aif2mode; int micbias_mode; int aif1rate; int aif2rate; }; static int lhpf1_coeff; static int lhpf2_coeff; static unsigned int lhpf_filter_values[] = { 0xF03A, 0xF04B, 0xF099, 0x0000, 0x0000 }; const char *lhpf_filter_text[] = { "64Hz", "130Hz", "267Hz", "user defined1", "user defined2" }; const char *aif2_mode_text[] = { "Slave", "Master" }; const char *micbias_mode_text[] = { "BIAS1ON", "BIAS2ON", "BIAS3ON", "BIAS1OFF", "BIAS2OFF", "BIAS3OFF" }; static const struct soc_enum lhpf_filter_mode_enum[] = { SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(lhpf_filter_text), lhpf_filter_text), }; static const struct soc_enum aif2_mode_enum[] = { SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(aif2_mode_text), aif2_mode_text), }; static const struct soc_enum micbias_mode_enum[] = { SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(micbias_mode_text), micbias_mode_text), }; static struct { int min; /* Minimum impedance */ int max; /* Maximum impedance */ unsigned int gain; /* Register value to set for this measurement */ } hp_gain_table[] = { { 0, 42, 0x6c | ARIZONA_OUT_VU }, { 43, 100, 0x70 | ARIZONA_OUT_VU }, { 101, 200, 0x74 | ARIZONA_OUT_VU }, { 201, 450, 0x78 | ARIZONA_OUT_VU }, { 451, 1000, 0x7c | ARIZONA_OUT_VU }, { 1001, INT_MAX, 0x6c | ARIZONA_OUT_VU }, }; static struct snd_soc_codec *the_codec; void adonisuniv_wm5102_hpdet_cb(unsigned int meas) { int i; WARN_ON(!the_codec); if (!the_codec) return; for (i = 0; i < ARRAY_SIZE(hp_gain_table); i++) { if (meas < hp_gain_table[i].min || meas > hp_gain_table[i].max) continue; dev_crit(the_codec->dev, "SET GAIN %x for %d ohms\n", hp_gain_table[i].gain, meas); snd_soc_write(the_codec, ARIZONA_DAC_DIGITAL_VOLUME_1L, hp_gain_table[i].gain); snd_soc_write(the_codec, ARIZONA_DAC_DIGITAL_VOLUME_1R, hp_gain_table[i].gain); } } static int adonisuniv_start_sysclk(struct snd_soc_card *card) { struct wm5102_machine_priv *priv = snd_soc_card_get_drvdata(card); int ret; int fs; if (priv->aif1rate >= 192000) fs = 256; else fs = 512; ret = snd_soc_codec_set_pll(priv->codec, WM5102_FLL1, ARIZONA_CLK_SRC_MCLK1, ADONISUNIV_DEFAULT_MCLK1, priv->aif1rate * fs); if (ret != 0) { dev_err(priv->codec->dev, "Failed to start FLL1: %d\n", ret); return ret; } return ret; } static int adonisuniv_stop_sysclk(struct snd_soc_card *card) { struct wm5102_machine_priv *priv = snd_soc_card_get_drvdata(card); int ret; ret = snd_soc_codec_set_pll(priv->codec, WM5102_FLL1, 0, 0, 0); if (ret != 0) { dev_err(priv->codec->dev, "Failed to stop FLL1: %d\n", ret); return ret; } ret = snd_soc_codec_set_sysclk(priv->codec, ARIZONA_CLK_SYSCLK, 0, 0, 0); if (ret != 0) { dev_err(priv->codec->dev, "Failed to stop SYSCLK: %d\n", ret); return ret; } return ret; } #ifdef USE_BIAS_LEVEL_POST static int adonisuniv_set_bias_level(struct snd_soc_card *card, struct snd_soc_dapm_context *dapm, enum snd_soc_bias_level level) { struct snd_soc_dai *codec_dai = card->rtd[0].codec_dai; if (dapm->dev != codec_dai->dev) return 0; dev_info(card->dev, "%s: %d\n", __func__, level); switch (level) { case SND_SOC_BIAS_PREPARE: if (dapm->bias_level != SND_SOC_BIAS_STANDBY) break; adonisuniv_start_sysclk(card); break; default: break; } return 0; } static int adonisuniv_set_bias_level_post(struct snd_soc_card *card, struct snd_soc_dapm_context *dapm, enum snd_soc_bias_level level) { struct snd_soc_dai *codec_dai = card->rtd[0].codec_dai; if (dapm->dev != codec_dai->dev) return 0; dev_info(card->dev, "%s: %d\n", __func__, level); switch (level) { case SND_SOC_BIAS_STANDBY: adonisuniv_stop_sysclk(card); break; default: break; } dapm->bias_level = level; return 0; } #endif int adonisuniv_set_media_clocking(struct wm5102_machine_priv *priv) { struct snd_soc_codec *codec = priv->codec; int ret; int fs; if (priv->aif1rate >= 192000) fs = 256; else fs = 512; ret = snd_soc_codec_set_pll(codec, WM5102_FLL1_REFCLK, ARIZONA_FLL_SRC_NONE, 0, 0); if (ret != 0) { dev_err(codec->dev, "Failed to start FLL1 REF: %d\n", ret); return ret; } ret = snd_soc_codec_set_pll(codec, WM5102_FLL1, ARIZONA_CLK_SRC_MCLK1, ADONISUNIV_DEFAULT_MCLK1, priv->aif1rate * fs); if (ret != 0) { dev_err(codec->dev, "Failed to start FLL1: %d\n", ret); return ret; } ret = snd_soc_codec_set_sysclk(codec, ARIZONA_CLK_SYSCLK, ARIZONA_CLK_SRC_FLL1, priv->aif1rate * fs, SND_SOC_CLOCK_IN); if (ret < 0) dev_err(codec->dev, "Failed to set SYSCLK to FLL1: %d\n", ret); ret = snd_soc_codec_set_sysclk(codec, ARIZONA_CLK_ASYNCCLK, ARIZONA_CLK_SRC_FLL2, ADONISUNIV_TELCLK_RATE, SND_SOC_CLOCK_IN); if (ret < 0) dev_err(codec->dev, "Unable to set ASYNCCLK to FLL2: %d\n", ret); /* AIF1 from SYSCLK, AIF2 and 3 from ASYNCCLK */ ret = snd_soc_dai_set_sysclk(priv->aif[0], ARIZONA_CLK_SYSCLK, 0, 0); if (ret < 0) dev_err(codec->dev, "Can't set AIF1 to SYSCLK: %d\n", ret); ret = snd_soc_dai_set_sysclk(priv->aif[1], ARIZONA_CLK_ASYNCCLK, 0, 0); if (ret < 0) dev_err(codec->dev, "Can't set AIF2 to ASYNCCLK: %d\n", ret); ret = snd_soc_dai_set_sysclk(priv->aif[2], ARIZONA_CLK_ASYNCCLK, 0, 0); if (ret < 0) dev_err(codec->dev, "Can't set AIF3 to ASYNCCLK: %d\n", ret); return 0; } static void adonisuniv_gpio_init(void) { #ifdef GPIO_MICBIAS_EN int err; /* Main Microphone BIAS */ err = gpio_request(GPIO_MICBIAS_EN, "MAINMIC_BIAS"); if (err) { pr_err(KERN_ERR "MIC_BIAS_EN GPIO set error!\n"); return; } gpio_direction_output(GPIO_MICBIAS_EN, 1); /*This is tempary code to enable for main mic.(force enable GPIO) */ gpio_set_value(GPIO_MICBIAS_EN, 0); #endif #ifdef GPIO_SUB_MICBIAS_EN int ret; /* Sub Microphone BIAS */ ret = gpio_request(GPIO_SUB_MICBIAS_EN, "SUBMIC_BIAS"); if (ret) { pr_err(KERN_ERR "SUBMIC_BIAS_EN GPIO set error!\n"); return; } gpio_direction_output(GPIO_SUB_MICBIAS_EN, 1); gpio_set_value(GPIO_SUB_MICBIAS_EN, 0); #endif } /* * AdnoisUniv wm5102 GPIO enable configure. */ static int adonisuniv_ext_mainmicbias(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_card *card = w->dapm->card; struct snd_soc_codec *codec = card->rtd[0].codec; #ifdef GPIO_MICBIAS_EN switch (event) { case SND_SOC_DAPM_PRE_PMU: gpio_set_value(GPIO_MICBIAS_EN, 1); break; case SND_SOC_DAPM_POST_PMD: gpio_set_value(GPIO_MICBIAS_EN, 0); break; } dev_dbg(codec->dev, "Main Mic BIAS: %d\n", event); #endif return 0; } static int adonisuniv_ext_submicbias(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { #ifdef GPIO_SUB_MICBIAS_EN struct snd_soc_card *card = w->dapm->card; struct snd_soc_codec *codec = card->rtd[0].codec; switch (event) { case SND_SOC_DAPM_PRE_PMU: gpio_set_value(GPIO_SUB_MICBIAS_EN, 1); break; case SND_SOC_DAPM_POST_PMD: gpio_set_value(GPIO_SUB_MICBIAS_EN, 0); break; } dev_dbg(codec->dev, "Sub Mic BIAS: %d\n", event); #endif return 0; } static int get_lhpf1_coeff(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { ucontrol->value.integer.value[0] = lhpf1_coeff; return 0; } static int set_lhpf1_coeff(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct regmap *regmap = codec->control_data; lhpf1_coeff = ucontrol->value.integer.value[0]; dev_info(codec->dev, "%s: lhpf1 mode=%d, val=0x%x\n", __func__, lhpf1_coeff, lhpf_filter_values[lhpf1_coeff]); regmap_update_bits(regmap, ARIZONA_HPLPF1_2, ARIZONA_LHPF1_COEFF_MASK, lhpf_filter_values[lhpf1_coeff]); return 0; } static int get_lhpf2_coeff(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { ucontrol->value.integer.value[0] = lhpf2_coeff; return 0; } static int set_lhpf2_coeff(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct regmap *regmap = codec->control_data; lhpf2_coeff = ucontrol->value.integer.value[0]; dev_info(codec->dev, "%s: lhpf2 mode=%d, val=0x%x (%p)\n", __func__, lhpf2_coeff, lhpf_filter_values[lhpf2_coeff], codec); regmap_update_bits(regmap, ARIZONA_HPLPF2_2, ARIZONA_LHPF2_COEFF_MASK, lhpf_filter_values[lhpf2_coeff]); return 0; } static int get_aif2_mode(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct wm5102_machine_priv *priv = snd_soc_card_get_drvdata(codec->card); ucontrol->value.integer.value[0] = priv->aif2mode; return 0; } static int set_aif2_mode(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct wm5102_machine_priv *priv = snd_soc_card_get_drvdata(codec->card); struct snd_soc_dai *codec_dai = codec->card->rtd[0].codec_dai; if((priv->aif2mode == 1) && (ucontrol->value.integer.value[0] == 0)) { int ret; ret = snd_soc_dai_set_pll(codec_dai, WM5102_FLL2, 0, 0, 0); if (ret != 0) dev_err(codec->dev, "Failed to stop FLL2: %d\n", ret); } priv->aif2mode = ucontrol->value.integer.value[0]; dev_info(codec->dev, "set aif2 mode: %s\n", aif2_mode_text[priv->aif2mode]); return 0; } static int get_micbias_mode(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct wm5102_machine_priv *priv = snd_soc_card_get_drvdata(codec->card); ucontrol->value.integer.value[0] = priv->micbias_mode; return 0; } static int set_micbias_mode(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct regmap *regmap = codec->control_data; micbias_type micbias = ucontrol->value.integer.value[0]; switch (micbias) { case MICBIAS1ON: regmap_update_bits(regmap, ARIZONA_MIC_BIAS_CTRL_1, ARIZONA_MICB1_ENA_MASK, ARIZONA_MICB1_ENA); break; case MICBIAS2ON: regmap_update_bits(regmap, ARIZONA_MIC_BIAS_CTRL_2, ARIZONA_MICB2_ENA_MASK, ARIZONA_MICB2_ENA); break; case MICBIAS3ON: regmap_update_bits(regmap, ARIZONA_MIC_BIAS_CTRL_3, ARIZONA_MICB3_ENA_MASK, ARIZONA_MICB3_ENA); break; case MICBIAS1OFF: regmap_update_bits(regmap, ARIZONA_MIC_BIAS_CTRL_1, ARIZONA_MICB1_ENA_MASK, 0); break; case MICBIAS2OFF: regmap_update_bits(regmap, ARIZONA_MIC_BIAS_CTRL_2, ARIZONA_MICB2_ENA_MASK, 0); break; case MICBIAS3OFF: regmap_update_bits(regmap, ARIZONA_MIC_BIAS_CTRL_3, ARIZONA_MICB3_ENA_MASK, 0); break; default: break; } dev_info(codec->dev, "set micbias mode: %s\n", micbias_mode_text[micbias]); return 0; } static const struct snd_kcontrol_new adonisuniv_codec_controls[] = { SOC_ENUM_EXT("LHPF1 COEFF FILTER", lhpf_filter_mode_enum[0], get_lhpf1_coeff, set_lhpf1_coeff), SOC_ENUM_EXT("LHPF2 COEFF FILTER", lhpf_filter_mode_enum[0], get_lhpf2_coeff, set_lhpf2_coeff), SOC_ENUM_EXT("AIF2 Mode", aif2_mode_enum[0], get_aif2_mode, set_aif2_mode), SOC_ENUM_EXT("MICBIAS Mode", micbias_mode_enum[0], get_micbias_mode, set_micbias_mode), }; static const struct snd_kcontrol_new adonisuniv_controls[] = { SOC_DAPM_PIN_SWITCH("HP"), SOC_DAPM_PIN_SWITCH("SPK"), SOC_DAPM_PIN_SWITCH("RCV"), SOC_DAPM_PIN_SWITCH("VPS"), SOC_DAPM_PIN_SWITCH("HDMI"), SOC_DAPM_PIN_SWITCH("Main Mic"), SOC_DAPM_PIN_SWITCH("Sub Mic"), SOC_DAPM_PIN_SWITCH("3rd Mic"), SOC_DAPM_PIN_SWITCH("Headset Mic"), }; const struct snd_soc_dapm_widget adonisuniv_dapm_widgets[] = { SND_SOC_DAPM_OUTPUT("HDMIL"), SND_SOC_DAPM_OUTPUT("HDMIR"), SND_SOC_DAPM_HP("HP", NULL), SND_SOC_DAPM_SPK("SPK", NULL), SND_SOC_DAPM_SPK("RCV", NULL), SND_SOC_DAPM_LINE("VPS", NULL), SND_SOC_DAPM_LINE("HDMI", NULL), SND_SOC_DAPM_MIC("Headset Mic", NULL), SND_SOC_DAPM_MIC("Main Mic", adonisuniv_ext_mainmicbias), SND_SOC_DAPM_MIC("Sub Mic", adonisuniv_ext_submicbias), SND_SOC_DAPM_MIC("3rd Mic", NULL), }; const struct snd_soc_dapm_route adonisuniv_dapm_routes[] = { { "HDMIL", NULL, "AIF1RX1" }, { "HDMIR", NULL, "AIF1RX2" }, { "HDMI", NULL, "HDMIL" }, { "HDMI", NULL, "HDMIR" }, { "HP", NULL, "HPOUT1L" }, { "HP", NULL, "HPOUT1R" }, { "SPK", NULL, "SPKOUTLN" }, { "SPK", NULL, "SPKOUTLP" }, { "SPK", NULL, "SPKOUTRN" }, { "SPK", NULL, "SPKOUTRP" }, { "VPS", NULL, "HPOUT2L" }, { "VPS", NULL, "HPOUT2R" }, { "RCV", NULL, "EPOUTN" }, { "RCV", NULL, "EPOUTP" }, { "IN1L", NULL, "Main Mic" }, { "Main Mic", NULL, "MICVDD" }, { "Headset Mic", NULL, "MICBIAS1" }, { "IN1R", NULL, "Headset Mic" }, { "Sub Mic", NULL, "MICBIAS3" }, { "IN2L", NULL, "Sub Mic" }, { "3rd Mic", NULL, "MICBIAS2" }, { "IN2R", NULL, "3rd Mic" }, }; static int adonisuniv_wm5102_aif1_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; struct snd_soc_dai *codec_dai = rtd->codec_dai; struct snd_soc_codec *codec = rtd->codec; struct wm5102_machine_priv *priv = snd_soc_card_get_drvdata(codec->card); int ret; dev_info(codec_dai->dev, "aif1: %dch, %dHz, %dbytes\n", params_channels(params), params_rate(params), params_buffer_bytes(params)); priv->aif1rate = params_rate(params); adonisuniv_set_media_clocking(priv); ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBM_CFM); if (ret < 0) { dev_err(codec_dai->dev, "Failed to set audio format in codec: %d\n", ret); return ret; } /* Set the cpu DAI configuration */ ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBM_CFM); if (ret < 0) { dev_err(codec_dai->dev, "Failed to set audio format in cpu: %d\n", ret); return ret; } ret = snd_soc_dai_set_sysclk(cpu_dai, SAMSUNG_I2S_OPCLK, 0, MOD_OPCLK_PCLK); if (ret < 0) { dev_err(codec_dai->dev, "Failed to set system clock in cpu: %d\n", ret); return ret; } return 0; } static int adonisuniv_wm5102_aif1_hw_free(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_card *card = rtd->card; dev_info(card->dev, "%s\n", __func__); return 0; } /* * AdnoisUniv wm5102 DAI operations. */ static struct snd_soc_ops adonisuniv_wm5102_aif1_ops = { .hw_params = adonisuniv_wm5102_aif1_hw_params, .hw_free = adonisuniv_wm5102_aif1_hw_free, }; static int adonisuniv_wm5102_aif2_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *codec_dai = rtd->codec_dai; struct wm5102_machine_priv *priv = snd_soc_card_get_drvdata(rtd->card); int ret; int bclk; dev_info(codec_dai->dev, "aif2: %dch, %dHz, %dbytes\n", params_channels(params), params_rate(params), params_buffer_bytes(params)); if (priv->aif2rate != params_rate(params)) { ret = snd_soc_dai_set_pll(codec_dai, WM5102_FLL2, 0, 0, 0); if (ret != 0) dev_err(codec_dai->dev, "Failed to stop FLL2: %d\n", ret); priv->aif2rate = params_rate(params); } switch (priv->aif2rate) { case 8000: bclk = 256000; break; case 16000: bclk = 512000; break; default: dev_warn(codec_dai->dev, "Unsupported LRCLK %d, falling back to 8000Hz\n", (int)params_rate(params)); bclk = 256000; } /* Set the codec DAI configuration, aif2_mode:0 is slave */ if (priv->aif2mode == 0) ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBS_CFS); else ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBM_CFM); if (ret < 0) { dev_err(codec_dai->dev, "Failed to set audio format in codec: %d\n", ret); return ret; } if (priv->aif2mode == 0) { ret = snd_soc_dai_set_pll(codec_dai, WM5102_FLL2_REFCLK, ARIZONA_FLL_SRC_MCLK1, ADONISUNIV_DEFAULT_MCLK1, ADONISUNIV_TELCLK_RATE); if (ret != 0) { dev_err(codec_dai->dev, "Failed to start FLL2 REF: %d\n", ret); return ret; } ret = snd_soc_dai_set_pll(codec_dai, WM5102_FLL2, ARIZONA_FLL_SRC_AIF2BCLK, bclk, ADONISUNIV_TELCLK_RATE); if (ret != 0) { dev_err(codec_dai->dev, "Failed to start FLL2%d\n", ret); return ret; } } else { ret = snd_soc_dai_set_pll(codec_dai, WM5102_FLL2, 0, 0, 0); if (ret != 0) dev_err(codec_dai->dev, "Failed to stop FLL2: %d\n", ret); ret = snd_soc_dai_set_pll(codec_dai, WM5102_FLL2_REFCLK, ARIZONA_FLL_SRC_NONE, 0, 0); if (ret != 0) { dev_err(codec_dai->dev, "Failed to start FLL2 REF: %d\n", ret); return ret; } ret = snd_soc_dai_set_pll(codec_dai, WM5102_FLL2, ARIZONA_CLK_SRC_MCLK1, ADONISUNIV_DEFAULT_MCLK1, ADONISUNIV_TELCLK_RATE); if (ret != 0) { dev_err(codec_dai->dev, "Failed to start FLL2: %d\n", ret); return ret; } } return 0; } static struct snd_soc_ops adonisuniv_wm5102_aif2_ops = { .hw_params = adonisuniv_wm5102_aif2_hw_params, }; static int adonisuniv_wm5102_aif3_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *codec_dai = rtd->codec_dai; int ret; dev_info(codec_dai->dev, "aif3: %dch, %dHz, %dbytes\n", params_channels(params), params_rate(params), params_buffer_bytes(params)); ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBM_CFM); if (ret < 0) { dev_err(codec_dai->dev, "Failed to set BT mode: %d\n", ret); return ret; } return 0; } static struct snd_soc_ops adonisuniv_wm5102_aif3_ops = { .hw_params = adonisuniv_wm5102_aif3_hw_params, }; static int adonisuniv_late_probe(struct snd_soc_card *card) { struct snd_soc_codec *codec = card->rtd[0].codec; struct snd_soc_dai *codec_dai = card->rtd[0].codec_dai; struct snd_soc_dai *cpu_dai = card->rtd[0].cpu_dai; struct wm5102_machine_priv *priv = snd_soc_card_get_drvdata(codec->card); int i, ret; priv->codec = codec; the_codec = codec; for (i = 0; i < 3; i++) priv->aif[i] = card->rtd[i].codec_dai; codec_dai->driver->playback.channels_max = cpu_dai->driver->playback.channels_max; /* close codec device immediately when pcm is closed */ codec->ignore_pmdown_time = true; snd_soc_dapm_ignore_suspend(&codec->dapm, "RCV"); snd_soc_dapm_ignore_suspend(&codec->dapm, "VPS"); snd_soc_dapm_ignore_suspend(&codec->dapm, "SPK"); snd_soc_dapm_ignore_suspend(&codec->dapm, "HP"); snd_soc_dapm_ignore_suspend(&codec->dapm, "AIF2 Playback"); snd_soc_dapm_ignore_suspend(&codec->dapm, "AIF2 Capture"); snd_soc_dapm_ignore_suspend(&codec->dapm, "AIF3 Playback"); snd_soc_dapm_ignore_suspend(&codec->dapm, "AIF3 Capture"); adonisuniv_set_media_clocking(priv); ret = snd_soc_add_codec_controls(codec, adonisuniv_codec_controls, ARRAY_SIZE(adonisuniv_codec_controls)); if (ret < 0) { dev_err(codec->dev, "Failed to add controls to codec: %d\n", ret); return ret; } dev_info(codec->dev, "%s: Successfully created\n", __func__); return snd_soc_dapm_sync(&codec->dapm); } static int adonisuniv_suspend_post(struct snd_soc_card *card) { struct snd_soc_codec *codec = card->rtd[0].codec; int ret; if (codec->active) { dev_info(codec->dev, "sound card is still active state"); return 0; } ret = snd_soc_codec_set_pll(codec, WM5102_FLL1, ARIZONA_CLK_SRC_MCLK1, ADONISUNIV_DEFAULT_MCLK1, 0); if (ret != 0) { dev_err(codec->dev, "Failed to stop FLL1: %d\n", ret); return ret; } ret = snd_soc_codec_set_pll(codec, WM5102_FLL2, 0, 0, 0); if (ret != 0) { dev_err(codec->dev, "Failed to stop FLL2: %d\n", ret); return ret; } ret = snd_soc_codec_set_sysclk(codec, ARIZONA_CLK_SYSCLK, 0, 0, 0); if (ret != 0) { dev_err(codec->dev, "Failed to stop SYSCLK: %d\n", ret); return ret; } exynos5_audio_set_mclk(0, 1); return 0; } static int adonisuniv_resume_pre(struct snd_soc_card *card) { struct wm5102_machine_priv *wm5102_priv = snd_soc_card_get_drvdata(card); exynos5_audio_set_mclk(1, 0); adonisuniv_set_media_clocking(wm5102_priv); return 0; } static struct snd_soc_dai_driver adonisuniv_ext_dai[] = { { .name = "adonisuniv.cp", .playback = { .channels_min = 1, .channels_max = 2, .rate_min = 8000, .rate_max = 48000, .rates = (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000 | SNDRV_PCM_RATE_48000), .formats = SNDRV_PCM_FMTBIT_S16_LE, }, .capture = { .channels_min = 1, .channels_max = 2, .rate_min = 8000, .rate_max = 48000, .rates = (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000 | SNDRV_PCM_RATE_48000), .formats = SNDRV_PCM_FMTBIT_S16_LE, }, }, { .name = "adonisuniv.bt", .playback = { .channels_min = 1, .channels_max = 2, .rate_min = 8000, .rate_max = 16000, .rates = (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000), .formats = SNDRV_PCM_FMTBIT_S16_LE, }, .capture = { .channels_min = 1, .channels_max = 2, .rate_min = 8000, .rate_max = 16000, .rates = (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000), .formats = SNDRV_PCM_FMTBIT_S16_LE, }, }, }; static struct snd_soc_dai_link adonisuniv_dai[] = { { .name = "AdonisUniv_WM5102 Multi Ch", .stream_name = "Pri_Dai", .cpu_dai_name = "samsung-i2s.0", .codec_dai_name = "wm5102-aif1", .platform_name = "samsung-audio", .codec_name = "wm5102-codec", .ops = &adonisuniv_wm5102_aif1_ops, }, { .name = "AdonisUniv_WM5102 Voice", .stream_name = "Voice Tx/Rx", .cpu_dai_name = "adonisuniv.cp", .codec_dai_name = "wm5102-aif2", .platform_name = "snd-soc-dummy", .codec_name = "wm5102-codec", .ops = &adonisuniv_wm5102_aif2_ops, .ignore_suspend = 1, }, { .name = "AdonisUniv_WM5102 BT", .stream_name = "BT Tx/Rx", .cpu_dai_name = "adonisuniv.bt", .codec_dai_name = "wm5102-aif3", .platform_name = "snd-soc-dummy", .codec_name = "wm5102-codec", .ops = &adonisuniv_wm5102_aif3_ops, .ignore_suspend = 1, }, { .name = "AdonisUniv_WM5102 Playback", .stream_name = "Sec_Dai", .cpu_dai_name = "samsung-i2s.4", .codec_dai_name = "wm5102-aif1", #ifdef CONFIG_SND_SAMSUNG_USE_IDMA .platform_name = "samsung-idma", #else .platform_name = "samsung-audio", #endif .codec_name = "wm5102-codec", .ops = &adonisuniv_wm5102_aif1_ops, }, }; static struct snd_soc_card adonisuniv = { .name = "AdonisUniv Sound Card", .owner = THIS_MODULE, .dai_link = adonisuniv_dai, .num_links = ARRAY_SIZE(adonisuniv_dai), .controls = adonisuniv_controls, .num_controls = ARRAY_SIZE(adonisuniv_controls), .dapm_widgets = adonisuniv_dapm_widgets, .num_dapm_widgets = ARRAY_SIZE(adonisuniv_dapm_widgets), .dapm_routes = adonisuniv_dapm_routes, .num_dapm_routes = ARRAY_SIZE(adonisuniv_dapm_routes), .late_probe = adonisuniv_late_probe, .suspend_post = adonisuniv_suspend_post, .resume_pre = adonisuniv_resume_pre, #ifdef USE_BIAS_LEVEL_POST .set_bias_level = adonisuniv_set_bias_level, .set_bias_level_post = adonisuniv_set_bias_level_post, #endif }; static int __devinit snd_adonisuniv_probe(struct platform_device *pdev) { int ret; struct wm5102_machine_priv *wm5102; wm5102 = kzalloc(sizeof *wm5102, GFP_KERNEL); if (!wm5102) { pr_err("Failed to allocate memory\n"); return -ENOMEM; } exynos5_audio_set_mclk(1, 0); ret = snd_soc_register_dais(&pdev->dev, adonisuniv_ext_dai, ARRAY_SIZE(adonisuniv_ext_dai)); if (ret != 0) pr_err("Failed to register external DAIs: %d\n", ret); snd_soc_card_set_drvdata(&adonisuniv, wm5102); adonisuniv.dev = &pdev->dev; ret = snd_soc_register_card(&adonisuniv); if (ret) { dev_err(&pdev->dev, "snd_soc_register_card failed %d\n", ret); kfree(wm5102); } adonisuniv_gpio_init(); return ret; } static int __devexit snd_adonisuniv_remove(struct platform_device *pdev) { struct snd_soc_card *card = &adonisuniv; struct wm5102_machine_priv *wm5102 = snd_soc_card_get_drvdata(card); snd_soc_unregister_card(&adonisuniv); kfree(wm5102); exynos5_audio_set_mclk(0, 0); #ifdef GPIO_MICBIAS_EN gpio_free(GPIO_MICBIAS_EN); #endif #ifdef GPIO_SUB_MICBIAS_EN gpio_free(GPIO_SUB_MICBIAS_EN); #endif return 0; } static struct platform_driver snd_adonisuniv_driver = { .driver = { .owner = THIS_MODULE, .name = "wm5102-card", .pm = &snd_soc_pm_ops, }, .probe = snd_adonisuniv_probe, .remove = __devexit_p(snd_adonisuniv_remove), }; module_platform_driver(snd_adonisuniv_driver); MODULE_AUTHOR("JS. Park <[email protected]>"); MODULE_DESCRIPTION("ALSA SoC AdonisUniv wm5102"); MODULE_LICENSE("GPL");
VanirAOSP/kernel_samsung_exynos5420
sound/soc/samsung/adonisuniv_wm5102.c
C
gpl-2.0
26,639
/* i2c-core.c - a device driver for the iic-bus interface */ /* ------------------------------------------------------------------------- */ /* Copyright (C) 1995-99 Simon G. Vogl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ /* ------------------------------------------------------------------------- */ /* With some changes from Kyösti Mälkki <[email protected]>. All SMBus-related things are written by Frodo Looijaard <[email protected]> SMBus 2.0 support by Mark Studebaker <[email protected]> and Jean Delvare <[email protected]> Mux support by Rodolfo Giometti <[email protected]> and Michael Lawnick <[email protected]> OF support is copyright (c) 2008 Jochen Friedrich <[email protected]> (based on a previous patch from Jon Smirl <[email protected]>) and (c) 2013 Wolfram Sang <[email protected]> I2C ACPI code Copyright (C) 2014 Intel Corp Author: Lan Tianyu <[email protected]> I2C slave support (c) 2014 by Wolfram Sang <[email protected]> */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/delay.h> #include <linux/errno.h> #include <linux/gpio.h> #include <linux/slab.h> #include <linux/i2c.h> #include <linux/init.h> #include <linux/idr.h> #include <linux/mutex.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/of_irq.h> #include <linux/clk/clk-conf.h> #include <linux/completion.h> #include <linux/hardirq.h> #include <linux/irqflags.h> #include <linux/rwsem.h> #include <linux/pm_runtime.h> #include <linux/pm_domain.h> #include <linux/acpi.h> #include <linux/jump_label.h> #include <asm/uaccess.h> #include <linux/err.h> #include "i2c-core.h" #define CREATE_TRACE_POINTS #include <trace/events/i2c.h> /* core_lock protects i2c_adapter_idr, and guarantees that device detection, deletion of detected devices, and attach_adapter calls are serialized */ static DEFINE_MUTEX(core_lock); static DEFINE_IDR(i2c_adapter_idr); static struct device_type i2c_client_type; static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver); static struct static_key i2c_trace_msg = STATIC_KEY_INIT_FALSE; void i2c_transfer_trace_reg(void) { static_key_slow_inc(&i2c_trace_msg); } void i2c_transfer_trace_unreg(void) { static_key_slow_dec(&i2c_trace_msg); } #if defined(CONFIG_ACPI) struct acpi_i2c_handler_data { struct acpi_connection_info info; struct i2c_adapter *adapter; }; struct gsb_buffer { u8 status; u8 len; union { u16 wdata; u8 bdata; u8 data[0]; }; } __packed; static int acpi_i2c_add_resource(struct acpi_resource *ares, void *data) { struct i2c_board_info *info = data; if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) { struct acpi_resource_i2c_serialbus *sb; sb = &ares->data.i2c_serial_bus; if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_I2C) { info->addr = sb->slave_address; if (sb->access_mode == ACPI_I2C_10BIT_MODE) info->flags |= I2C_CLIENT_TEN; } } else if (info->irq < 0) { struct resource r; if (acpi_dev_resource_interrupt(ares, 0, &r)) info->irq = r.start; } /* Tell the ACPI core to skip this resource */ return 1; } static acpi_status acpi_i2c_add_device(acpi_handle handle, u32 level, void *data, void **return_value) { struct i2c_adapter *adapter = data; struct list_head resource_list; struct i2c_board_info info; struct acpi_device *adev; int ret; if (acpi_bus_get_device(handle, &adev)) return AE_OK; if (acpi_bus_get_status(adev) || !adev->status.present) return AE_OK; memset(&info, 0, sizeof(info)); info.acpi_node.companion = adev; info.irq = -1; INIT_LIST_HEAD(&resource_list); ret = acpi_dev_get_resources(adev, &resource_list, acpi_i2c_add_resource, &info); acpi_dev_free_resource_list(&resource_list); if (ret < 0 || !info.addr) return AE_OK; adev->power.flags.ignore_parent = true; strlcpy(info.type, dev_name(&adev->dev), sizeof(info.type)); if (!i2c_new_device(adapter, &info)) { adev->power.flags.ignore_parent = false; dev_err(&adapter->dev, "failed to add I2C device %s from ACPI\n", dev_name(&adev->dev)); } return AE_OK; } /** * acpi_i2c_register_devices - enumerate I2C slave devices behind adapter * @adap: pointer to adapter * * Enumerate all I2C slave devices behind this adapter by walking the ACPI * namespace. When a device is found it will be added to the Linux device * model and bound to the corresponding ACPI handle. */ static void acpi_i2c_register_devices(struct i2c_adapter *adap) { acpi_handle handle; acpi_status status; if (!adap->dev.parent) return; handle = ACPI_HANDLE(adap->dev.parent); if (!handle) return; status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, 1, acpi_i2c_add_device, NULL, adap, NULL); if (ACPI_FAILURE(status)) dev_warn(&adap->dev, "failed to enumerate I2C slaves\n"); } #else /* CONFIG_ACPI */ static inline void acpi_i2c_register_devices(struct i2c_adapter *adap) { } #endif /* CONFIG_ACPI */ #ifdef CONFIG_ACPI_I2C_OPREGION static int acpi_gsb_i2c_read_bytes(struct i2c_client *client, u8 cmd, u8 *data, u8 data_len) { struct i2c_msg msgs[2]; int ret; u8 *buffer; buffer = kzalloc(data_len, GFP_KERNEL); if (!buffer) return AE_NO_MEMORY; msgs[0].addr = client->addr; msgs[0].flags = client->flags; msgs[0].len = 1; msgs[0].buf = &cmd; msgs[1].addr = client->addr; msgs[1].flags = client->flags | I2C_M_RD; msgs[1].len = data_len; msgs[1].buf = buffer; ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); if (ret < 0) dev_err(&client->adapter->dev, "i2c read failed\n"); else memcpy(data, buffer, data_len); kfree(buffer); return ret; } static int acpi_gsb_i2c_write_bytes(struct i2c_client *client, u8 cmd, u8 *data, u8 data_len) { struct i2c_msg msgs[1]; u8 *buffer; int ret = AE_OK; buffer = kzalloc(data_len + 1, GFP_KERNEL); if (!buffer) return AE_NO_MEMORY; buffer[0] = cmd; memcpy(buffer + 1, data, data_len); msgs[0].addr = client->addr; msgs[0].flags = client->flags; msgs[0].len = data_len + 1; msgs[0].buf = buffer; ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); if (ret < 0) dev_err(&client->adapter->dev, "i2c write failed\n"); kfree(buffer); return ret; } static acpi_status acpi_i2c_space_handler(u32 function, acpi_physical_address command, u32 bits, u64 *value64, void *handler_context, void *region_context) { struct gsb_buffer *gsb = (struct gsb_buffer *)value64; struct acpi_i2c_handler_data *data = handler_context; struct acpi_connection_info *info = &data->info; struct acpi_resource_i2c_serialbus *sb; struct i2c_adapter *adapter = data->adapter; struct i2c_client client; struct acpi_resource *ares; u32 accessor_type = function >> 16; u8 action = function & ACPI_IO_MASK; acpi_status ret; int status; ret = acpi_buffer_to_resource(info->connection, info->length, &ares); if (ACPI_FAILURE(ret)) return ret; if (!value64 || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS) { ret = AE_BAD_PARAMETER; goto err; } sb = &ares->data.i2c_serial_bus; if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C) { ret = AE_BAD_PARAMETER; goto err; } memset(&client, 0, sizeof(client)); client.adapter = adapter; client.addr = sb->slave_address; client.flags = 0; if (sb->access_mode == ACPI_I2C_10BIT_MODE) client.flags |= I2C_CLIENT_TEN; switch (accessor_type) { case ACPI_GSB_ACCESS_ATTRIB_SEND_RCV: if (action == ACPI_READ) { status = i2c_smbus_read_byte(&client); if (status >= 0) { gsb->bdata = status; status = 0; } } else { status = i2c_smbus_write_byte(&client, gsb->bdata); } break; case ACPI_GSB_ACCESS_ATTRIB_BYTE: if (action == ACPI_READ) { status = i2c_smbus_read_byte_data(&client, command); if (status >= 0) { gsb->bdata = status; status = 0; } } else { status = i2c_smbus_write_byte_data(&client, command, gsb->bdata); } break; case ACPI_GSB_ACCESS_ATTRIB_WORD: if (action == ACPI_READ) { status = i2c_smbus_read_word_data(&client, command); if (status >= 0) { gsb->wdata = status; status = 0; } } else { status = i2c_smbus_write_word_data(&client, command, gsb->wdata); } break; case ACPI_GSB_ACCESS_ATTRIB_BLOCK: if (action == ACPI_READ) { status = i2c_smbus_read_block_data(&client, command, gsb->data); if (status >= 0) { gsb->len = status; status = 0; } } else { status = i2c_smbus_write_block_data(&client, command, gsb->len, gsb->data); } break; case ACPI_GSB_ACCESS_ATTRIB_MULTIBYTE: if (action == ACPI_READ) { status = acpi_gsb_i2c_read_bytes(&client, command, gsb->data, info->access_length); if (status > 0) status = 0; } else { status = acpi_gsb_i2c_write_bytes(&client, command, gsb->data, info->access_length); } break; default: pr_info("protocol(0x%02x) is not supported.\n", accessor_type); ret = AE_BAD_PARAMETER; goto err; } gsb->status = status; err: ACPI_FREE(ares); return ret; } static int acpi_i2c_install_space_handler(struct i2c_adapter *adapter) { acpi_handle handle; struct acpi_i2c_handler_data *data; acpi_status status; if (!adapter->dev.parent) return -ENODEV; handle = ACPI_HANDLE(adapter->dev.parent); if (!handle) return -ENODEV; data = kzalloc(sizeof(struct acpi_i2c_handler_data), GFP_KERNEL); if (!data) return -ENOMEM; data->adapter = adapter; status = acpi_bus_attach_private_data(handle, (void *)data); if (ACPI_FAILURE(status)) { kfree(data); return -ENOMEM; } status = acpi_install_address_space_handler(handle, ACPI_ADR_SPACE_GSBUS, &acpi_i2c_space_handler, NULL, data); if (ACPI_FAILURE(status)) { dev_err(&adapter->dev, "Error installing i2c space handler\n"); acpi_bus_detach_private_data(handle); kfree(data); return -ENOMEM; } acpi_walk_dep_device_list(handle); return 0; } static void acpi_i2c_remove_space_handler(struct i2c_adapter *adapter) { acpi_handle handle; struct acpi_i2c_handler_data *data; acpi_status status; if (!adapter->dev.parent) return; handle = ACPI_HANDLE(adapter->dev.parent); if (!handle) return; acpi_remove_address_space_handler(handle, ACPI_ADR_SPACE_GSBUS, &acpi_i2c_space_handler); status = acpi_bus_get_private_data(handle, (void **)&data); if (ACPI_SUCCESS(status)) kfree(data); acpi_bus_detach_private_data(handle); } #else /* CONFIG_ACPI_I2C_OPREGION */ static inline void acpi_i2c_remove_space_handler(struct i2c_adapter *adapter) { } static inline int acpi_i2c_install_space_handler(struct i2c_adapter *adapter) { return 0; } #endif /* CONFIG_ACPI_I2C_OPREGION */ /* ------------------------------------------------------------------------- */ static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id, const struct i2c_client *client) { while (id->name[0]) { if (strcmp(client->name, id->name) == 0) return id; id++; } return NULL; } static int i2c_device_match(struct device *dev, struct device_driver *drv) { struct i2c_client *client = i2c_verify_client(dev); struct i2c_driver *driver; if (!client) return 0; /* Attempt an OF style match */ if (of_driver_match_device(dev, drv)) return 1; /* Then ACPI style match */ if (acpi_driver_match_device(dev, drv)) return 1; driver = to_i2c_driver(drv); /* match on an id table if there is one */ if (driver->id_table) return i2c_match_id(driver->id_table, client) != NULL; return 0; } /* uevent helps with hotplug: modprobe -q $(MODALIAS) */ static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env) { struct i2c_client *client = to_i2c_client(dev); int rc; rc = acpi_device_uevent_modalias(dev, env); if (rc != -ENODEV) return rc; if (add_uevent_var(env, "MODALIAS=%s%s", I2C_MODULE_PREFIX, client->name)) return -ENOMEM; dev_dbg(dev, "uevent\n"); return 0; } /* i2c bus recovery routines */ static int get_scl_gpio_value(struct i2c_adapter *adap) { return gpio_get_value(adap->bus_recovery_info->scl_gpio); } static void set_scl_gpio_value(struct i2c_adapter *adap, int val) { gpio_set_value(adap->bus_recovery_info->scl_gpio, val); } static int get_sda_gpio_value(struct i2c_adapter *adap) { return gpio_get_value(adap->bus_recovery_info->sda_gpio); } static int i2c_get_gpios_for_recovery(struct i2c_adapter *adap) { struct i2c_bus_recovery_info *bri = adap->bus_recovery_info; struct device *dev = &adap->dev; int ret = 0; ret = gpio_request_one(bri->scl_gpio, GPIOF_OPEN_DRAIN | GPIOF_OUT_INIT_HIGH, "i2c-scl"); if (ret) { dev_warn(dev, "Can't get SCL gpio: %d\n", bri->scl_gpio); return ret; } if (bri->get_sda) { if (gpio_request_one(bri->sda_gpio, GPIOF_IN, "i2c-sda")) { /* work without SDA polling */ dev_warn(dev, "Can't get SDA gpio: %d. Not using SDA polling\n", bri->sda_gpio); bri->get_sda = NULL; } } return ret; } static void i2c_put_gpios_for_recovery(struct i2c_adapter *adap) { struct i2c_bus_recovery_info *bri = adap->bus_recovery_info; if (bri->get_sda) gpio_free(bri->sda_gpio); gpio_free(bri->scl_gpio); } /* * We are generating clock pulses. ndelay() determines durating of clk pulses. * We will generate clock with rate 100 KHz and so duration of both clock levels * is: delay in ns = (10^6 / 100) / 2 */ #define RECOVERY_NDELAY 5000 #define RECOVERY_CLK_CNT 9 static int i2c_generic_recovery(struct i2c_adapter *adap) { struct i2c_bus_recovery_info *bri = adap->bus_recovery_info; int i = 0, val = 1, ret = 0; if (bri->prepare_recovery) bri->prepare_recovery(bri); /* * By this time SCL is high, as we need to give 9 falling-rising edges */ while (i++ < RECOVERY_CLK_CNT * 2) { if (val) { /* Break if SDA is high */ if (bri->get_sda && bri->get_sda(adap)) break; /* SCL shouldn't be low here */ if (!bri->get_scl(adap)) { dev_err(&adap->dev, "SCL is stuck low, exit recovery\n"); ret = -EBUSY; break; } } val = !val; bri->set_scl(adap, val); ndelay(RECOVERY_NDELAY); } if (bri->unprepare_recovery) bri->unprepare_recovery(bri); return ret; } int i2c_generic_scl_recovery(struct i2c_adapter *adap) { adap->bus_recovery_info->set_scl(adap, 1); return i2c_generic_recovery(adap); } int i2c_generic_gpio_recovery(struct i2c_adapter *adap) { int ret; ret = i2c_get_gpios_for_recovery(adap); if (ret) return ret; ret = i2c_generic_recovery(adap); i2c_put_gpios_for_recovery(adap); return ret; } int i2c_recover_bus(struct i2c_adapter *adap) { if (!adap->bus_recovery_info) return -EOPNOTSUPP; dev_dbg(&adap->dev, "Trying i2c bus recovery\n"); return adap->bus_recovery_info->recover_bus(adap); } static int i2c_device_probe(struct device *dev) { struct i2c_client *client = i2c_verify_client(dev); struct i2c_driver *driver; int status; if (!client) return 0; if (!client->irq && dev->of_node) { int irq = of_irq_get(dev->of_node, 0); if (irq == -EPROBE_DEFER) return irq; if (irq < 0) irq = 0; client->irq = irq; } driver = to_i2c_driver(dev->driver); if (!driver->probe || !driver->id_table) return -ENODEV; if (!device_can_wakeup(&client->dev)) device_init_wakeup(&client->dev, client->flags & I2C_CLIENT_WAKE); dev_dbg(dev, "probe\n"); status = of_clk_set_defaults(dev->of_node, false); if (status < 0) return status; status = dev_pm_domain_attach(&client->dev, true); if (status != -EPROBE_DEFER) { status = driver->probe(client, i2c_match_id(driver->id_table, client)); if (status) dev_pm_domain_detach(&client->dev, true); } return status; } static int i2c_device_remove(struct device *dev) { struct i2c_client *client = i2c_verify_client(dev); struct i2c_driver *driver; int status = 0; if (!client || !dev->driver) return 0; driver = to_i2c_driver(dev->driver); if (driver->remove) { dev_dbg(dev, "remove\n"); status = driver->remove(client); } if (dev->of_node) irq_dispose_mapping(client->irq); dev_pm_domain_detach(&client->dev, true); return status; } static void i2c_device_shutdown(struct device *dev) { struct i2c_client *client = i2c_verify_client(dev); struct i2c_driver *driver; if (!client || !dev->driver) return; driver = to_i2c_driver(dev->driver); if (driver->shutdown) driver->shutdown(client); } #ifdef CONFIG_PM_SLEEP static int i2c_legacy_suspend(struct device *dev, pm_message_t mesg) { struct i2c_client *client = i2c_verify_client(dev); struct i2c_driver *driver; if (!client || !dev->driver) return 0; driver = to_i2c_driver(dev->driver); if (!driver->suspend) return 0; return driver->suspend(client, mesg); } static int i2c_legacy_resume(struct device *dev) { struct i2c_client *client = i2c_verify_client(dev); struct i2c_driver *driver; if (!client || !dev->driver) return 0; driver = to_i2c_driver(dev->driver); if (!driver->resume) return 0; return driver->resume(client); } static int i2c_device_pm_suspend(struct device *dev) { const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL; if (pm) return pm_generic_suspend(dev); else return i2c_legacy_suspend(dev, PMSG_SUSPEND); } static int i2c_device_pm_resume(struct device *dev) { const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL; if (pm) return pm_generic_resume(dev); else return i2c_legacy_resume(dev); } static int i2c_device_pm_freeze(struct device *dev) { const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL; if (pm) return pm_generic_freeze(dev); else return i2c_legacy_suspend(dev, PMSG_FREEZE); } static int i2c_device_pm_thaw(struct device *dev) { const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL; if (pm) return pm_generic_thaw(dev); else return i2c_legacy_resume(dev); } static int i2c_device_pm_poweroff(struct device *dev) { const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL; if (pm) return pm_generic_poweroff(dev); else return i2c_legacy_suspend(dev, PMSG_HIBERNATE); } static int i2c_device_pm_restore(struct device *dev) { const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL; if (pm) return pm_generic_restore(dev); else return i2c_legacy_resume(dev); } #else /* !CONFIG_PM_SLEEP */ #define i2c_device_pm_suspend NULL #define i2c_device_pm_resume NULL #define i2c_device_pm_freeze NULL #define i2c_device_pm_thaw NULL #define i2c_device_pm_poweroff NULL #define i2c_device_pm_restore NULL #endif /* !CONFIG_PM_SLEEP */ static void i2c_client_dev_release(struct device *dev) { kfree(to_i2c_client(dev)); } static ssize_t show_name(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%s\n", dev->type == &i2c_client_type ? to_i2c_client(dev)->name : to_i2c_adapter(dev)->name); } static ssize_t show_modalias(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); int len; len = acpi_device_modalias(dev, buf, PAGE_SIZE -1); if (len != -ENODEV) return len; return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name); } static DEVICE_ATTR(name, S_IRUGO, show_name, NULL); static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL); static struct attribute *i2c_dev_attrs[] = { &dev_attr_name.attr, /* modalias helps coldplug: modprobe $(cat .../modalias) */ &dev_attr_modalias.attr, NULL }; static struct attribute_group i2c_dev_attr_group = { .attrs = i2c_dev_attrs, }; static const struct attribute_group *i2c_dev_attr_groups[] = { &i2c_dev_attr_group, NULL }; static const struct dev_pm_ops i2c_device_pm_ops = { .suspend = i2c_device_pm_suspend, .resume = i2c_device_pm_resume, .freeze = i2c_device_pm_freeze, .thaw = i2c_device_pm_thaw, .poweroff = i2c_device_pm_poweroff, .restore = i2c_device_pm_restore, SET_RUNTIME_PM_OPS( pm_generic_runtime_suspend, pm_generic_runtime_resume, NULL ) }; struct bus_type i2c_bus_type = { .name = "i2c", .match = i2c_device_match, .probe = i2c_device_probe, .remove = i2c_device_remove, .shutdown = i2c_device_shutdown, .pm = &i2c_device_pm_ops, }; EXPORT_SYMBOL_GPL(i2c_bus_type); static struct device_type i2c_client_type = { .groups = i2c_dev_attr_groups, .uevent = i2c_device_uevent, .release = i2c_client_dev_release, }; /** * i2c_verify_client - return parameter as i2c_client, or NULL * @dev: device, probably from some driver model iterator * * When traversing the driver model tree, perhaps using driver model * iterators like @device_for_each_child(), you can't assume very much * about the nodes you find. Use this function to avoid oopses caused * by wrongly treating some non-I2C device as an i2c_client. */ struct i2c_client *i2c_verify_client(struct device *dev) { return (dev->type == &i2c_client_type) ? to_i2c_client(dev) : NULL; } EXPORT_SYMBOL(i2c_verify_client); /* This is a permissive address validity check, I2C address map constraints * are purposely not enforced, except for the general call address. */ static int i2c_check_client_addr_validity(const struct i2c_client *client) { if (client->flags & I2C_CLIENT_TEN) { /* 10-bit address, all values are valid */ if (client->addr > 0x3ff) return -EINVAL; } else { /* 7-bit address, reject the general call address */ if (client->addr == 0x00 || client->addr > 0x7f) return -EINVAL; } return 0; } /* And this is a strict address validity check, used when probing. If a * device uses a reserved address, then it shouldn't be probed. 7-bit * addressing is assumed, 10-bit address devices are rare and should be * explicitly enumerated. */ static int i2c_check_addr_validity(unsigned short addr) { /* * Reserved addresses per I2C specification: * 0x00 General call address / START byte * 0x01 CBUS address * 0x02 Reserved for different bus format * 0x03 Reserved for future purposes * 0x04-0x07 Hs-mode master code * 0x78-0x7b 10-bit slave addressing * 0x7c-0x7f Reserved for future purposes */ if (addr < 0x08 || addr > 0x77) return -EINVAL; return 0; } static int __i2c_check_addr_busy(struct device *dev, void *addrp) { struct i2c_client *client = i2c_verify_client(dev); int addr = *(int *)addrp; if (client && client->addr == addr) return -EBUSY; return 0; } /* walk up mux tree */ static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr) { struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter); int result; result = device_for_each_child(&adapter->dev, &addr, __i2c_check_addr_busy); if (!result && parent) result = i2c_check_mux_parents(parent, addr); return result; } /* recurse down mux tree */ static int i2c_check_mux_children(struct device *dev, void *addrp) { int result; if (dev->type == &i2c_adapter_type) result = device_for_each_child(dev, addrp, i2c_check_mux_children); else result = __i2c_check_addr_busy(dev, addrp); return result; } static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr) { struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter); int result = 0; if (parent) result = i2c_check_mux_parents(parent, addr); if (!result) result = device_for_each_child(&adapter->dev, &addr, i2c_check_mux_children); return result; } /** * i2c_lock_adapter - Get exclusive access to an I2C bus segment * @adapter: Target I2C bus segment */ void i2c_lock_adapter(struct i2c_adapter *adapter) { struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter); if (parent) i2c_lock_adapter(parent); else rt_mutex_lock(&adapter->bus_lock); } EXPORT_SYMBOL_GPL(i2c_lock_adapter); /** * i2c_trylock_adapter - Try to get exclusive access to an I2C bus segment * @adapter: Target I2C bus segment */ static int i2c_trylock_adapter(struct i2c_adapter *adapter) { struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter); if (parent) return i2c_trylock_adapter(parent); else return rt_mutex_trylock(&adapter->bus_lock); } /** * i2c_unlock_adapter - Release exclusive access to an I2C bus segment * @adapter: Target I2C bus segment */ void i2c_unlock_adapter(struct i2c_adapter *adapter) { struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter); if (parent) i2c_unlock_adapter(parent); else rt_mutex_unlock(&adapter->bus_lock); } EXPORT_SYMBOL_GPL(i2c_unlock_adapter); static void i2c_dev_set_name(struct i2c_adapter *adap, struct i2c_client *client) { struct acpi_device *adev = ACPI_COMPANION(&client->dev); if (adev) { dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev)); return; } /* For 10-bit clients, add an arbitrary offset to avoid collisions */ dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap), client->addr | ((client->flags & I2C_CLIENT_TEN) ? 0xa000 : 0)); } /** * i2c_new_device - instantiate an i2c device * @adap: the adapter managing the device * @info: describes one I2C device; bus_num is ignored * Context: can sleep * * Create an i2c device. Binding is handled through driver model * probe()/remove() methods. A driver may be bound to this device when we * return from this function, or any later moment (e.g. maybe hotplugging will * load the driver module). This call is not appropriate for use by mainboard * initialization logic, which usually runs during an arch_initcall() long * before any i2c_adapter could exist. * * This returns the new i2c client, which may be saved for later use with * i2c_unregister_device(); or NULL to indicate an error. */ struct i2c_client * i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info) { struct i2c_client *client; int status; client = kzalloc(sizeof *client, GFP_KERNEL); if (!client) return NULL; client->adapter = adap; client->dev.platform_data = info->platform_data; if (info->archdata) client->dev.archdata = *info->archdata; client->flags = info->flags; client->addr = info->addr; client->irq = info->irq; strlcpy(client->name, info->type, sizeof(client->name)); /* Check for address validity */ status = i2c_check_client_addr_validity(client); if (status) { dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n", client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr); goto out_err_silent; } /* Check for address business */ status = i2c_check_addr_busy(adap, client->addr); if (status) goto out_err; client->dev.parent = &client->adapter->dev; client->dev.bus = &i2c_bus_type; client->dev.type = &i2c_client_type; client->dev.of_node = info->of_node; ACPI_COMPANION_SET(&client->dev, info->acpi_node.companion); i2c_dev_set_name(adap, client); status = device_register(&client->dev); if (status) goto out_err; dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n", client->name, dev_name(&client->dev)); return client; out_err: dev_err(&adap->dev, "Failed to register i2c client %s at 0x%02x " "(%d)\n", client->name, client->addr, status); out_err_silent: kfree(client); return NULL; } EXPORT_SYMBOL_GPL(i2c_new_device); /** * i2c_unregister_device - reverse effect of i2c_new_device() * @client: value returned from i2c_new_device() * Context: can sleep */ void i2c_unregister_device(struct i2c_client *client) { device_unregister(&client->dev); } EXPORT_SYMBOL_GPL(i2c_unregister_device); static const struct i2c_device_id dummy_id[] = { { "dummy", 0 }, { }, }; static int dummy_probe(struct i2c_client *client, const struct i2c_device_id *id) { return 0; } static int dummy_remove(struct i2c_client *client) { return 0; } static struct i2c_driver dummy_driver = { .driver.name = "dummy", .probe = dummy_probe, .remove = dummy_remove, .id_table = dummy_id, }; /** * i2c_new_dummy - return a new i2c device bound to a dummy driver * @adapter: the adapter managing the device * @address: seven bit address to be used * Context: can sleep * * This returns an I2C client bound to the "dummy" driver, intended for use * with devices that consume multiple addresses. Examples of such chips * include various EEPROMS (like 24c04 and 24c08 models). * * These dummy devices have two main uses. First, most I2C and SMBus calls * except i2c_transfer() need a client handle; the dummy will be that handle. * And second, this prevents the specified address from being bound to a * different driver. * * This returns the new i2c client, which should be saved for later use with * i2c_unregister_device(); or NULL to indicate an error. */ struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address) { struct i2c_board_info info = { I2C_BOARD_INFO("dummy", address), }; return i2c_new_device(adapter, &info); } EXPORT_SYMBOL_GPL(i2c_new_dummy); /* ------------------------------------------------------------------------- */ /* I2C bus adapters -- one roots each I2C or SMBUS segment */ static void i2c_adapter_dev_release(struct device *dev) { struct i2c_adapter *adap = to_i2c_adapter(dev); complete(&adap->dev_released); } /* * This function is only needed for mutex_lock_nested, so it is never * called unless locking correctness checking is enabled. Thus we * make it inline to avoid a compiler warning. That's what gcc ends up * doing anyway. */ static inline unsigned int i2c_adapter_depth(struct i2c_adapter *adapter) { unsigned int depth = 0; while ((adapter = i2c_parent_is_i2c_adapter(adapter))) depth++; return depth; } /* * Let users instantiate I2C devices through sysfs. This can be used when * platform initialization code doesn't contain the proper data for * whatever reason. Also useful for drivers that do device detection and * detection fails, either because the device uses an unexpected address, * or this is a compatible device with different ID register values. * * Parameter checking may look overzealous, but we really don't want * the user to provide incorrect parameters. */ static ssize_t i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_adapter *adap = to_i2c_adapter(dev); struct i2c_board_info info; struct i2c_client *client; char *blank, end; int res; memset(&info, 0, sizeof(struct i2c_board_info)); blank = strchr(buf, ' '); if (!blank) { dev_err(dev, "%s: Missing parameters\n", "new_device"); return -EINVAL; } if (blank - buf > I2C_NAME_SIZE - 1) { dev_err(dev, "%s: Invalid device name\n", "new_device"); return -EINVAL; } memcpy(info.type, buf, blank - buf); /* Parse remaining parameters, reject extra parameters */ res = sscanf(++blank, "%hi%c", &info.addr, &end); if (res < 1) { dev_err(dev, "%s: Can't parse I2C address\n", "new_device"); return -EINVAL; } if (res > 1 && end != '\n') { dev_err(dev, "%s: Extra parameters\n", "new_device"); return -EINVAL; } client = i2c_new_device(adap, &info); if (!client) return -EINVAL; /* Keep track of the added device */ mutex_lock(&adap->userspace_clients_lock); list_add_tail(&client->detected, &adap->userspace_clients); mutex_unlock(&adap->userspace_clients_lock); dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device", info.type, info.addr); return count; } /* * And of course let the users delete the devices they instantiated, if * they got it wrong. This interface can only be used to delete devices * instantiated by i2c_sysfs_new_device above. This guarantees that we * don't delete devices to which some kernel code still has references. * * Parameter checking may look overzealous, but we really don't want * the user to delete the wrong device. */ static ssize_t i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_adapter *adap = to_i2c_adapter(dev); struct i2c_client *client, *next; unsigned short addr; char end; int res; /* Parse parameters, reject extra parameters */ res = sscanf(buf, "%hi%c", &addr, &end); if (res < 1) { dev_err(dev, "%s: Can't parse I2C address\n", "delete_device"); return -EINVAL; } if (res > 1 && end != '\n') { dev_err(dev, "%s: Extra parameters\n", "delete_device"); return -EINVAL; } /* Make sure the device was added through sysfs */ res = -ENOENT; mutex_lock_nested(&adap->userspace_clients_lock, i2c_adapter_depth(adap)); list_for_each_entry_safe(client, next, &adap->userspace_clients, detected) { if (client->addr == addr) { dev_info(dev, "%s: Deleting device %s at 0x%02hx\n", "delete_device", client->name, client->addr); list_del(&client->detected); i2c_unregister_device(client); res = count; break; } } mutex_unlock(&adap->userspace_clients_lock); if (res < 0) dev_err(dev, "%s: Can't find device in list\n", "delete_device"); return res; } static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device); static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL, i2c_sysfs_delete_device); static struct attribute *i2c_adapter_attrs[] = { &dev_attr_name.attr, &dev_attr_new_device.attr, &dev_attr_delete_device.attr, NULL }; static struct attribute_group i2c_adapter_attr_group = { .attrs = i2c_adapter_attrs, }; static const struct attribute_group *i2c_adapter_attr_groups[] = { &i2c_adapter_attr_group, NULL }; struct device_type i2c_adapter_type = { .groups = i2c_adapter_attr_groups, .release = i2c_adapter_dev_release, }; EXPORT_SYMBOL_GPL(i2c_adapter_type); /** * i2c_verify_adapter - return parameter as i2c_adapter or NULL * @dev: device, probably from some driver model iterator * * When traversing the driver model tree, perhaps using driver model * iterators like @device_for_each_child(), you can't assume very much * about the nodes you find. Use this function to avoid oopses caused * by wrongly treating some non-I2C device as an i2c_adapter. */ struct i2c_adapter *i2c_verify_adapter(struct device *dev) { return (dev->type == &i2c_adapter_type) ? to_i2c_adapter(dev) : NULL; } EXPORT_SYMBOL(i2c_verify_adapter); #ifdef CONFIG_I2C_COMPAT static struct class_compat *i2c_adapter_compat_class; #endif static void i2c_scan_static_board_info(struct i2c_adapter *adapter) { struct i2c_devinfo *devinfo; down_read(&__i2c_board_lock); list_for_each_entry(devinfo, &__i2c_board_list, list) { if (devinfo->busnum == adapter->nr && !i2c_new_device(adapter, &devinfo->board_info)) dev_err(&adapter->dev, "Can't create device at 0x%02x\n", devinfo->board_info.addr); } up_read(&__i2c_board_lock); } /* OF support code */ #if IS_ENABLED(CONFIG_OF) static struct i2c_client *of_i2c_register_device(struct i2c_adapter *adap, struct device_node *node) { struct i2c_client *result; struct i2c_board_info info = {}; struct dev_archdata dev_ad = {}; const __be32 *addr; int len; dev_dbg(&adap->dev, "of_i2c: register %s\n", node->full_name); if (of_modalias_node(node, info.type, sizeof(info.type)) < 0) { dev_err(&adap->dev, "of_i2c: modalias failure on %s\n", node->full_name); return ERR_PTR(-EINVAL); } addr = of_get_property(node, "reg", &len); if (!addr || (len < sizeof(int))) { dev_err(&adap->dev, "of_i2c: invalid reg on %s\n", node->full_name); return ERR_PTR(-EINVAL); } info.addr = be32_to_cpup(addr); if (info.addr > (1 << 10) - 1) { dev_err(&adap->dev, "of_i2c: invalid addr=%x on %s\n", info.addr, node->full_name); return ERR_PTR(-EINVAL); } info.of_node = of_node_get(node); info.archdata = &dev_ad; if (of_get_property(node, "wakeup-source", NULL)) info.flags |= I2C_CLIENT_WAKE; request_module("%s%s", I2C_MODULE_PREFIX, info.type); result = i2c_new_device(adap, &info); if (result == NULL) { dev_err(&adap->dev, "of_i2c: Failure registering %s\n", node->full_name); of_node_put(node); return ERR_PTR(-EINVAL); } return result; } static void of_i2c_register_devices(struct i2c_adapter *adap) { struct device_node *node; /* Only register child devices if the adapter has a node pointer set */ if (!adap->dev.of_node) return; dev_dbg(&adap->dev, "of_i2c: walking child nodes\n"); for_each_available_child_of_node(adap->dev.of_node, node) of_i2c_register_device(adap, node); } static int of_dev_node_match(struct device *dev, void *data) { return dev->of_node == data; } /* must call put_device() when done with returned i2c_client device */ struct i2c_client *of_find_i2c_device_by_node(struct device_node *node) { struct device *dev; dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match); if (!dev) return NULL; return i2c_verify_client(dev); } EXPORT_SYMBOL(of_find_i2c_device_by_node); /* must call put_device() when done with returned i2c_adapter device */ struct i2c_adapter *of_find_i2c_adapter_by_node(struct device_node *node) { struct device *dev; dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match); if (!dev) return NULL; return i2c_verify_adapter(dev); } EXPORT_SYMBOL(of_find_i2c_adapter_by_node); #else static void of_i2c_register_devices(struct i2c_adapter *adap) { } #endif /* CONFIG_OF */ static int i2c_do_add_adapter(struct i2c_driver *driver, struct i2c_adapter *adap) { /* Detect supported devices on that bus, and instantiate them */ i2c_detect(adap, driver); /* Let legacy drivers scan this bus for matching devices */ if (driver->attach_adapter) { dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n", driver->driver.name); dev_warn(&adap->dev, "Please use another way to instantiate " "your i2c_client\n"); /* We ignore the return code; if it fails, too bad */ driver->attach_adapter(adap); } return 0; } static int __process_new_adapter(struct device_driver *d, void *data) { return i2c_do_add_adapter(to_i2c_driver(d), data); } static int i2c_register_adapter(struct i2c_adapter *adap) { int res = 0; /* Can't register until after driver model init */ if (unlikely(WARN_ON(!i2c_bus_type.p))) { res = -EAGAIN; goto out_list; } /* Sanity checks */ if (unlikely(adap->name[0] == '\0')) { pr_err("i2c-core: Attempt to register an adapter with " "no name!\n"); return -EINVAL; } if (unlikely(!adap->algo)) { pr_err("i2c-core: Attempt to register adapter '%s' with " "no algo!\n", adap->name); return -EINVAL; } rt_mutex_init(&adap->bus_lock); mutex_init(&adap->userspace_clients_lock); INIT_LIST_HEAD(&adap->userspace_clients); /* Set default timeout to 1 second if not already set */ if (adap->timeout == 0) adap->timeout = HZ; dev_set_name(&adap->dev, "i2c-%d", adap->nr); adap->dev.bus = &i2c_bus_type; adap->dev.type = &i2c_adapter_type; res = device_register(&adap->dev); if (res) goto out_list; dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name); #ifdef CONFIG_I2C_COMPAT res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev, adap->dev.parent); if (res) dev_warn(&adap->dev, "Failed to create compatibility class link\n"); #endif /* bus recovery specific initialization */ if (adap->bus_recovery_info) { struct i2c_bus_recovery_info *bri = adap->bus_recovery_info; if (!bri->recover_bus) { dev_err(&adap->dev, "No recover_bus() found, not using recovery\n"); adap->bus_recovery_info = NULL; goto exit_recovery; } /* Generic GPIO recovery */ if (bri->recover_bus == i2c_generic_gpio_recovery) { if (!gpio_is_valid(bri->scl_gpio)) { dev_err(&adap->dev, "Invalid SCL gpio, not using recovery\n"); adap->bus_recovery_info = NULL; goto exit_recovery; } if (gpio_is_valid(bri->sda_gpio)) bri->get_sda = get_sda_gpio_value; else bri->get_sda = NULL; bri->get_scl = get_scl_gpio_value; bri->set_scl = set_scl_gpio_value; } else if (!bri->set_scl || !bri->get_scl) { /* Generic SCL recovery */ dev_err(&adap->dev, "No {get|set}_gpio() found, not using recovery\n"); adap->bus_recovery_info = NULL; } } exit_recovery: /* create pre-declared device nodes */ of_i2c_register_devices(adap); acpi_i2c_register_devices(adap); acpi_i2c_install_space_handler(adap); if (adap->nr < __i2c_first_dynamic_bus_num) i2c_scan_static_board_info(adap); /* Notify drivers */ mutex_lock(&core_lock); bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter); mutex_unlock(&core_lock); return 0; out_list: mutex_lock(&core_lock); idr_remove(&i2c_adapter_idr, adap->nr); mutex_unlock(&core_lock); return res; } /** * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1 * @adap: the adapter to register (with adap->nr initialized) * Context: can sleep * * See i2c_add_numbered_adapter() for details. */ static int __i2c_add_numbered_adapter(struct i2c_adapter *adap) { int id; mutex_lock(&core_lock); id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1, GFP_KERNEL); mutex_unlock(&core_lock); if (id < 0) return id == -ENOSPC ? -EBUSY : id; return i2c_register_adapter(adap); } /** * i2c_add_adapter - declare i2c adapter, use dynamic bus number * @adapter: the adapter to add * Context: can sleep * * This routine is used to declare an I2C adapter when its bus number * doesn't matter or when its bus number is specified by an dt alias. * Examples of bases when the bus number doesn't matter: I2C adapters * dynamically added by USB links or PCI plugin cards. * * When this returns zero, a new bus number was allocated and stored * in adap->nr, and the specified adapter became available for clients. * Otherwise, a negative errno value is returned. */ int i2c_add_adapter(struct i2c_adapter *adapter) { struct device *dev = &adapter->dev; int id; if (dev->of_node) { id = of_alias_get_id(dev->of_node, "i2c"); if (id >= 0) { adapter->nr = id; return __i2c_add_numbered_adapter(adapter); } } mutex_lock(&core_lock); id = idr_alloc(&i2c_adapter_idr, adapter, __i2c_first_dynamic_bus_num, 0, GFP_KERNEL); mutex_unlock(&core_lock); if (id < 0) return id; adapter->nr = id; return i2c_register_adapter(adapter); } EXPORT_SYMBOL(i2c_add_adapter); /** * i2c_add_numbered_adapter - declare i2c adapter, use static bus number * @adap: the adapter to register (with adap->nr initialized) * Context: can sleep * * This routine is used to declare an I2C adapter when its bus number * matters. For example, use it for I2C adapters from system-on-chip CPUs, * or otherwise built in to the system's mainboard, and where i2c_board_info * is used to properly configure I2C devices. * * If the requested bus number is set to -1, then this function will behave * identically to i2c_add_adapter, and will dynamically assign a bus number. * * If no devices have pre-been declared for this bus, then be sure to * register the adapter before any dynamically allocated ones. Otherwise * the required bus ID may not be available. * * When this returns zero, the specified adapter became available for * clients using the bus number provided in adap->nr. Also, the table * of I2C devices pre-declared using i2c_register_board_info() is scanned, * and the appropriate driver model device nodes are created. Otherwise, a * negative errno value is returned. */ int i2c_add_numbered_adapter(struct i2c_adapter *adap) { if (adap->nr == -1) /* -1 means dynamically assign bus id */ return i2c_add_adapter(adap); return __i2c_add_numbered_adapter(adap); } EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter); static void i2c_do_del_adapter(struct i2c_driver *driver, struct i2c_adapter *adapter) { struct i2c_client *client, *_n; /* Remove the devices we created ourselves as the result of hardware * probing (using a driver's detect method) */ list_for_each_entry_safe(client, _n, &driver->clients, detected) { if (client->adapter == adapter) { dev_dbg(&adapter->dev, "Removing %s at 0x%x\n", client->name, client->addr); list_del(&client->detected); i2c_unregister_device(client); } } } static int __unregister_client(struct device *dev, void *dummy) { struct i2c_client *client = i2c_verify_client(dev); if (client && strcmp(client->name, "dummy")) i2c_unregister_device(client); return 0; } static int __unregister_dummy(struct device *dev, void *dummy) { struct i2c_client *client = i2c_verify_client(dev); if (client) i2c_unregister_device(client); return 0; } static int __process_removed_adapter(struct device_driver *d, void *data) { i2c_do_del_adapter(to_i2c_driver(d), data); return 0; } /** * i2c_del_adapter - unregister I2C adapter * @adap: the adapter being unregistered * Context: can sleep * * This unregisters an I2C adapter which was previously registered * by @i2c_add_adapter or @i2c_add_numbered_adapter. */ void i2c_del_adapter(struct i2c_adapter *adap) { struct i2c_adapter *found; struct i2c_client *client, *next; /* First make sure that this adapter was ever added */ mutex_lock(&core_lock); found = idr_find(&i2c_adapter_idr, adap->nr); mutex_unlock(&core_lock); if (found != adap) { pr_debug("i2c-core: attempting to delete unregistered " "adapter [%s]\n", adap->name); return; } acpi_i2c_remove_space_handler(adap); /* Tell drivers about this removal */ mutex_lock(&core_lock); bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_removed_adapter); mutex_unlock(&core_lock); /* Remove devices instantiated from sysfs */ mutex_lock_nested(&adap->userspace_clients_lock, i2c_adapter_depth(adap)); list_for_each_entry_safe(client, next, &adap->userspace_clients, detected) { dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name, client->addr); list_del(&client->detected); i2c_unregister_device(client); } mutex_unlock(&adap->userspace_clients_lock); /* Detach any active clients. This can't fail, thus we do not * check the returned value. This is a two-pass process, because * we can't remove the dummy devices during the first pass: they * could have been instantiated by real devices wishing to clean * them up properly, so we give them a chance to do that first. */ device_for_each_child(&adap->dev, NULL, __unregister_client); device_for_each_child(&adap->dev, NULL, __unregister_dummy); #ifdef CONFIG_I2C_COMPAT class_compat_remove_link(i2c_adapter_compat_class, &adap->dev, adap->dev.parent); #endif /* device name is gone after device_unregister */ dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name); /* clean up the sysfs representation */ init_completion(&adap->dev_released); device_unregister(&adap->dev); /* wait for sysfs to drop all references */ wait_for_completion(&adap->dev_released); /* free bus id */ mutex_lock(&core_lock); idr_remove(&i2c_adapter_idr, adap->nr); mutex_unlock(&core_lock); /* Clear the device structure in case this adapter is ever going to be added again */ memset(&adap->dev, 0, sizeof(adap->dev)); } EXPORT_SYMBOL(i2c_del_adapter); /* ------------------------------------------------------------------------- */ int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *)) { int res; mutex_lock(&core_lock); res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn); mutex_unlock(&core_lock); return res; } EXPORT_SYMBOL_GPL(i2c_for_each_dev); static int __process_new_driver(struct device *dev, void *data) { if (dev->type != &i2c_adapter_type) return 0; return i2c_do_add_adapter(data, to_i2c_adapter(dev)); } /* * An i2c_driver is used with one or more i2c_client (device) nodes to access * i2c slave chips, on a bus instance associated with some i2c_adapter. */ int i2c_register_driver(struct module *owner, struct i2c_driver *driver) { int res; /* Can't register until after driver model init */ if (unlikely(WARN_ON(!i2c_bus_type.p))) return -EAGAIN; /* add the driver to the list of i2c drivers in the driver core */ driver->driver.owner = owner; driver->driver.bus = &i2c_bus_type; /* When registration returns, the driver core * will have called probe() for all matching-but-unbound devices. */ res = driver_register(&driver->driver); if (res) return res; /* Drivers should switch to dev_pm_ops instead. */ if (driver->suspend) pr_warn("i2c-core: driver [%s] using legacy suspend method\n", driver->driver.name); if (driver->resume) pr_warn("i2c-core: driver [%s] using legacy resume method\n", driver->driver.name); pr_debug("i2c-core: driver [%s] registered\n", driver->driver.name); INIT_LIST_HEAD(&driver->clients); /* Walk the adapters that are already present */ i2c_for_each_dev(driver, __process_new_driver); return 0; } EXPORT_SYMBOL(i2c_register_driver); static int __process_removed_driver(struct device *dev, void *data) { if (dev->type == &i2c_adapter_type) i2c_do_del_adapter(data, to_i2c_adapter(dev)); return 0; } /** * i2c_del_driver - unregister I2C driver * @driver: the driver being unregistered * Context: can sleep */ void i2c_del_driver(struct i2c_driver *driver) { i2c_for_each_dev(driver, __process_removed_driver); driver_unregister(&driver->driver); pr_debug("i2c-core: driver [%s] unregistered\n", driver->driver.name); } EXPORT_SYMBOL(i2c_del_driver); /* ------------------------------------------------------------------------- */ /** * i2c_use_client - increments the reference count of the i2c client structure * @client: the client being referenced * * Each live reference to a client should be refcounted. The driver model does * that automatically as part of driver binding, so that most drivers don't * need to do this explicitly: they hold a reference until they're unbound * from the device. * * A pointer to the client with the incremented reference counter is returned. */ struct i2c_client *i2c_use_client(struct i2c_client *client) { if (client && get_device(&client->dev)) return client; return NULL; } EXPORT_SYMBOL(i2c_use_client); /** * i2c_release_client - release a use of the i2c client structure * @client: the client being no longer referenced * * Must be called when a user of a client is finished with it. */ void i2c_release_client(struct i2c_client *client) { if (client) put_device(&client->dev); } EXPORT_SYMBOL(i2c_release_client); struct i2c_cmd_arg { unsigned cmd; void *arg; }; static int i2c_cmd(struct device *dev, void *_arg) { struct i2c_client *client = i2c_verify_client(dev); struct i2c_cmd_arg *arg = _arg; struct i2c_driver *driver; if (!client || !client->dev.driver) return 0; driver = to_i2c_driver(client->dev.driver); if (driver->command) driver->command(client, arg->cmd, arg->arg); return 0; } void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg) { struct i2c_cmd_arg cmd_arg; cmd_arg.cmd = cmd; cmd_arg.arg = arg; device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd); } EXPORT_SYMBOL(i2c_clients_command); #if IS_ENABLED(CONFIG_OF_DYNAMIC) static int of_i2c_notify(struct notifier_block *nb, unsigned long action, void *arg) { struct of_reconfig_data *rd = arg; struct i2c_adapter *adap; struct i2c_client *client; switch (of_reconfig_get_state_change(action, rd)) { case OF_RECONFIG_CHANGE_ADD: adap = of_find_i2c_adapter_by_node(rd->dn->parent); if (adap == NULL) return NOTIFY_OK; /* not for us */ client = of_i2c_register_device(adap, rd->dn); put_device(&adap->dev); if (IS_ERR(client)) { pr_err("%s: failed to create for '%s'\n", __func__, rd->dn->full_name); return notifier_from_errno(PTR_ERR(client)); } break; case OF_RECONFIG_CHANGE_REMOVE: /* find our device by node */ client = of_find_i2c_device_by_node(rd->dn); if (client == NULL) return NOTIFY_OK; /* no? not meant for us */ /* unregister takes one ref away */ i2c_unregister_device(client); /* and put the reference of the find */ put_device(&client->dev); break; } return NOTIFY_OK; } static struct notifier_block i2c_of_notifier = { .notifier_call = of_i2c_notify, }; #else extern struct notifier_block i2c_of_notifier; #endif /* CONFIG_OF_DYNAMIC */ static int __init i2c_init(void) { int retval; retval = bus_register(&i2c_bus_type); if (retval) return retval; #ifdef CONFIG_I2C_COMPAT i2c_adapter_compat_class = class_compat_register("i2c-adapter"); if (!i2c_adapter_compat_class) { retval = -ENOMEM; goto bus_err; } #endif retval = i2c_add_driver(&dummy_driver); if (retval) goto class_err; if (IS_ENABLED(CONFIG_OF_DYNAMIC)) WARN_ON(of_reconfig_notifier_register(&i2c_of_notifier)); return 0; class_err: #ifdef CONFIG_I2C_COMPAT class_compat_unregister(i2c_adapter_compat_class); bus_err: #endif bus_unregister(&i2c_bus_type); return retval; } static void __exit i2c_exit(void) { if (IS_ENABLED(CONFIG_OF_DYNAMIC)) WARN_ON(of_reconfig_notifier_unregister(&i2c_of_notifier)); i2c_del_driver(&dummy_driver); #ifdef CONFIG_I2C_COMPAT class_compat_unregister(i2c_adapter_compat_class); #endif bus_unregister(&i2c_bus_type); tracepoint_synchronize_unregister(); } /* We must initialize early, because some subsystems register i2c drivers * in subsys_initcall() code, but are linked (and initialized) before i2c. */ postcore_initcall(i2c_init); module_exit(i2c_exit); /* ---------------------------------------------------- * the functional interface to the i2c busses. * ---------------------------------------------------- */ /** * __i2c_transfer - unlocked flavor of i2c_transfer * @adap: Handle to I2C bus * @msgs: One or more messages to execute before STOP is issued to * terminate the operation; each message begins with a START. * @num: Number of messages to be executed. * * Returns negative errno, else the number of messages executed. * * Adapter lock must be held when calling this function. No debug logging * takes place. adap->algo->master_xfer existence isn't checked. */ int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num) { unsigned long orig_jiffies; int ret, try; /* i2c_trace_msg gets enabled when tracepoint i2c_transfer gets * enabled. This is an efficient way of keeping the for-loop from * being executed when not needed. */ if (static_key_false(&i2c_trace_msg)) { int i; for (i = 0; i < num; i++) if (msgs[i].flags & I2C_M_RD) trace_i2c_read(adap, &msgs[i], i); else trace_i2c_write(adap, &msgs[i], i); } /* Retry automatically on arbitration loss */ orig_jiffies = jiffies; for (ret = 0, try = 0; try <= adap->retries; try++) { ret = adap->algo->master_xfer(adap, msgs, num); if (ret != -EAGAIN) break; if (time_after(jiffies, orig_jiffies + adap->timeout)) break; } if (static_key_false(&i2c_trace_msg)) { int i; for (i = 0; i < ret; i++) if (msgs[i].flags & I2C_M_RD) trace_i2c_reply(adap, &msgs[i], i); trace_i2c_result(adap, i, ret); } return ret; } EXPORT_SYMBOL(__i2c_transfer); /** * i2c_transfer - execute a single or combined I2C message * @adap: Handle to I2C bus * @msgs: One or more messages to execute before STOP is issued to * terminate the operation; each message begins with a START. * @num: Number of messages to be executed. * * Returns negative errno, else the number of messages executed. * * Note that there is no requirement that each message be sent to * the same slave address, although that is the most common model. */ int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num) { int ret; /* REVISIT the fault reporting model here is weak: * * - When we get an error after receiving N bytes from a slave, * there is no way to report "N". * * - When we get a NAK after transmitting N bytes to a slave, * there is no way to report "N" ... or to let the master * continue executing the rest of this combined message, if * that's the appropriate response. * * - When for example "num" is two and we successfully complete * the first message but get an error part way through the * second, it's unclear whether that should be reported as * one (discarding status on the second message) or errno * (discarding status on the first one). */ if (adap->algo->master_xfer) { #ifdef DEBUG for (ret = 0; ret < num; ret++) { dev_dbg(&adap->dev, "master_xfer[%d] %c, addr=0x%02x, " "len=%d%s\n", ret, (msgs[ret].flags & I2C_M_RD) ? 'R' : 'W', msgs[ret].addr, msgs[ret].len, (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : ""); } #endif if (in_atomic() || irqs_disabled()) { ret = i2c_trylock_adapter(adap); if (!ret) /* I2C activity is ongoing. */ return -EAGAIN; } else { i2c_lock_adapter(adap); } ret = __i2c_transfer(adap, msgs, num); i2c_unlock_adapter(adap); return ret; } else { dev_dbg(&adap->dev, "I2C level transfers not supported\n"); return -EOPNOTSUPP; } } EXPORT_SYMBOL(i2c_transfer); /** * i2c_master_send - issue a single I2C message in master transmit mode * @client: Handle to slave device * @buf: Data that will be written to the slave * @count: How many bytes to write, must be less than 64k since msg.len is u16 * * Returns negative errno, or else the number of bytes written. */ int i2c_master_send(const struct i2c_client *client, const char *buf, int count) { int ret; struct i2c_adapter *adap = client->adapter; struct i2c_msg msg; msg.addr = client->addr; msg.flags = client->flags & I2C_M_TEN; msg.len = count; msg.buf = (char *)buf; ret = i2c_transfer(adap, &msg, 1); /* * If everything went ok (i.e. 1 msg transmitted), return #bytes * transmitted, else error code. */ return (ret == 1) ? count : ret; } EXPORT_SYMBOL(i2c_master_send); /** * i2c_master_recv - issue a single I2C message in master receive mode * @client: Handle to slave device * @buf: Where to store data read from slave * @count: How many bytes to read, must be less than 64k since msg.len is u16 * * Returns negative errno, or else the number of bytes read. */ int i2c_master_recv(const struct i2c_client *client, char *buf, int count) { struct i2c_adapter *adap = client->adapter; struct i2c_msg msg; int ret; msg.addr = client->addr; msg.flags = client->flags & I2C_M_TEN; msg.flags |= I2C_M_RD; msg.len = count; msg.buf = buf; ret = i2c_transfer(adap, &msg, 1); /* * If everything went ok (i.e. 1 msg received), return #bytes received, * else error code. */ return (ret == 1) ? count : ret; } EXPORT_SYMBOL(i2c_master_recv); /* ---------------------------------------------------- * the i2c address scanning function * Will not work for 10-bit addresses! * ---------------------------------------------------- */ /* * Legacy default probe function, mostly relevant for SMBus. The default * probe method is a quick write, but it is known to corrupt the 24RF08 * EEPROMs due to a state machine bug, and could also irreversibly * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f, * we use a short byte read instead. Also, some bus drivers don't implement * quick write, so we fallback to a byte read in that case too. * On x86, there is another special case for FSC hardware monitoring chips, * which want regular byte reads (address 0x73.) Fortunately, these are the * only known chips using this I2C address on PC hardware. * Returns 1 if probe succeeded, 0 if not. */ static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr) { int err; union i2c_smbus_data dummy; #ifdef CONFIG_X86 if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON) && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA)) err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0, I2C_SMBUS_BYTE_DATA, &dummy); else #endif if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50) && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK)) err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0, I2C_SMBUS_QUICK, NULL); else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE)) err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0, I2C_SMBUS_BYTE, &dummy); else { dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n", addr); err = -EOPNOTSUPP; } return err >= 0; } static int i2c_detect_address(struct i2c_client *temp_client, struct i2c_driver *driver) { struct i2c_board_info info; struct i2c_adapter *adapter = temp_client->adapter; int addr = temp_client->addr; int err; /* Make sure the address is valid */ err = i2c_check_addr_validity(addr); if (err) { dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n", addr); return err; } /* Skip if already in use */ if (i2c_check_addr_busy(adapter, addr)) return 0; /* Make sure there is something at this address */ if (!i2c_default_probe(adapter, addr)) return 0; /* Finally call the custom detection function */ memset(&info, 0, sizeof(struct i2c_board_info)); info.addr = addr; err = driver->detect(temp_client, &info); if (err) { /* -ENODEV is returned if the detection fails. We catch it here as this isn't an error. */ return err == -ENODEV ? 0 : err; } /* Consistency check */ if (info.type[0] == '\0') { dev_err(&adapter->dev, "%s detection function provided " "no name for 0x%x\n", driver->driver.name, addr); } else { struct i2c_client *client; /* Detection succeeded, instantiate the device */ if (adapter->class & I2C_CLASS_DEPRECATED) dev_warn(&adapter->dev, "This adapter will soon drop class based instantiation of devices. " "Please make sure client 0x%02x gets instantiated by other means. " "Check 'Documentation/i2c/instantiating-devices' for details.\n", info.addr); dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n", info.type, info.addr); client = i2c_new_device(adapter, &info); if (client) list_add_tail(&client->detected, &driver->clients); else dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n", info.type, info.addr); } return 0; } static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver) { const unsigned short *address_list; struct i2c_client *temp_client; int i, err = 0; int adap_id = i2c_adapter_id(adapter); address_list = driver->address_list; if (!driver->detect || !address_list) return 0; /* Warn that the adapter lost class based instantiation */ if (adapter->class == I2C_CLASS_DEPRECATED) { dev_dbg(&adapter->dev, "This adapter dropped support for I2C classes and " "won't auto-detect %s devices anymore. If you need it, check " "'Documentation/i2c/instantiating-devices' for alternatives.\n", driver->driver.name); return 0; } /* Stop here if the classes do not match */ if (!(adapter->class & driver->class)) return 0; /* Set up a temporary client to help detect callback */ temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL); if (!temp_client) return -ENOMEM; temp_client->adapter = adapter; for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) { dev_dbg(&adapter->dev, "found normal entry for adapter %d, " "addr 0x%02x\n", adap_id, address_list[i]); temp_client->addr = address_list[i]; err = i2c_detect_address(temp_client, driver); if (unlikely(err)) break; } kfree(temp_client); return err; } int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr) { return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0, I2C_SMBUS_QUICK, NULL) >= 0; } EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read); struct i2c_client * i2c_new_probed_device(struct i2c_adapter *adap, struct i2c_board_info *info, unsigned short const *addr_list, int (*probe)(struct i2c_adapter *, unsigned short addr)) { int i; if (!probe) probe = i2c_default_probe; for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) { /* Check address validity */ if (i2c_check_addr_validity(addr_list[i]) < 0) { dev_warn(&adap->dev, "Invalid 7-bit address " "0x%02x\n", addr_list[i]); continue; } /* Check address availability */ if (i2c_check_addr_busy(adap, addr_list[i])) { dev_dbg(&adap->dev, "Address 0x%02x already in " "use, not probing\n", addr_list[i]); continue; } /* Test address responsiveness */ if (probe(adap, addr_list[i])) break; } if (addr_list[i] == I2C_CLIENT_END) { dev_dbg(&adap->dev, "Probing failed, no device found\n"); return NULL; } info->addr = addr_list[i]; return i2c_new_device(adap, info); } EXPORT_SYMBOL_GPL(i2c_new_probed_device); struct i2c_adapter *i2c_get_adapter(int nr) { struct i2c_adapter *adapter; mutex_lock(&core_lock); adapter = idr_find(&i2c_adapter_idr, nr); if (adapter && !try_module_get(adapter->owner)) adapter = NULL; mutex_unlock(&core_lock); return adapter; } EXPORT_SYMBOL(i2c_get_adapter); void i2c_put_adapter(struct i2c_adapter *adap) { if (adap) module_put(adap->owner); } EXPORT_SYMBOL(i2c_put_adapter); /* The SMBus parts */ #define POLY (0x1070U << 3) static u8 crc8(u16 data) { int i; for (i = 0; i < 8; i++) { if (data & 0x8000) data = data ^ POLY; data = data << 1; } return (u8)(data >> 8); } /* Incremental CRC8 over count bytes in the array pointed to by p */ static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count) { int i; for (i = 0; i < count; i++) crc = crc8((crc ^ p[i]) << 8); return crc; } /* Assume a 7-bit address, which is reasonable for SMBus */ static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg) { /* The address will be sent first */ u8 addr = (msg->addr << 1) | !!(msg->flags & I2C_M_RD); pec = i2c_smbus_pec(pec, &addr, 1); /* The data buffer follows */ return i2c_smbus_pec(pec, msg->buf, msg->len); } /* Used for write only transactions */ static inline void i2c_smbus_add_pec(struct i2c_msg *msg) { msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg); msg->len++; } /* Return <0 on CRC error If there was a write before this read (most cases) we need to take the partial CRC from the write part into account. Note that this function does modify the message (we need to decrease the message length to hide the CRC byte from the caller). */ static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg) { u8 rpec = msg->buf[--msg->len]; cpec = i2c_smbus_msg_pec(cpec, msg); if (rpec != cpec) { pr_debug("i2c-core: Bad PEC 0x%02x vs. 0x%02x\n", rpec, cpec); return -EBADMSG; } return 0; } /** * i2c_smbus_read_byte - SMBus "receive byte" protocol * @client: Handle to slave device * * This executes the SMBus "receive byte" protocol, returning negative errno * else the byte received from the device. */ s32 i2c_smbus_read_byte(const struct i2c_client *client) { union i2c_smbus_data data; int status; status = i2c_smbus_xfer(client->adapter, client->addr, client->flags, I2C_SMBUS_READ, 0, I2C_SMBUS_BYTE, &data); return (status < 0) ? status : data.byte; } EXPORT_SYMBOL(i2c_smbus_read_byte); /** * i2c_smbus_write_byte - SMBus "send byte" protocol * @client: Handle to slave device * @value: Byte to be sent * * This executes the SMBus "send byte" protocol, returning negative errno * else zero on success. */ s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value) { return i2c_smbus_xfer(client->adapter, client->addr, client->flags, I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL); } EXPORT_SYMBOL(i2c_smbus_write_byte); /** * i2c_smbus_read_byte_data - SMBus "read byte" protocol * @client: Handle to slave device * @command: Byte interpreted by slave * * This executes the SMBus "read byte" protocol, returning negative errno * else a data byte received from the device. */ s32 i2c_smbus_read_byte_data(const struct i2c_client *client, u8 command) { union i2c_smbus_data data; int status; status = i2c_smbus_xfer(client->adapter, client->addr, client->flags, I2C_SMBUS_READ, command, I2C_SMBUS_BYTE_DATA, &data); return (status < 0) ? status : data.byte; } EXPORT_SYMBOL(i2c_smbus_read_byte_data); /** * i2c_smbus_write_byte_data - SMBus "write byte" protocol * @client: Handle to slave device * @command: Byte interpreted by slave * @value: Byte being written * * This executes the SMBus "write byte" protocol, returning negative errno * else zero on success. */ s32 i2c_smbus_write_byte_data(const struct i2c_client *client, u8 command, u8 value) { union i2c_smbus_data data; data.byte = value; return i2c_smbus_xfer(client->adapter, client->addr, client->flags, I2C_SMBUS_WRITE, command, I2C_SMBUS_BYTE_DATA, &data); } EXPORT_SYMBOL(i2c_smbus_write_byte_data); /** * i2c_smbus_read_word_data - SMBus "read word" protocol * @client: Handle to slave device * @command: Byte interpreted by slave * * This executes the SMBus "read word" protocol, returning negative errno * else a 16-bit unsigned "word" received from the device. */ s32 i2c_smbus_read_word_data(const struct i2c_client *client, u8 command) { union i2c_smbus_data data; int status; status = i2c_smbus_xfer(client->adapter, client->addr, client->flags, I2C_SMBUS_READ, command, I2C_SMBUS_WORD_DATA, &data); return (status < 0) ? status : data.word; } EXPORT_SYMBOL(i2c_smbus_read_word_data); /** * i2c_smbus_write_word_data - SMBus "write word" protocol * @client: Handle to slave device * @command: Byte interpreted by slave * @value: 16-bit "word" being written * * This executes the SMBus "write word" protocol, returning negative errno * else zero on success. */ s32 i2c_smbus_write_word_data(const struct i2c_client *client, u8 command, u16 value) { union i2c_smbus_data data; data.word = value; return i2c_smbus_xfer(client->adapter, client->addr, client->flags, I2C_SMBUS_WRITE, command, I2C_SMBUS_WORD_DATA, &data); } EXPORT_SYMBOL(i2c_smbus_write_word_data); /** * i2c_smbus_read_block_data - SMBus "block read" protocol * @client: Handle to slave device * @command: Byte interpreted by slave * @values: Byte array into which data will be read; big enough to hold * the data returned by the slave. SMBus allows at most 32 bytes. * * This executes the SMBus "block read" protocol, returning negative errno * else the number of data bytes in the slave's response. * * Note that using this function requires that the client's adapter support * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality. Not all adapter drivers * support this; its emulation through I2C messaging relies on a specific * mechanism (I2C_M_RECV_LEN) which may not be implemented. */ s32 i2c_smbus_read_block_data(const struct i2c_client *client, u8 command, u8 *values) { union i2c_smbus_data data; int status; status = i2c_smbus_xfer(client->adapter, client->addr, client->flags, I2C_SMBUS_READ, command, I2C_SMBUS_BLOCK_DATA, &data); if (status) return status; memcpy(values, &data.block[1], data.block[0]); return data.block[0]; } EXPORT_SYMBOL(i2c_smbus_read_block_data); /** * i2c_smbus_write_block_data - SMBus "block write" protocol * @client: Handle to slave device * @command: Byte interpreted by slave * @length: Size of data block; SMBus allows at most 32 bytes * @values: Byte array which will be written. * * This executes the SMBus "block write" protocol, returning negative errno * else zero on success. */ s32 i2c_smbus_write_block_data(const struct i2c_client *client, u8 command, u8 length, const u8 *values) { union i2c_smbus_data data; if (length > I2C_SMBUS_BLOCK_MAX) length = I2C_SMBUS_BLOCK_MAX; data.block[0] = length; memcpy(&data.block[1], values, length); return i2c_smbus_xfer(client->adapter, client->addr, client->flags, I2C_SMBUS_WRITE, command, I2C_SMBUS_BLOCK_DATA, &data); } EXPORT_SYMBOL(i2c_smbus_write_block_data); /* Returns the number of read bytes */ s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client, u8 command, u8 length, u8 *values) { union i2c_smbus_data data; int status; if (length > I2C_SMBUS_BLOCK_MAX) length = I2C_SMBUS_BLOCK_MAX; data.block[0] = length; status = i2c_smbus_xfer(client->adapter, client->addr, client->flags, I2C_SMBUS_READ, command, I2C_SMBUS_I2C_BLOCK_DATA, &data); if (status < 0) return status; memcpy(values, &data.block[1], data.block[0]); return data.block[0]; } EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data); s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client, u8 command, u8 length, const u8 *values) { union i2c_smbus_data data; if (length > I2C_SMBUS_BLOCK_MAX) length = I2C_SMBUS_BLOCK_MAX; data.block[0] = length; memcpy(data.block + 1, values, length); return i2c_smbus_xfer(client->adapter, client->addr, client->flags, I2C_SMBUS_WRITE, command, I2C_SMBUS_I2C_BLOCK_DATA, &data); } EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data); /* Simulate a SMBus command using the i2c protocol No checking of parameters is done! */ static s32 i2c_smbus_xfer_emulated(struct i2c_adapter *adapter, u16 addr, unsigned short flags, char read_write, u8 command, int size, union i2c_smbus_data *data) { /* So we need to generate a series of msgs. In the case of writing, we need to use only one message; when reading, we need two. We initialize most things with sane defaults, to keep the code below somewhat simpler. */ unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3]; unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2]; int num = read_write == I2C_SMBUS_READ ? 2 : 1; int i; u8 partial_pec = 0; int status; struct i2c_msg msg[2] = { { .addr = addr, .flags = flags, .len = 1, .buf = msgbuf0, }, { .addr = addr, .flags = flags | I2C_M_RD, .len = 0, .buf = msgbuf1, }, }; msgbuf0[0] = command; switch (size) { case I2C_SMBUS_QUICK: msg[0].len = 0; /* Special case: The read/write field is used as data */ msg[0].flags = flags | (read_write == I2C_SMBUS_READ ? I2C_M_RD : 0); num = 1; break; case I2C_SMBUS_BYTE: if (read_write == I2C_SMBUS_READ) { /* Special case: only a read! */ msg[0].flags = I2C_M_RD | flags; num = 1; } break; case I2C_SMBUS_BYTE_DATA: if (read_write == I2C_SMBUS_READ) msg[1].len = 1; else { msg[0].len = 2; msgbuf0[1] = data->byte; } break; case I2C_SMBUS_WORD_DATA: if (read_write == I2C_SMBUS_READ) msg[1].len = 2; else { msg[0].len = 3; msgbuf0[1] = data->word & 0xff; msgbuf0[2] = data->word >> 8; } break; case I2C_SMBUS_PROC_CALL: num = 2; /* Special case */ read_write = I2C_SMBUS_READ; msg[0].len = 3; msg[1].len = 2; msgbuf0[1] = data->word & 0xff; msgbuf0[2] = data->word >> 8; break; case I2C_SMBUS_BLOCK_DATA: if (read_write == I2C_SMBUS_READ) { msg[1].flags |= I2C_M_RECV_LEN; msg[1].len = 1; /* block length will be added by the underlying bus driver */ } else { msg[0].len = data->block[0] + 2; if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) { dev_err(&adapter->dev, "Invalid block write size %d\n", data->block[0]); return -EINVAL; } for (i = 1; i < msg[0].len; i++) msgbuf0[i] = data->block[i-1]; } break; case I2C_SMBUS_BLOCK_PROC_CALL: num = 2; /* Another special case */ read_write = I2C_SMBUS_READ; if (data->block[0] > I2C_SMBUS_BLOCK_MAX) { dev_err(&adapter->dev, "Invalid block write size %d\n", data->block[0]); return -EINVAL; } msg[0].len = data->block[0] + 2; for (i = 1; i < msg[0].len; i++) msgbuf0[i] = data->block[i-1]; msg[1].flags |= I2C_M_RECV_LEN; msg[1].len = 1; /* block length will be added by the underlying bus driver */ break; case I2C_SMBUS_I2C_BLOCK_DATA: if (read_write == I2C_SMBUS_READ) { msg[1].len = data->block[0]; } else { msg[0].len = data->block[0] + 1; if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) { dev_err(&adapter->dev, "Invalid block write size %d\n", data->block[0]); return -EINVAL; } for (i = 1; i <= data->block[0]; i++) msgbuf0[i] = data->block[i]; } break; default: dev_err(&adapter->dev, "Unsupported transaction %d\n", size); return -EOPNOTSUPP; } i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK && size != I2C_SMBUS_I2C_BLOCK_DATA); if (i) { /* Compute PEC if first message is a write */ if (!(msg[0].flags & I2C_M_RD)) { if (num == 1) /* Write only */ i2c_smbus_add_pec(&msg[0]); else /* Write followed by read */ partial_pec = i2c_smbus_msg_pec(0, &msg[0]); } /* Ask for PEC if last message is a read */ if (msg[num-1].flags & I2C_M_RD) msg[num-1].len++; } status = i2c_transfer(adapter, msg, num); if (status < 0) return status; /* Check PEC if last message is a read */ if (i && (msg[num-1].flags & I2C_M_RD)) { status = i2c_smbus_check_pec(partial_pec, &msg[num-1]); if (status < 0) return status; } if (read_write == I2C_SMBUS_READ) switch (size) { case I2C_SMBUS_BYTE: data->byte = msgbuf0[0]; break; case I2C_SMBUS_BYTE_DATA: data->byte = msgbuf1[0]; break; case I2C_SMBUS_WORD_DATA: case I2C_SMBUS_PROC_CALL: data->word = msgbuf1[0] | (msgbuf1[1] << 8); break; case I2C_SMBUS_I2C_BLOCK_DATA: for (i = 0; i < data->block[0]; i++) data->block[i+1] = msgbuf1[i]; break; case I2C_SMBUS_BLOCK_DATA: case I2C_SMBUS_BLOCK_PROC_CALL: for (i = 0; i < msgbuf1[0] + 1; i++) data->block[i] = msgbuf1[i]; break; } return 0; } /** * i2c_smbus_xfer - execute SMBus protocol operations * @adapter: Handle to I2C bus * @addr: Address of SMBus slave on that bus * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC) * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE * @command: Byte interpreted by slave, for protocols which use such bytes * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL * @data: Data to be read or written * * This executes an SMBus protocol operation, and returns a negative * errno code else zero on success. */ s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags, char read_write, u8 command, int protocol, union i2c_smbus_data *data) { unsigned long orig_jiffies; int try; s32 res; /* If enabled, the following two tracepoints are conditional on * read_write and protocol. */ trace_smbus_write(adapter, addr, flags, read_write, command, protocol, data); trace_smbus_read(adapter, addr, flags, read_write, command, protocol); flags &= I2C_M_TEN | I2C_CLIENT_PEC | I2C_CLIENT_SCCB; if (adapter->algo->smbus_xfer) { i2c_lock_adapter(adapter); /* Retry automatically on arbitration loss */ orig_jiffies = jiffies; for (res = 0, try = 0; try <= adapter->retries; try++) { res = adapter->algo->smbus_xfer(adapter, addr, flags, read_write, command, protocol, data); if (res != -EAGAIN) break; if (time_after(jiffies, orig_jiffies + adapter->timeout)) break; } i2c_unlock_adapter(adapter); if (res != -EOPNOTSUPP || !adapter->algo->master_xfer) goto trace; /* * Fall back to i2c_smbus_xfer_emulated if the adapter doesn't * implement native support for the SMBus operation. */ } res = i2c_smbus_xfer_emulated(adapter, addr, flags, read_write, command, protocol, data); trace: /* If enabled, the reply tracepoint is conditional on read_write. */ trace_smbus_reply(adapter, addr, flags, read_write, command, protocol, data); trace_smbus_result(adapter, addr, flags, read_write, command, protocol, res); return res; } EXPORT_SYMBOL(i2c_smbus_xfer); #if IS_ENABLED(CONFIG_I2C_SLAVE) int i2c_slave_register(struct i2c_client *client, i2c_slave_cb_t slave_cb) { int ret; if (!client || !slave_cb) return -EINVAL; if (!(client->flags & I2C_CLIENT_TEN)) { /* Enforce stricter address checking */ ret = i2c_check_addr_validity(client->addr); if (ret) return ret; } if (!client->adapter->algo->reg_slave) return -EOPNOTSUPP; client->slave_cb = slave_cb; i2c_lock_adapter(client->adapter); ret = client->adapter->algo->reg_slave(client); i2c_unlock_adapter(client->adapter); if (ret) client->slave_cb = NULL; return ret; } EXPORT_SYMBOL_GPL(i2c_slave_register); int i2c_slave_unregister(struct i2c_client *client) { int ret; if (!client->adapter->algo->unreg_slave) return -EOPNOTSUPP; i2c_lock_adapter(client->adapter); ret = client->adapter->algo->unreg_slave(client); i2c_unlock_adapter(client->adapter); if (ret == 0) client->slave_cb = NULL; return ret; } EXPORT_SYMBOL_GPL(i2c_slave_unregister); #endif MODULE_AUTHOR("Simon G. Vogl <[email protected]>"); MODULE_DESCRIPTION("I2C-Bus main module"); MODULE_LICENSE("GPL");
jeremytrimble/adi-linux
drivers/i2c/i2c-core.c
C
gpl-2.0
81,127
/*- * Copyright (c) 2003-2007 Tim Kientzle * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test.h" __FBSDID("$FreeBSD: src/usr.bin/tar/test/test_version.c,v 1.2 2008/05/26 17:10:10 kientzle Exp $"); /* * Test that --version option works and generates reasonable output. */ DEFINE_TEST(test_version) { int r; char *p, *q; size_t s; r = systemf("%s --version >version.stdout 2>version.stderr", testprog); if (r != 0) r = systemf("%s -W version >version.stdout 2>version.stderr", testprog); failure("Unable to run either %s --version or %s -W version", testprog, testprog); if (!assert(r == 0)) return; /* --version should generate nothing to stdout. */ assertEmptyFile("version.stderr"); /* Verify format of version message. */ q = p = slurpfile(&s, "version.stdout"); /* Version message should start with name of program, then space. */ assert(s > 6); failure("Version must start with 'bsdtar': ``%s''", p); if (!assertEqualMem(q, "bsdtar ", 7)) return; q += 7; s -= 7; /* Version number is a series of digits and periods. */ while (s > 0 && (*q == '.' || (*q >= '0' && *q <= '9'))) { ++q; --s; } /* Version number terminated by space. */ failure("No space after bsdtar version: ``%s''", p); assert(s > 1); /* Skip a single trailing a,b,c, or d. */ if (*q == 'a' || *q == 'b' || *q == 'c' || *q == 'd') ++q; failure("No space after bsdtar version: ``%s''", p); assert(*q == ' '); ++q; --s; /* Separator. */ failure("No `-' between bsdtar and libarchive versions: ``%s''", p); assertEqualMem(q, "- ", 2); q += 2; s -= 2; /* libarchive name and version number */ failure("Not long enough for libarchive version: ``%s''", p); assert(s > 11); failure("Libarchive version must start with `libarchive': ``%s''", p); assertEqualMem(q, "libarchive ", 11); q += 11; s -= 11; /* Version number is a series of digits and periods. */ while (s > 0 && (*q == '.' || (*q >= '0' && *q <= '9'))) { ++q; --s; } /* Skip a single trailing a,b,c, or d. */ if (*q == 'a' || *q == 'b' || *q == 'c' || *q == 'd') ++q; /* All terminated by end-of-line. */ assert(s >= 1); /* Skip an optional CR character (e.g., Windows) */ failure("Version output must end with \\n or \\r\\n"); if (*q == '\r') { ++q; --s; } assertEqualMem(q, "\n", 1); free(p); }
kraziegent/mysql-5.6
xtrabackup/src/libarchive/tar/test/test_version.c
C
gpl-2.0
3,554
/** Course formats **/ .course-content .section li.activity {margin:7px 0;} .course-content .header {background-image:url([[pix:theme|gradient_h]]);background-repeat:repeat-x;border-top:1px solid #C6BDA8;background-color:#E3DFD4;} .course-content h2.header {padding-left:1em;} .course-content ul.weeks li.section {border:1px solid #DDD;} .course-content ul.weeks li.section .content {background-color:#FAFAFA;padding:5px 10px;} .course-content ul.weeks li.section .content h3 {margin:0;color:#777;font-weight:normal;} .course-content ul.weeks li.section .left {padding:5px 0;} .course-content ul.weeks li.section .right {padding:5px 0;} /** coursebox **/ .coursebox {border:none} .coursebox > .info {margin:0;font-size:100%;} .coursebox .content {font-size:90%;} .coursebox .enrolmenticons img, .coursebox .moreinfo img {margin: 0.3em 0.2em -0.2em 0;} #page-course-recent h2.main {font-size:110%;} #page-course-recent .user {font-size:75%;} #page-course-recent .grade {font-style:italic;font-size:90%;} #page-course-recent .forum-recent .reply .title {font-style:italic;font-size:90%;} #page-course-recent .forum-recent .discussion .title {font-weight:bold;font-style:italic;font-size:90%;} .path-course-view .availabilityinfo {font-size:85%;color:#aaa;} .path-course-view .availabilityinfo strong {font-weight:normal;color:black;} .path-course-view .dimmed_text img {opacity:0.3;filter:alpha(opacity='30');} .path-course-view .section {line-height:1.2em;} .path-course-view .section .activity {padding:0.2em 0;} .path-course-view .section .activity a {line-height:1em;} .path-course-view .section .weekdates {margin:0;font-weight:normal;font-size:100%;} .path-course-view .section .groupinglabel {color:#666666;} .path-course-view .section .groupinglabel.dimmed_text {color: #AAA;} .path-course-view .section .left {font-weight:bold;} .path-course-view .weeks .section, .path-course-view .topics .section, .path-course-view .section td {border-color:#DDDDDD;} .path-course-view .weeks .content , .path-course-view .topics .content, .path-course-view .weeks .section, .path-course-view .topics .section {background:transparent;} .path-course-view .section td.side {background:#FFFFFF;} .path-course-view .weeks .current, .path-course-view .topics .current, .path-course-view .current td.side {background:#FFD991;} .path-course-view .weeks .hidden, .path-course-view .topics .hidden, .path-course-view .hidden td.side {background:#DDDDDD;} .path-course-view .section .weekdates {color:#777777;} .path-course-view .weeks .weekdates , .path-course-view .topics .weekdates {color:#333333;} .weeks li.section , .topics li.section {border-style:solid;border-width:1px;} .weeks .content, .topics .content {padding:5px;} #page-report-outline-user .section {border-color:#AAAAAA;} #page-admin-report .plugin, #page-report .plugin, #page-course-import .plugin {margin-bottom:20px;margin-left:10%;margin-right:10%;border:1px solid #cecece;background-color:[[setting:blockcontentbgc]];} .path-course-view .unread {background:#E3DFD4;} .path-course-view .completionprogress {font-size:80%; padding:8px 26px 5px 5px;} .course_category_tree.category-browse {padding:20px;} #page-report #content {padding-top:15px;padding-bottom:15px;} #page-report #region-main p, #page-report-log-index #region-main .info, #page-report-loglive-index #region-main .info, #page-report-stats-index #region-main .graph {text-align:center;} #page-report .logselectform, #page-report .participationselectform, #page-report-log-index .logselectform, #page-report-participation-index .participationselectform {text-align:center;} .categorypicker {text-align:center;margin-bottom:10px;} .path-report-outline .loginfo {text-align:center;margin:1em;} /* Course */ /*.courses .coursebox.even {background-color:white; border-color:white;}*/ .courses .coursebox.odd {background-color:[[setting:rblockcolumnbgc]];border-color:[[setting:rblockcolumnbgc]];} .courses .coursebox:hover, .course_category_tree .courses > .paging:hover {background-color:#eee;} /* Category listings */ .course_category_tree .controls {margin-bottom:5px;text-align:right;float:right;} .course_category_tree .controls div {padding-right:2em;font-size:75%;} .course_category_tree .category > .info {background-color:#e3dfd4;background-image:url([[pix:theme|hgradient]]);background-repeat:repeat-x;border:1px solid #ddd;} .course_category_tree.frontpage-category-names .category > .info {background:none;border:none;} .courses > .paging, .course_category_tree .subcategories > .paging {padding:5px;} /* Publication */ #page-course-publish-metadata .metadatatext {width:400px;} #page-course-publish-metadata .hubscreenshot {display:inline;float:left;margin-right:10px;} #page-course-publish-metadata .hubscreenshot img {vertical-align:bottom;} #page-course-publish-metadata .hubdescription {} #page-course-publish-metadata .hubinfo {display:block; margin-bottom:20px;} #page-course-publish-metadata .hublink {} #page-course-publish-backup .courseuploadtextinfo {text-align:center;} #page-course-publish-backup .sharecoursecontinue {text-align:center;}
classroomtechtools/dragonnet-old
theme/formal_white/style/course.css
CSS
gpl-3.0
5,096
# # Copyright (c) 2010-2012, NVIDIA CORPORATION. All rights reserved. # # (C) Copyright 2000-2008 # Wolfgang Denk, DENX Software Engineering, [email protected]. # # This program is free software; you can redistribute it and/or modify it # under the terms and conditions of the GNU General Public License, # version 2, as published by the Free Software Foundation. # # This program is distributed in the hope it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # obj-y += clock.o funcmux.o pinmux.o
r2t2sdr/r2t2
u-boot/arch/arm/cpu/tegra30-common/Makefile
Makefile
gpl-3.0
778
<!DOCTYPE HTML> <html> <head> <meta name="variant" content=""> <meta name="variant" content="?keep-promise"> <title>Test#add_cleanup: multiple functions with one in error</title> <script src="../../variants.js"></script> <script src="../../../testharness.js"></script> <script src="../../../testharnessreport.js"></script> </head> <body> <div id="log"></div> <script> "use strict"; test(function(t) { t.add_cleanup(function() { throw new Error("exception in cleanup function"); }); // The following cleanup function defines a test so that the reported // data demonstrates the intended run-time behavior, i.e. that // `testharness.js` invokes all cleanup functions even when one or more // throw errors. t.add_cleanup(function() { test(function() {}, "Verification test"); }); }, "Test with multiple cleanup functions"); </script> <script type="text/json" id="expected"> { "summarized_status": { "status_string": "ERROR", "message": "Test named 'Test with multiple cleanup functions' specified 2 'cleanup' functions, and 1 failed." }, "summarized_tests": [ { "status_string": "PASS", "name": "Test with multiple cleanup functions", "properties": {}, "message": null }, { "status_string": "NOTRUN", "name": "Verification test", "properties": {}, "message": null } ], "type": "complete" } </script> </body> </html>
asajeffrey/servo
tests/wpt/web-platform-tests/resources/test/tests/functional/add_cleanup_err_multi.html
HTML
mpl-2.0
1,444
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery UI Autocomplete - XML data parsed once</title> <link rel="stylesheet" href="../../themes/base/jquery.ui.all.css"> <script src="../../jquery-1.8.2.js"></script> <script src="../../ui/jquery.ui.core.js"></script> <script src="../../ui/jquery.ui.widget.js"></script> <script src="../../ui/jquery.ui.position.js"></script> <script src="../../ui/jquery.ui.menu.js"></script> <script src="../../ui/jquery.ui.autocomplete.js"></script> <link rel="stylesheet" href="../demos.css"> <style> .ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; } </style> <script> $(function() { function log( message ) { $( "<div/>" ).text( message ).prependTo( "#log" ); $( "#log" ).attr( "scrollTop", 0 ); } $.ajax({ url: "london.xml", dataType: "xml", success: function( xmlResponse ) { var data = $( "geoname", xmlResponse ).map(function() { return { value: $( "name", this ).text() + ", " + ( $.trim( $( "countryName", this ).text() ) || "(unknown country)" ), id: $( "geonameId", this ).text() }; }).get(); $( "#birds" ).autocomplete({ source: data, minLength: 0, select: function( event, ui ) { log( ui.item ? "Selected: " + ui.item.value + ", geonameId: " + ui.item.id : "Nothing selected, input was " + this.value ); } }); } }); }); </script> </head> <body> <div class="ui-widget"> <label for="birds">London matches: </label> <input id="birds" /> </div> <div class="ui-widget" style="margin-top:2em; font-family:Arial"> Result: <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div> </div> <div class="demo-description"> <p>This demo shows how to retrieve some XML data, parse it using jQuery's methods, then provide it to the autocomplete as the datasource.</p> <p>This should also serve as a reference on how to parse a remote XML datasource - the parsing would just happen for each request within the source-callback.</p> </div> </body> </html>
apnadmin/appynotebook
web/sc/nd/js/jquery-ui-1.9.1.custom/development-bundle/demos/autocomplete/xml.html
HTML
agpl-3.0
2,143
var edx = edx || {}; (function($) { 'use strict'; edx.student = edx.student || {}; edx.student.account = edx.student.account || {}; edx.student.account.EmailOptInInterface = { urls: { emailOptInUrl: '/user_api/v1/preferences/email_opt_in/' }, headers: { 'X-CSRFToken': $.cookie('csrftoken') }, /** * Set the email opt in setting for the organization associated * with this course. * @param {string} courseKey Slash-separated course key. * @param {string} emailOptIn The preference to opt in or out of organization emails. */ setPreference: function( courseKey, emailOptIn, context ) { return $.ajax({ url: this.urls.emailOptInUrl, type: 'POST', data: {course_id: courseKey, email_opt_in: emailOptIn}, headers: this.headers, context: context }); } }; })(jQuery);
shubhdev/openedx
lms/static/js/student_account/emailoptin.js
JavaScript
agpl-3.0
1,019
class C<T extends C<? extends C<? extends T>>>{ void foo(C<?> x){ <error descr="Inferred type 'capture<?>' for type parameter 'T' is not within its bound; should extend 'C<? extends capture<?>>'">bar(x)</error>; } <T extends C<? extends T>> void bar(C<T> x){} }
ahb0327/intellij-community
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IDEA57533.java
Java
apache-2.0
282
# Copyright (c) 2014 Cisco Systems, Inc. # 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. from oslo_utils import uuidutils import webob from nova.api.openstack.compute.contrib import server_groups from nova.api.openstack.compute.plugins.v3 import server_groups as sg_v21 from nova.api.openstack import extensions from nova import context import nova.db from nova import exception from nova import objects from nova import test from nova.tests.unit.api.openstack import fakes FAKE_UUID1 = 'a47ae74e-ab08-447f-8eee-ffd43fc46c16' FAKE_UUID2 = 'c6e6430a-6563-4efa-9542-5e93c9e97d18' FAKE_UUID3 = 'b8713410-9ba3-e913-901b-13410ca90121' class AttrDict(dict): def __getattr__(self, k): return self[k] def server_group_template(**kwargs): sgroup = kwargs.copy() sgroup.setdefault('name', 'test') return sgroup def server_group_resp_template(**kwargs): sgroup = kwargs.copy() sgroup.setdefault('name', 'test') sgroup.setdefault('policies', []) sgroup.setdefault('members', []) return sgroup def server_group_db(sg): attrs = sg.copy() if 'id' in attrs: attrs['uuid'] = attrs.pop('id') if 'policies' in attrs: policies = attrs.pop('policies') attrs['policies'] = policies else: attrs['policies'] = [] if 'members' in attrs: members = attrs.pop('members') attrs['members'] = members else: attrs['members'] = [] attrs['deleted'] = 0 attrs['deleted_at'] = None attrs['created_at'] = None attrs['updated_at'] = None if 'user_id' not in attrs: attrs['user_id'] = 'user_id' if 'project_id' not in attrs: attrs['project_id'] = 'project_id' attrs['id'] = 7 return AttrDict(attrs) class ServerGroupTestV21(test.TestCase): validation_error = exception.ValidationError def setUp(self): super(ServerGroupTestV21, self).setUp() self._setup_controller() self.req = fakes.HTTPRequest.blank('') def _setup_controller(self): self.controller = sg_v21.ServerGroupController() def test_create_server_group_with_no_policies(self): sgroup = server_group_template() self.assertRaises(self.validation_error, self.controller.create, self.req, body={'server_group': sgroup}) def _create_server_group_normal(self, policies): sgroup = server_group_template() sgroup['policies'] = policies res_dict = self.controller.create(self.req, body={'server_group': sgroup}) self.assertEqual(res_dict['server_group']['name'], 'test') self.assertTrue(uuidutils.is_uuid_like(res_dict['server_group']['id'])) self.assertEqual(res_dict['server_group']['policies'], policies) def test_create_server_group(self): policies = ['affinity', 'anti-affinity'] for policy in policies: self._create_server_group_normal([policy]) def _create_instance(self, context): instance = objects.Instance(context=context, image_ref=1, node='node1', reservation_id='a', host='host1', project_id='fake', vm_state='fake', system_metadata={'key': 'value'}) instance.create() return instance def _create_instance_group(self, context, members): ig = objects.InstanceGroup(context=context, name='fake_name', user_id='fake_user', project_id='fake', members=members) ig.create() return ig.uuid def _create_groups_and_instances(self, ctx): instances = [self._create_instance(ctx), self._create_instance(ctx)] members = [instance.uuid for instance in instances] ig_uuid = self._create_instance_group(ctx, members) return (ig_uuid, instances, members) def test_display_members(self): ctx = context.RequestContext('fake_user', 'fake') (ig_uuid, instances, members) = self._create_groups_and_instances(ctx) res_dict = self.controller.show(self.req, ig_uuid) result_members = res_dict['server_group']['members'] self.assertEqual(2, len(result_members)) for member in members: self.assertIn(member, result_members) def test_display_active_members_only(self): ctx = context.RequestContext('fake_user', 'fake') (ig_uuid, instances, members) = self._create_groups_and_instances(ctx) # delete an instance instances[1].destroy() # check that the instance does not exist self.assertRaises(exception.InstanceNotFound, objects.Instance.get_by_uuid, ctx, instances[1].uuid) res_dict = self.controller.show(self.req, ig_uuid) result_members = res_dict['server_group']['members'] # check that only the active instance is displayed self.assertEqual(1, len(result_members)) self.assertIn(instances[0].uuid, result_members) def test_create_server_group_with_non_alphanumeric_in_name(self): # The fix for bug #1434335 expanded the allowable character set # for server group names to include non-alphanumeric characters # if they are printable. sgroup = server_group_template(name='good* $%name', policies=['affinity']) res_dict = self.controller.create(self.req, body={'server_group': sgroup}) self.assertEqual(res_dict['server_group']['name'], 'good* $%name') def test_create_server_group_with_illegal_name(self): # blank name sgroup = server_group_template(name='', policies=['test_policy']) self.assertRaises(self.validation_error, self.controller.create, self.req, body={'server_group': sgroup}) # name with length 256 sgroup = server_group_template(name='1234567890' * 26, policies=['test_policy']) self.assertRaises(self.validation_error, self.controller.create, self.req, body={'server_group': sgroup}) # non-string name sgroup = server_group_template(name=12, policies=['test_policy']) self.assertRaises(self.validation_error, self.controller.create, self.req, body={'server_group': sgroup}) # name with leading spaces sgroup = server_group_template(name=' leading spaces', policies=['test_policy']) self.assertRaises(self.validation_error, self.controller.create, self.req, body={'server_group': sgroup}) # name with trailing spaces sgroup = server_group_template(name='trailing space ', policies=['test_policy']) self.assertRaises(self.validation_error, self.controller.create, self.req, body={'server_group': sgroup}) # name with all spaces sgroup = server_group_template(name=' ', policies=['test_policy']) self.assertRaises(self.validation_error, self.controller.create, self.req, body={'server_group': sgroup}) # name with unprintable character sgroup = server_group_template(name='bad\x00name', policies=['test_policy']) self.assertRaises(self.validation_error, self.controller.create, self.req, body={'server_group': sgroup}) # name with out of range char U0001F4A9 sgroup = server_group_template(name=u"\U0001F4A9", policies=['affinity']) self.assertRaises(self.validation_error, self.controller.create, self.req, body={'server_group': sgroup}) def test_create_server_group_with_illegal_policies(self): # blank policy sgroup = server_group_template(name='fake-name', policies='') self.assertRaises(self.validation_error, self.controller.create, self.req, body={'server_group': sgroup}) # policy as integer sgroup = server_group_template(name='fake-name', policies=7) self.assertRaises(self.validation_error, self.controller.create, self.req, body={'server_group': sgroup}) # policy as string sgroup = server_group_template(name='fake-name', policies='invalid') self.assertRaises(self.validation_error, self.controller.create, self.req, body={'server_group': sgroup}) # policy as None sgroup = server_group_template(name='fake-name', policies=None) self.assertRaises(self.validation_error, self.controller.create, self.req, body={'server_group': sgroup}) def test_create_server_group_conflicting_policies(self): sgroup = server_group_template() policies = ['anti-affinity', 'affinity'] sgroup['policies'] = policies self.assertRaises(self.validation_error, self.controller.create, self.req, body={'server_group': sgroup}) def test_create_server_group_with_duplicate_policies(self): sgroup = server_group_template() policies = ['affinity', 'affinity'] sgroup['policies'] = policies self.assertRaises(self.validation_error, self.controller.create, self.req, body={'server_group': sgroup}) def test_create_server_group_not_supported(self): sgroup = server_group_template() policies = ['storage-affinity', 'anti-affinity', 'rack-affinity'] sgroup['policies'] = policies self.assertRaises(self.validation_error, self.controller.create, self.req, body={'server_group': sgroup}) def test_create_server_group_with_no_body(self): self.assertRaises(self.validation_error, self.controller.create, self.req, body=None) def test_create_server_group_with_no_server_group(self): body = {'no-instanceGroup': None} self.assertRaises(self.validation_error, self.controller.create, self.req, body=body) def test_list_server_group_by_tenant(self): groups = [] policies = ['anti-affinity'] members = [] metadata = {} # always empty names = ['default-x', 'test'] sg1 = server_group_resp_template(id=str(1345), name=names[0], policies=policies, members=members, metadata=metadata) sg2 = server_group_resp_template(id=str(891), name=names[1], policies=policies, members=members, metadata=metadata) groups = [sg1, sg2] expected = {'server_groups': groups} def return_server_groups(context, project_id): return [server_group_db(sg) for sg in groups] self.stubs.Set(nova.db, 'instance_group_get_all_by_project_id', return_server_groups) res_dict = self.controller.index(self.req) self.assertEqual(res_dict, expected) def test_list_server_group_all(self): all_groups = [] tenant_groups = [] policies = ['anti-affinity'] members = [] metadata = {} # always empty names = ['default-x', 'test'] sg1 = server_group_resp_template(id=str(1345), name=names[0], policies=[], members=members, metadata=metadata) sg2 = server_group_resp_template(id=str(891), name=names[1], policies=policies, members=members, metadata={}) tenant_groups = [sg2] all_groups = [sg1, sg2] all = {'server_groups': all_groups} tenant_specific = {'server_groups': tenant_groups} def return_all_server_groups(context): return [server_group_db(sg) for sg in all_groups] self.stubs.Set(nova.db, 'instance_group_get_all', return_all_server_groups) def return_tenant_server_groups(context, project_id): return [server_group_db(sg) for sg in tenant_groups] self.stubs.Set(nova.db, 'instance_group_get_all_by_project_id', return_tenant_server_groups) path = '/os-server-groups?all_projects=True' req = fakes.HTTPRequest.blank(path, use_admin_context=True) res_dict = self.controller.index(req) self.assertEqual(res_dict, all) req = fakes.HTTPRequest.blank(path) res_dict = self.controller.index(req) self.assertEqual(res_dict, tenant_specific) def test_delete_server_group_by_id(self): sg = server_group_template(id='123') self.called = False def server_group_delete(context, id): self.called = True def return_server_group(context, group_id): self.assertEqual(sg['id'], group_id) return server_group_db(sg) self.stubs.Set(nova.db, 'instance_group_delete', server_group_delete) self.stubs.Set(nova.db, 'instance_group_get', return_server_group) resp = self.controller.delete(self.req, '123') self.assertTrue(self.called) # NOTE: on v2.1, http status code is set as wsgi_code of API # method instead of status_int in a response object. if isinstance(self.controller, sg_v21.ServerGroupController): status_int = self.controller.delete.wsgi_code else: status_int = resp.status_int self.assertEqual(204, status_int) def test_delete_non_existing_server_group(self): self.assertRaises(webob.exc.HTTPNotFound, self.controller.delete, self.req, 'invalid') class ServerGroupTestV2(ServerGroupTestV21): validation_error = webob.exc.HTTPBadRequest def _setup_controller(self): ext_mgr = extensions.ExtensionManager() ext_mgr.extensions = {} self.controller = server_groups.ServerGroupController(ext_mgr)
jeffrey4l/nova
nova/tests/unit/api/openstack/compute/contrib/test_server_groups.py
Python
apache-2.0
15,330
--- layout: global title: SHOW PARTITIONS displayTitle: SHOW PARTITIONS license: | 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. --- ### Description The `SHOW PARTITIONS` statement is used to list partitions of a table. An optional partition spec may be specified to return the partitions matching the supplied partition spec. ### Syntax ```sql SHOW PARTITIONS table_identifier [ partition_spec ] ``` ### Parameters * **table_identifier** Specifies a table name, which may be optionally qualified with a database name. **Syntax:** `[ database_name. ] table_name` * **partition_spec** An optional parameter that specifies a comma separated list of key and value pairs for partitions. When specified, the partitions that match the partition specification are returned. **Syntax:** `PARTITION ( partition_col_name = partition_col_val [ , ... ] )` ### Examples ```sql -- create a partitioned table and insert a few rows. USE salesdb; CREATE TABLE customer(id INT, name STRING) PARTITIONED BY (state STRING, city STRING); INSERT INTO customer PARTITION (state = 'CA', city = 'Fremont') VALUES (100, 'John'); INSERT INTO customer PARTITION (state = 'CA', city = 'San Jose') VALUES (200, 'Marry'); INSERT INTO customer PARTITION (state = 'AZ', city = 'Peoria') VALUES (300, 'Daniel'); -- Lists all partitions for table `customer` SHOW PARTITIONS customer; +----------------------+ | partition| +----------------------+ | state=AZ/city=Peoria| | state=CA/city=Fremont| |state=CA/city=San Jose| +----------------------+ -- Lists all partitions for the qualified table `customer` SHOW PARTITIONS salesdb.customer; +----------------------+ | partition| +----------------------+ | state=AZ/city=Peoria| | state=CA/city=Fremont| |state=CA/city=San Jose| +----------------------+ -- Specify a full partition spec to list specific partition SHOW PARTITIONS customer PARTITION (state = 'CA', city = 'Fremont'); +---------------------+ | partition| +---------------------+ |state=CA/city=Fremont| +---------------------+ -- Specify a partial partition spec to list the specific partitions SHOW PARTITIONS customer PARTITION (state = 'CA'); +----------------------+ | partition| +----------------------+ | state=CA/city=Fremont| |state=CA/city=San Jose| +----------------------+ -- Specify a partial spec to list specific partition SHOW PARTITIONS customer PARTITION (city = 'San Jose'); +----------------------+ | partition| +----------------------+ |state=CA/city=San Jose| +----------------------+ ``` ### Related Statements * [CREATE TABLE](sql-ref-syntax-ddl-create-table.html) * [INSERT STATEMENT](sql-ref-syntax-dml-insert.html) * [DESCRIBE TABLE](sql-ref-syntax-aux-describe-table.html) * [SHOW TABLE](sql-ref-syntax-aux-show-table.html)
maropu/spark
docs/sql-ref-syntax-aux-show-partitions.md
Markdown
apache-2.0
3,564