repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
kipid/blog | nodejs/node.js-mysql-1/node_modules/underscore/cjs/isSet.js | 305 | var _tagTester = require('./_tagTester.js');
var _stringTagBug = require('./_stringTagBug.js');
var _methodFingerprint = require('./_methodFingerprint.js');
var isSet = _stringTagBug.isIE11 ? _methodFingerprint.ie11fingerprint(_methodFingerprint.setMethods) : _tagTester('Set');
module.exports = isSet;
| mit |
npomfret/XChange | xchange-dsx/src/main/java/org/knowm/xchange/dsx/service/trade/params/DSXTradeHistoryParams.java | 1997 | package org.knowm.xchange.dsx.service.trade.params;
import java.util.Date;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair;
import org.knowm.xchange.service.trade.params.TradeHistoryParamLimit;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsIdSpan;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsSorted;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan;
public class DSXTradeHistoryParams
implements TradeHistoryParamsIdSpan,
TradeHistoryParamsTimeSpan,
TradeHistoryParamCurrencyPair,
TradeHistoryParamsSorted,
TradeHistoryParamLimit {
private String startId;
private String endId;
private Date startTime;
private Date endTime;
private Order order;
private Integer limit;
private CurrencyPair currencyPair;
@Override
public Integer getLimit() {
return limit;
}
@Override
public void setLimit(Integer limit) {
this.limit = limit;
}
@Override
public String getStartId() {
return startId;
}
@Override
public void setStartId(String startId) {
this.startId = startId;
}
@Override
public String getEndId() {
return endId;
}
@Override
public void setEndId(String endId) {
this.endId = endId;
}
@Override
public Date getStartTime() {
return startTime;
}
@Override
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
@Override
public Date getEndTime() {
return endTime;
}
@Override
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
@Override
public Order getOrder() {
return order;
}
@Override
public void setOrder(Order order) {
this.order = order;
}
@Override
public CurrencyPair getCurrencyPair() {
return currencyPair;
}
@Override
public void setCurrencyPair(CurrencyPair currencyPair) {
this.currencyPair = currencyPair;
}
}
| mit |
rainlike/justshop | vendor/payum/payum/src/Payum/Core/Bridge/Symfony/PayumEvents.php | 251 | <?php
namespace Payum\Core\Bridge\Symfony;
final class PayumEvents
{
const GATEWAY_PRE_EXECUTE = 'payum.gateway.pre_execute';
const GATEWAY_EXECUTE = 'payum.gateway.execute';
const GATEWAY_POST_EXECUTE = 'payum.gateway.post_execute';
}
| mit |
local-minimum/ludumdare | src/shrub/src/other/constants.php | 2597 | <?php
/// @defgroup Other
/// @ingroup Modules
/// Names that shouldn't be allowed. Again these are names, not words.
global_AddReservedName(
// Religion and delicate subjects
'god',
'devil',
'jesus',
'christ',
'satan',
'allah',
'mohamed',
'xenu',
'christian',
'atheist',
'atheism',
'jewish',
'jew',
'jews',
'muslim',
'scientologist',
'scientology',
'jihad',
'nazis',
'nazi',
'communists',
'communist',
'republicans',
'republican',
'democrats',
'democrat',
'liberals',
'liberal',
'dictators',
'dictator',
'socialists',
'socialist',
'wikileaks',
'wikileak',
'terrorists',
'terrorist',
'terrorism',
'hitler',
'trump',
'clinton',
'obama',
'putin',
'911',
// Business
'sales',
'sale',
'marketing',
'ceo',
'cfo',
'cto',
'legal',
'lawers',
'lawer',
'law',
'owners',
'owner',
'boss',
'managers',
'manager',
'masters',
'master',
'slaves',
'slave',
'contacts',
'contact',
'contracts',
'contract',
'contractors',
'contractor',
'jobs',
'job',
'charities',
'charity',
'payments',
'payment',
'orders',
'order',
'refunds',
'refund',
'deals',
'deal',
'discounts',
'discount',
'privacy',
'piracy',
'dmca',
// Companies and Brands (of concequence)
'valve',
'nintendo',
'sony',
'microsoft',
'sega',
'konami',
'capcom',
'atari',
'namco',
'activision',
'playstation',
'xbox',
'steam',
'iphone',
'ipad',
'ios',
'android',
'windows',
'mac',
'linux',
'twitter',
'twitch',
'facebook',
'google',
'apple',
'amazon',
'netflix',
'instagram',
'snapchat',
'tumblr',
'hasbro',
'mattel',
'disney',
'marvel',
// Profanity and troublesome words
'fuck',
'fucks',
'fucker',
'fuckers',
'fucking',
'fuckyou',
'fuckme',
'fat',
'ass',
'asses',
'asshole',
'assholes',
'anal',
'shit',
'shits',
'wank',
'wanks',
'wanker',
'wankers',
'bollock',
'bollocks',
'bitch',
'bitches',
'twat',
'twats',
'dick',
'cocks',
'cock',
'cocks',
'penis',
'pussy',
'pussies',
'vagina',
'vaginas',
'tit',
'tits',
'cunt',
'cunts',
'clit',
'clits',
'gay',
'gays',
'fag',
'fags',
'fagot',
'fagots',
'faggot',
'faggots',
'sex',
'sexy',
'rape',
'whore',
'whores',
'porn',
'porno',
'pornography',
'cum',
'cumming',
'niger',
'nigers',
'wtf' // what I'm thinking right now
// Congratulations, you found the swear-words in the source code.
// We're not using a very sophisticated name blocker, nor are we censoring speech,
// we just want to avoid these accounts getting created.
// It's not meant to be comprehensive, just to help discourage juvenile behavior.
);
| mit |
928PJY/docfx | src/Microsoft.DocAsCode.MarkdownLite/IMarkdownRewriteEngine.cs | 1256 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.MarkdownLite
{
using System;
using System.Collections.Immutable;
/// <summary>
/// Markdown rewrite engine.
/// </summary>
public interface IMarkdownRewriteEngine
{
/// <summary>
/// Get markdown engine.
/// </summary>
IMarkdownEngine Engine { get; }
/// <summary>
/// Rewrite markdown tokens.
/// </summary>
/// <param name="tokens">Source markdown tokens.</param>
/// <returns>Rewritten markdown tokens.</returns>
ImmutableArray<IMarkdownToken> Rewrite(ImmutableArray<IMarkdownToken> tokens);
ImmutableArray<IMarkdownToken> GetParents();
bool HasVariable(string name);
object GetVariable(string name);
void SetVariable(string name, object value);
void RemoveVariable(string name);
bool HasPostProcess(string name);
void SetPostProcess(string name, Action<IMarkdownRewriteEngine> action);
void RemovePostProcess(string name);
void Initialize();
void Complete();
}
}
| mit |
vancarney/apihero-module-socket.io | node_modules/apihero-module-browserify/test/server/common/models/AnonymousModel_0.js | 168 | /*
* AnonymousModel_0.js
* Schema Generated by API-Hero
* Add custom Schema Validators, Types and Methods below
*/
module.exports = function(AnonymousModel_0) {
}; | mit |
cdnjs/cdnjs | ajax/libs/react-dates/21.8.0/shapes/SingleDatePickerShape.js | 4935 | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _propTypes = _interopRequireDefault(require("prop-types"));
var _reactMomentProptypes = _interopRequireDefault(require("react-moment-proptypes"));
var _airbnbPropTypes = require("airbnb-prop-types");
var _defaultPhrases = require("../defaultPhrases");
var _getPhrasePropTypes = _interopRequireDefault(require("../utils/getPhrasePropTypes"));
var _IconPositionShape = _interopRequireDefault(require("./IconPositionShape"));
var _OrientationShape = _interopRequireDefault(require("./OrientationShape"));
var _AnchorDirectionShape = _interopRequireDefault(require("./AnchorDirectionShape"));
var _OpenDirectionShape = _interopRequireDefault(require("./OpenDirectionShape"));
var _DayOfWeekShape = _interopRequireDefault(require("./DayOfWeekShape"));
var _CalendarInfoPositionShape = _interopRequireDefault(require("./CalendarInfoPositionShape"));
var _NavPositionShape = _interopRequireDefault(require("./NavPositionShape"));
var _default = {
// required props for a functional interactive SingleDatePicker
date: _reactMomentProptypes["default"].momentObj,
onDateChange: _propTypes["default"].func.isRequired,
focused: _propTypes["default"].bool,
onFocusChange: _propTypes["default"].func.isRequired,
// input related props
id: _propTypes["default"].string.isRequired,
placeholder: _propTypes["default"].string,
ariaLabel: _propTypes["default"].string,
disabled: _propTypes["default"].bool,
required: _propTypes["default"].bool,
readOnly: _propTypes["default"].bool,
screenReaderInputMessage: _propTypes["default"].string,
showClearDate: _propTypes["default"].bool,
customCloseIcon: _propTypes["default"].node,
showDefaultInputIcon: _propTypes["default"].bool,
inputIconPosition: _IconPositionShape["default"],
customInputIcon: _propTypes["default"].node,
noBorder: _propTypes["default"].bool,
block: _propTypes["default"].bool,
small: _propTypes["default"].bool,
regular: _propTypes["default"].bool,
verticalSpacing: _airbnbPropTypes.nonNegativeInteger,
keepFocusOnInput: _propTypes["default"].bool,
// calendar presentation and interaction related props
renderMonthText: (0, _airbnbPropTypes.mutuallyExclusiveProps)(_propTypes["default"].func, 'renderMonthText', 'renderMonthElement'),
renderMonthElement: (0, _airbnbPropTypes.mutuallyExclusiveProps)(_propTypes["default"].func, 'renderMonthText', 'renderMonthElement'),
renderWeekHeaderElement: _propTypes["default"].func,
orientation: _OrientationShape["default"],
anchorDirection: _AnchorDirectionShape["default"],
openDirection: _OpenDirectionShape["default"],
horizontalMargin: _propTypes["default"].number,
withPortal: _propTypes["default"].bool,
withFullScreenPortal: _propTypes["default"].bool,
appendToBody: _propTypes["default"].bool,
disableScroll: _propTypes["default"].bool,
initialVisibleMonth: _propTypes["default"].func,
firstDayOfWeek: _DayOfWeekShape["default"],
numberOfMonths: _propTypes["default"].number,
keepOpenOnDateSelect: _propTypes["default"].bool,
reopenPickerOnClearDate: _propTypes["default"].bool,
renderCalendarInfo: _propTypes["default"].func,
calendarInfoPosition: _CalendarInfoPositionShape["default"],
hideKeyboardShortcutsPanel: _propTypes["default"].bool,
daySize: _airbnbPropTypes.nonNegativeInteger,
isRTL: _propTypes["default"].bool,
verticalHeight: _airbnbPropTypes.nonNegativeInteger,
transitionDuration: _airbnbPropTypes.nonNegativeInteger,
horizontalMonthPadding: _airbnbPropTypes.nonNegativeInteger,
// navigation related props
dayPickerNavigationInlineStyles: _propTypes["default"].object,
navPosition: _NavPositionShape["default"],
navPrev: _propTypes["default"].node,
navNext: _propTypes["default"].node,
renderNavPrevButton: _propTypes["default"].func,
renderNavNextButton: _propTypes["default"].func,
onPrevMonthClick: _propTypes["default"].func,
onNextMonthClick: _propTypes["default"].func,
onClose: _propTypes["default"].func,
// day presentation and interaction related props
renderCalendarDay: _propTypes["default"].func,
renderDayContents: _propTypes["default"].func,
enableOutsideDays: _propTypes["default"].bool,
isDayBlocked: _propTypes["default"].func,
isOutsideRange: _propTypes["default"].func,
isDayHighlighted: _propTypes["default"].func,
// internationalization props
displayFormat: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].func]),
monthFormat: _propTypes["default"].string,
weekDayFormat: _propTypes["default"].string,
phrases: _propTypes["default"].shape((0, _getPhrasePropTypes["default"])(_defaultPhrases.SingleDatePickerPhrases)),
dayAriaLabelFormat: _propTypes["default"].string
};
exports["default"] = _default; | mit |
bartlomiej-laczkowski/che | samples/sample-plugin-filetype/che-sample-plugin-filetype-ide/src/main/java/org/eclipse/che/plugin/filetype/ide/MyFileTypeExtension.java | 1864 | /*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* 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
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.plugin.filetype.ide;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.eclipse.che.ide.api.action.ActionManager;
import org.eclipse.che.ide.api.action.DefaultActionGroup;
import org.eclipse.che.ide.api.extension.Extension;
import org.eclipse.che.ide.api.filetypes.FileType;
import org.eclipse.che.ide.api.filetypes.FileTypeRegistry;
import org.eclipse.che.plugin.filetype.ide.action.CreateMyFileAction;
import static org.eclipse.che.ide.api.action.IdeActions.GROUP_MAIN_CONTEXT_MENU;
/**
* Simple extension that registers the custom "MyFileType" and
* an action to create files of that type.
*
* @author Edgar Mueller
*/
@Extension(title = "My FileType Extension")
public class MyFileTypeExtension {
@Inject
public void MyFileTypeExtension(
final ActionManager actionManager,
final CreateMyFileAction createMyFileAction,
final FileTypeRegistry fileTypeRegistry,
final @Named("MyFileType") FileType myFileType) {
actionManager.registerAction("createMyFileAction", createMyFileAction);
DefaultActionGroup mainContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_CONTEXT_MENU);
mainContextMenu.add(createMyFileAction);
fileTypeRegistry.registerFileType(myFileType);
}
}
| epl-1.0 |
phxql/smarthome | bundles/config/org.eclipse.smarthome.config.discovery/src/main/java/org/eclipse/smarthome/config/discovery/inbox/InboxListener.java | 1897 | /**
* Copyright (c) 2014-2016 by the respective copyright holders.
* 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
*/
package org.eclipse.smarthome.config.discovery.inbox;
import org.eclipse.smarthome.config.discovery.DiscoveryResult;
/**
* The {@link InboxListener} interface for receiving {@link Inbox} events.
* <p>
* A class that is interested in processing {@link Inbox} events fired synchronously by the {@link Inbox} service has to
* implement this interface.
*
* @author Michael Grammling - Initial Contribution.
*
* @see Inbox
*/
public interface InboxListener {
/**
* Invoked synchronously when a <i>NEW</i> {@link DiscoveryResult} has been added
* to the {@link Inbox}.
*
* @param source the inbox which is the source of this event (not null)
* @param result the discovery result which has been added to the inbox (not null)
*/
void thingAdded(Inbox source, DiscoveryResult result);
/**
* Invoked synchronously when an <i>EXISTING</i> {@link DiscoveryResult} has been
* updated in the {@link Inbox}.
*
* @param source the inbox which is the source of this event (not null)
* @param result the discovery result which has been updated in the inbox (not null)
*/
void thingUpdated(Inbox source, DiscoveryResult result);
/**
* Invoked synchronously when an <i>EXISTING</i> {@link DiscoveryResult} has been
* removed from the {@link Inbox}.
*
* @param source the inbox which is the source of this event (not null)
* @param result the discovery result which has been removed from the inbox (not null)
*/
void thingRemoved(Inbox source, DiscoveryResult result);
}
| epl-1.0 |
14mRh4X0r/ForgeGradle | src/main/java/net/minecraftforge/gradle/patching/Base64.java | 4158 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package net.minecraftforge.gradle.patching;
import java.io.ByteArrayOutputStream;
import java.util.*;
/**
* STOLEN FROM diff4j v1.1
*
* Base64 utility methods.
*
* @author Maros Sandor
*/
class Base64
{
private Base64()
{
}
public static byte[] decode(List<String> ls)
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
for (String s : ls)
{
decode(s, bos);
}
return bos.toByteArray();
}
private static void decode(String s, ByteArrayOutputStream bos)
{
int i = 0;
int len = s.length();
while (true)
{
while (i < len && s.charAt(i) <= ' ')
{
i++;
}
if (i == len)
{
break;
}
int tri = (decode(s.charAt(i)) << 18)
+ (decode(s.charAt(i + 1)) << 12)
+ (decode(s.charAt(i + 2)) << 6)
+ (decode(s.charAt(i + 3)));
bos.write((tri >> 16) & 255);
if (s.charAt(i + 2) == '=')
{
break;
}
bos.write((tri >> 8) & 255);
if (s.charAt(i + 3) == '=')
{
break;
}
bos.write(tri & 255);
i += 4;
}
}
private static int decode(char c)
{
if (c >= 'A' && c <= 'Z')
{
return ((int) c) - 65;
}
else if (c >= 'a' && c <= 'z')
{
return ((int) c) - 97 + 26;
}
else if (c >= '0' && c <= '9')
{
return ((int) c) - 48 + 26 + 26;
}
else
{
switch (c)
{
case '+':
return 62;
case '/':
return 63;
case '=':
return 0;
default:
throw new RuntimeException("unexpected code: " + c);
}
}
}
}
| epl-1.0 |
pplatek/adempiere | base/src/org/compiere/model/X_C_DunningLevel.java | 14333 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/** Generated Model - DO NOT CHANGE */
package org.compiere.model;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.util.Properties;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
/** Generated Model for C_DunningLevel
* @author Adempiere (generated)
* @version Release 3.8.0 - $Id$ */
public class X_C_DunningLevel extends PO implements I_C_DunningLevel, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20150223L;
/** Standard Constructor */
public X_C_DunningLevel (Properties ctx, int C_DunningLevel_ID, String trxName)
{
super (ctx, C_DunningLevel_ID, trxName);
/** if (C_DunningLevel_ID == 0)
{
setC_DunningLevel_ID (0);
setC_Dunning_ID (0);
setChargeFee (false);
setChargeInterest (false);
setDaysAfterDue (Env.ZERO);
setDaysBetweenDunning (0);
setIsSetCreditStop (false);
setIsSetPaymentTerm (false);
setIsShowAllDue (false);
setIsShowNotDue (false);
setIsStatement (false);
// N
setName (null);
setPrintName (null);
} */
}
/** Load Constructor */
public X_C_DunningLevel (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 3 - Client - Org
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_DunningLevel[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Dunning Level.
@param C_DunningLevel_ID Dunning Level */
public void setC_DunningLevel_ID (int C_DunningLevel_ID)
{
if (C_DunningLevel_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DunningLevel_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DunningLevel_ID, Integer.valueOf(C_DunningLevel_ID));
}
/** Get Dunning Level.
@return Dunning Level */
public int getC_DunningLevel_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DunningLevel_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_C_Dunning getC_Dunning() throws RuntimeException
{
return (org.compiere.model.I_C_Dunning)MTable.get(getCtx(), org.compiere.model.I_C_Dunning.Table_Name)
.getPO(getC_Dunning_ID(), get_TrxName()); }
/** Set Dunning.
@param C_Dunning_ID
Dunning Rules for overdue invoices
*/
public void setC_Dunning_ID (int C_Dunning_ID)
{
if (C_Dunning_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Dunning_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Dunning_ID, Integer.valueOf(C_Dunning_ID));
}
/** Get Dunning.
@return Dunning Rules for overdue invoices
*/
public int getC_Dunning_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Dunning_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_C_PaymentTerm getC_PaymentTerm() throws RuntimeException
{
return (org.compiere.model.I_C_PaymentTerm)MTable.get(getCtx(), org.compiere.model.I_C_PaymentTerm.Table_Name)
.getPO(getC_PaymentTerm_ID(), get_TrxName()); }
/** Set Payment Term.
@param C_PaymentTerm_ID
The terms of Payment (timing, discount)
*/
public void setC_PaymentTerm_ID (int C_PaymentTerm_ID)
{
if (C_PaymentTerm_ID < 1)
set_Value (COLUMNNAME_C_PaymentTerm_ID, null);
else
set_Value (COLUMNNAME_C_PaymentTerm_ID, Integer.valueOf(C_PaymentTerm_ID));
}
/** Get Payment Term.
@return The terms of Payment (timing, discount)
*/
public int getC_PaymentTerm_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_PaymentTerm_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Charge fee.
@param ChargeFee
Indicates if fees will be charged for overdue invoices
*/
public void setChargeFee (boolean ChargeFee)
{
set_Value (COLUMNNAME_ChargeFee, Boolean.valueOf(ChargeFee));
}
/** Get Charge fee.
@return Indicates if fees will be charged for overdue invoices
*/
public boolean isChargeFee ()
{
Object oo = get_Value(COLUMNNAME_ChargeFee);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Charge Interest.
@param ChargeInterest
Indicates if interest will be charged on overdue invoices
*/
public void setChargeInterest (boolean ChargeInterest)
{
set_Value (COLUMNNAME_ChargeInterest, Boolean.valueOf(ChargeInterest));
}
/** Get Charge Interest.
@return Indicates if interest will be charged on overdue invoices
*/
public boolean isChargeInterest ()
{
Object oo = get_Value(COLUMNNAME_ChargeInterest);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Days after due date.
@param DaysAfterDue
Days after due date to dun (if negative days until due)
*/
public void setDaysAfterDue (BigDecimal DaysAfterDue)
{
set_Value (COLUMNNAME_DaysAfterDue, DaysAfterDue);
}
/** Get Days after due date.
@return Days after due date to dun (if negative days until due)
*/
public BigDecimal getDaysAfterDue ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DaysAfterDue);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Days between dunning.
@param DaysBetweenDunning
Days between sending dunning notices
*/
public void setDaysBetweenDunning (int DaysBetweenDunning)
{
set_Value (COLUMNNAME_DaysBetweenDunning, Integer.valueOf(DaysBetweenDunning));
}
/** Get Days between dunning.
@return Days between sending dunning notices
*/
public int getDaysBetweenDunning ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DaysBetweenDunning);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
public org.compiere.model.I_AD_PrintFormat getDunning_PrintFormat() throws RuntimeException
{
return (org.compiere.model.I_AD_PrintFormat)MTable.get(getCtx(), org.compiere.model.I_AD_PrintFormat.Table_Name)
.getPO(getDunning_PrintFormat_ID(), get_TrxName()); }
/** Set Dunning Print Format.
@param Dunning_PrintFormat_ID
Print Format for printing Dunning Letters
*/
public void setDunning_PrintFormat_ID (int Dunning_PrintFormat_ID)
{
if (Dunning_PrintFormat_ID < 1)
set_Value (COLUMNNAME_Dunning_PrintFormat_ID, null);
else
set_Value (COLUMNNAME_Dunning_PrintFormat_ID, Integer.valueOf(Dunning_PrintFormat_ID));
}
/** Get Dunning Print Format.
@return Print Format for printing Dunning Letters
*/
public int getDunning_PrintFormat_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Dunning_PrintFormat_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Fee Amount.
@param FeeAmt
Fee amount in invoice currency
*/
public void setFeeAmt (BigDecimal FeeAmt)
{
set_Value (COLUMNNAME_FeeAmt, FeeAmt);
}
/** Get Fee Amount.
@return Fee amount in invoice currency
*/
public BigDecimal getFeeAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_FeeAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Interest in percent.
@param InterestPercent
Percentage interest to charge on overdue invoices
*/
public void setInterestPercent (BigDecimal InterestPercent)
{
set_Value (COLUMNNAME_InterestPercent, InterestPercent);
}
/** Get Interest in percent.
@return Percentage interest to charge on overdue invoices
*/
public BigDecimal getInterestPercent ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_InterestPercent);
if (bd == null)
return Env.ZERO;
return bd;
}
/** InvoiceCollectionType AD_Reference_ID=394 */
public static final int INVOICECOLLECTIONTYPE_AD_Reference_ID=394;
/** Dunning = D */
public static final String INVOICECOLLECTIONTYPE_Dunning = "D";
/** Collection Agency = C */
public static final String INVOICECOLLECTIONTYPE_CollectionAgency = "C";
/** Legal Procedure = L */
public static final String INVOICECOLLECTIONTYPE_LegalProcedure = "L";
/** Uncollectable = U */
public static final String INVOICECOLLECTIONTYPE_Uncollectable = "U";
/** Set Collection Status.
@param InvoiceCollectionType
Invoice Collection Status
*/
public void setInvoiceCollectionType (String InvoiceCollectionType)
{
set_Value (COLUMNNAME_InvoiceCollectionType, InvoiceCollectionType);
}
/** Get Collection Status.
@return Invoice Collection Status
*/
public String getInvoiceCollectionType ()
{
return (String)get_Value(COLUMNNAME_InvoiceCollectionType);
}
/** Set Credit Stop.
@param IsSetCreditStop
Set the business partner to credit stop
*/
public void setIsSetCreditStop (boolean IsSetCreditStop)
{
set_Value (COLUMNNAME_IsSetCreditStop, Boolean.valueOf(IsSetCreditStop));
}
/** Get Credit Stop.
@return Set the business partner to credit stop
*/
public boolean isSetCreditStop ()
{
Object oo = get_Value(COLUMNNAME_IsSetCreditStop);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Set Payment Term.
@param IsSetPaymentTerm
Set the payment term of the Business Partner
*/
public void setIsSetPaymentTerm (boolean IsSetPaymentTerm)
{
set_Value (COLUMNNAME_IsSetPaymentTerm, Boolean.valueOf(IsSetPaymentTerm));
}
/** Get Set Payment Term.
@return Set the payment term of the Business Partner
*/
public boolean isSetPaymentTerm ()
{
Object oo = get_Value(COLUMNNAME_IsSetPaymentTerm);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Show All Due.
@param IsShowAllDue
Show/print all due invoices
*/
public void setIsShowAllDue (boolean IsShowAllDue)
{
set_Value (COLUMNNAME_IsShowAllDue, Boolean.valueOf(IsShowAllDue));
}
/** Get Show All Due.
@return Show/print all due invoices
*/
public boolean isShowAllDue ()
{
Object oo = get_Value(COLUMNNAME_IsShowAllDue);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Show Not Due.
@param IsShowNotDue
Show/print all invoices which are not due (yet).
*/
public void setIsShowNotDue (boolean IsShowNotDue)
{
set_Value (COLUMNNAME_IsShowNotDue, Boolean.valueOf(IsShowNotDue));
}
/** Get Show Not Due.
@return Show/print all invoices which are not due (yet).
*/
public boolean isShowNotDue ()
{
Object oo = get_Value(COLUMNNAME_IsShowNotDue);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Is Statement.
@param IsStatement
Dunning Level is a definition of a statement
*/
public void setIsStatement (boolean IsStatement)
{
set_Value (COLUMNNAME_IsStatement, Boolean.valueOf(IsStatement));
}
/** Get Is Statement.
@return Dunning Level is a definition of a statement
*/
public boolean isStatement ()
{
Object oo = get_Value(COLUMNNAME_IsStatement);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Note.
@param Note
Optional additional user defined information
*/
public void setNote (String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
/** Get Note.
@return Optional additional user defined information
*/
public String getNote ()
{
return (String)get_Value(COLUMNNAME_Note);
}
/** Set Print Text.
@param PrintName
The label text to be printed on a document or correspondence.
*/
public void setPrintName (String PrintName)
{
set_Value (COLUMNNAME_PrintName, PrintName);
}
/** Get Print Text.
@return The label text to be printed on a document or correspondence.
*/
public String getPrintName ()
{
return (String)get_Value(COLUMNNAME_PrintName);
}
} | gpl-2.0 |
cameronscott137/rustbuilt | wp-content/themes/rustbuilt/core/model/modx/processors/browser/file/create.class.php | 2294 | <?php
/**
* Updates a file.
*
* @param string $file The absolute path of the file
* @param string $name Will rename the file if different
* @param string $content The new content of the file
*
* @package modx
* @subpackage processors.browser.file
*/
class modBrowserFileCreateProcessor extends modProcessor {
/** @var modMediaSource|modFileMediaSource $source */
public $source;
public function checkPermissions() {
return $this->modx->hasPermission('file_create');
}
public function getLanguageTopics() {
return array('file');
}
public function process() {
/* get base paths and sanitize incoming paths */
$directory = rawurldecode($this->getProperty('directory',''));
$directory = ltrim(strip_tags(str_replace(array('../','./'),'',$directory)),'/');
$name = $this->getProperty('name');
$name = ltrim(strip_tags(str_replace(array('../','./'),'',$name)),'/');
$loaded = $this->getSource();
if (!($this->source instanceof modMediaSource)) {
return $loaded;
}
if (!$this->source->checkPolicy('create')) {
return $this->failure($this->modx->lexicon('permission_denied'));
}
$path = $this->source->createObject($directory,$name,$this->getProperty('content'));
if (empty($path)) {
$msg = '';
$errors = $this->source->getErrors();
foreach ($errors as $k => $msg) {
$this->addFieldError($k,$msg);
}
return $this->failure($msg);
}
return $this->success('',array(
'file' => $directory.ltrim($name,'/'),
));
}
/**
* @return boolean|string
*/
public function getSource() {
$source = $this->getProperty('source',1);
/** @var modMediaSource $source */
$this->modx->loadClass('sources.modMediaSource');
$this->source = modMediaSource::getDefaultSource($this->modx,$source);
if (!$this->source->getWorkingContext()) {
return $this->modx->lexicon('permission_denied');
}
$this->source->setRequestProperties($this->getProperties());
return $this->source->initialize();
}
}
return 'modBrowserFileCreateProcessor'; | gpl-2.0 |
dmlloyd/openjdk-modules | hotspot/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements/src/org/graalvm/compiler/replacements/nodes/DirectObjectStoreNode.java | 6165 | /*
* Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* 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 org.graalvm.compiler.replacements.nodes;
import static org.graalvm.compiler.nodeinfo.NodeCycles.CYCLES_3;
import static org.graalvm.compiler.nodeinfo.NodeSize.SIZE_1;
import org.graalvm.compiler.core.common.LocationIdentity;
import org.graalvm.compiler.core.common.type.StampFactory;
import org.graalvm.compiler.graph.NodeClass;
import org.graalvm.compiler.nodeinfo.NodeInfo;
import org.graalvm.compiler.nodes.ConstantNode;
import org.graalvm.compiler.nodes.FixedWithNextNode;
import org.graalvm.compiler.nodes.StateSplit;
import org.graalvm.compiler.nodes.ValueNode;
import org.graalvm.compiler.nodes.calc.AddNode;
import org.graalvm.compiler.nodes.extended.JavaWriteNode;
import org.graalvm.compiler.nodes.extended.UnsafeStoreNode;
import org.graalvm.compiler.nodes.memory.HeapAccess.BarrierType;
import org.graalvm.compiler.nodes.memory.address.AddressNode;
import org.graalvm.compiler.nodes.memory.address.OffsetAddressNode;
import org.graalvm.compiler.nodes.spi.Lowerable;
import org.graalvm.compiler.nodes.spi.LoweringTool;
import jdk.vm.ci.meta.JavaKind;
/**
* A special purpose store node that differs from {@link UnsafeStoreNode} in that it is not a
* {@link StateSplit} and does not include a write barrier. Note that contrary to the sound of the
* name this node can be used for storing any kind.
*/
@NodeInfo(cycles = CYCLES_3, size = SIZE_1)
public final class DirectObjectStoreNode extends FixedWithNextNode implements Lowerable {
public static final NodeClass<DirectObjectStoreNode> TYPE = NodeClass.create(DirectObjectStoreNode.class);
@Input ValueNode object;
@Input ValueNode value;
@Input ValueNode offset;
protected final int displacement;
protected final LocationIdentity locationIdentity;
protected final JavaKind storeKind;
public DirectObjectStoreNode(ValueNode object, int displacement, ValueNode offset, ValueNode value, LocationIdentity locationIdentity, JavaKind storeKind) {
super(TYPE, StampFactory.forVoid());
this.object = object;
this.value = value;
this.offset = offset;
this.displacement = displacement;
this.locationIdentity = locationIdentity;
this.storeKind = storeKind;
}
@NodeIntrinsic
public static native void storeObject(Object obj, @ConstantNodeParameter int displacement, long offset, Object value, @ConstantNodeParameter LocationIdentity locationIdentity,
@ConstantNodeParameter JavaKind storeKind);
@NodeIntrinsic
public static native void storeBoolean(Object obj, @ConstantNodeParameter int displacement, long offset, boolean value, @ConstantNodeParameter LocationIdentity locationIdenity,
@ConstantNodeParameter JavaKind storeKind);
@NodeIntrinsic
public static native void storeByte(Object obj, @ConstantNodeParameter int displacement, long offset, byte value, @ConstantNodeParameter LocationIdentity locationIdenity,
@ConstantNodeParameter JavaKind storeKind);
@NodeIntrinsic
public static native void storeChar(Object obj, @ConstantNodeParameter int displacement, long offset, char value, @ConstantNodeParameter LocationIdentity locationIdenity,
@ConstantNodeParameter JavaKind storeKind);
@NodeIntrinsic
public static native void storeShort(Object obj, @ConstantNodeParameter int displacement, long offset, short value, @ConstantNodeParameter LocationIdentity locationIdenity,
@ConstantNodeParameter JavaKind storeKind);
@NodeIntrinsic
public static native void storeInt(Object obj, @ConstantNodeParameter int displacement, long offset, int value, @ConstantNodeParameter LocationIdentity locationIdenity,
@ConstantNodeParameter JavaKind storeKind);
@NodeIntrinsic
public static native void storeLong(Object obj, @ConstantNodeParameter int displacement, long offset, long value, @ConstantNodeParameter LocationIdentity locationIdenity,
@ConstantNodeParameter JavaKind storeKind);
@NodeIntrinsic
public static native void storeFloat(Object obj, @ConstantNodeParameter int displacement, long offset, float value, @ConstantNodeParameter LocationIdentity locationIdenity,
@ConstantNodeParameter JavaKind storeKind);
@NodeIntrinsic
public static native void storeDouble(Object obj, @ConstantNodeParameter int displacement, long offset, double value, @ConstantNodeParameter LocationIdentity locationIdenity,
@ConstantNodeParameter JavaKind storeKind);
@Override
public void lower(LoweringTool tool) {
ValueNode off = graph().unique(new AddNode(offset, ConstantNode.forIntegerStamp(offset.stamp(), displacement, graph())));
AddressNode address = graph().unique(new OffsetAddressNode(object, off));
JavaWriteNode write = graph().add(new JavaWriteNode(storeKind, address, locationIdentity, value, BarrierType.NONE, storeKind == JavaKind.Object, false));
graph().replaceFixedWithFixed(this, write);
tool.getLowerer().lower(write, tool);
}
}
| gpl-2.0 |
pulibrary/recap | core/modules/config/tests/src/Functional/LanguageNegotiationFormOverrideTest.php | 1995 | <?php
namespace Drupal\Tests\config\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Tests language-negotiation overrides are not on language-negotiation form.
*
* @group config
* @see \Drupal\Core\Form\ConfigFormBase
*/
class LanguageNegotiationFormOverrideTest extends BrowserTestBase {
protected static $modules = ['language', 'locale', 'locale_test'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests that overrides do not affect language-negotiation form values.
*/
public function testFormWithOverride() {
$this->drupalLogin($this->rootUser);
$overridden_value_en = 'whatever';
$overridden_value_es = 'loquesea';
// Set up an override.
$settings['config']['language.negotiation']['url']['prefixes'] = (object) [
'value' => ['en' => $overridden_value_en, 'es' => $overridden_value_es],
'required' => TRUE,
];
$this->writeSettings($settings);
// Add predefined language.
$edit = [
'predefined_langcode' => 'es',
];
$this->drupalGet('admin/config/regional/language/add');
$this->submitForm($edit, 'Add language');
// Overridden string for language-negotiation should not exist in the form.
$this->drupalGet('admin/config/regional/language/detection/url');
// The language-negotiation form should be found.
$this->assertSession()->pageTextContains('Path prefix configuration');
// The English override should not be found.
$this->assertSession()->fieldValueNotEquals('prefix[en]', $overridden_value_en);
// Now check the Spanish version of the page for the same thing.
$this->drupalGet($overridden_value_es . '/admin/config/regional/language/detection/url');
// The language-negotiation form should be found.
$this->assertSession()->pageTextContains('Path prefix configuration');
// The Spanish override should not be found.
$this->assertSession()->fieldValueNotEquals('prefix[es]', $overridden_value_es);
}
}
| gpl-2.0 |
badp/ganeti | lib/confd/client.py | 21941 | #
#
# Copyright (C) 2009, 2010, 2012 Google Inc.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
"""Ganeti confd client
Clients can use the confd client library to send requests to a group of master
candidates running confd. The expected usage is through the asyncore framework,
by sending queries, and asynchronously receiving replies through a callback.
This way the client library doesn't ever need to "wait" on a particular answer,
and can proceed even if some udp packets are lost. It's up to the user to
reschedule queries if they haven't received responses and they need them.
Example usage::
client = ConfdClient(...) # includes callback specification
req = confd_client.ConfdClientRequest(type=constants.CONFD_REQ_PING)
client.SendRequest(req)
# then make sure your client calls asyncore.loop() or daemon.Mainloop.Run()
# ... wait ...
# And your callback will be called by asyncore, when your query gets a
# response, or when it expires.
You can use the provided ConfdFilterCallback to act as a filter, only passing
"newer" answer to your callback, and filtering out outdated ones, or ones
confirming what you already got.
"""
# pylint: disable=E0203
# E0203: Access to member %r before its definition, since we use
# objects.py which doesn't explicitly initialise its members
import time
import random
from ganeti import utils
from ganeti import constants
from ganeti import objects
from ganeti import serializer
from ganeti import daemon # contains AsyncUDPSocket
from ganeti import errors
from ganeti import confd
from ganeti import ssconf
from ganeti import compat
from ganeti import netutils
from ganeti import pathutils
class ConfdAsyncUDPClient(daemon.AsyncUDPSocket):
"""Confd udp asyncore client
This is kept separate from the main ConfdClient to make sure it's easy to
implement a non-asyncore based client library.
"""
def __init__(self, client, family):
"""Constructor for ConfdAsyncUDPClient
@type client: L{ConfdClient}
@param client: client library, to pass the datagrams to
"""
daemon.AsyncUDPSocket.__init__(self, family)
self.client = client
# this method is overriding a daemon.AsyncUDPSocket method
def handle_datagram(self, payload, ip, port):
self.client.HandleResponse(payload, ip, port)
class _Request(object):
"""Request status structure.
@ivar request: the request data
@ivar args: any extra arguments for the callback
@ivar expiry: the expiry timestamp of the request
@ivar sent: the set of contacted peers
@ivar rcvd: the set of peers who replied
"""
def __init__(self, request, args, expiry, sent):
self.request = request
self.args = args
self.expiry = expiry
self.sent = frozenset(sent)
self.rcvd = set()
class ConfdClient:
"""Send queries to confd, and get back answers.
Since the confd model works by querying multiple master candidates, and
getting back answers, this is an asynchronous library. It can either work
through asyncore or with your own handling.
@type _requests: dict
@ivar _requests: dictionary indexes by salt, which contains data
about the outstanding requests; the values are objects of type
L{_Request}
"""
def __init__(self, hmac_key, peers, callback, port=None, logger=None):
"""Constructor for ConfdClient
@type hmac_key: string
@param hmac_key: hmac key to talk to confd
@type peers: list
@param peers: list of peer nodes
@type callback: f(L{ConfdUpcallPayload})
@param callback: function to call when getting answers
@type port: integer
@param port: confd port (default: use GetDaemonPort)
@type logger: logging.Logger
@param logger: optional logger for internal conditions
"""
if not callable(callback):
raise errors.ProgrammerError("callback must be callable")
self.UpdatePeerList(peers)
self._SetPeersAddressFamily()
self._hmac_key = hmac_key
self._socket = ConfdAsyncUDPClient(self, self._family)
self._callback = callback
self._confd_port = port
self._logger = logger
self._requests = {}
if self._confd_port is None:
self._confd_port = netutils.GetDaemonPort(constants.CONFD)
def UpdatePeerList(self, peers):
"""Update the list of peers
@type peers: list
@param peers: list of peer nodes
"""
# we are actually called from init, so:
# pylint: disable=W0201
if not isinstance(peers, list):
raise errors.ProgrammerError("peers must be a list")
# make a copy of peers, since we're going to shuffle the list, later
self._peers = list(peers)
def _PackRequest(self, request, now=None):
"""Prepare a request to be sent on the wire.
This function puts a proper salt in a confd request, puts the proper salt,
and adds the correct magic number.
"""
if now is None:
now = time.time()
tstamp = "%d" % now
req = serializer.DumpSignedJson(request.ToDict(), self._hmac_key, tstamp)
return confd.PackMagic(req)
def _UnpackReply(self, payload):
in_payload = confd.UnpackMagic(payload)
(dict_answer, salt) = serializer.LoadSignedJson(in_payload, self._hmac_key)
answer = objects.ConfdReply.FromDict(dict_answer)
return answer, salt
def ExpireRequests(self):
"""Delete all the expired requests.
"""
now = time.time()
for rsalt, rq in self._requests.items():
if now >= rq.expiry:
del self._requests[rsalt]
client_reply = ConfdUpcallPayload(salt=rsalt,
type=UPCALL_EXPIRE,
orig_request=rq.request,
extra_args=rq.args,
client=self,
)
self._callback(client_reply)
def SendRequest(self, request, args=None, coverage=0, async=True):
"""Send a confd request to some MCs
@type request: L{objects.ConfdRequest}
@param request: the request to send
@type args: tuple
@param args: additional callback arguments
@type coverage: integer
@param coverage: number of remote nodes to contact; if default
(0), it will use a reasonable default
(L{ganeti.constants.CONFD_DEFAULT_REQ_COVERAGE}), if -1 is
passed, it will use the maximum number of peers, otherwise the
number passed in will be used
@type async: boolean
@param async: handle the write asynchronously
"""
if coverage == 0:
coverage = min(len(self._peers), constants.CONFD_DEFAULT_REQ_COVERAGE)
elif coverage == -1:
coverage = len(self._peers)
if coverage > len(self._peers):
raise errors.ConfdClientError("Not enough MCs known to provide the"
" desired coverage")
if not request.rsalt:
raise errors.ConfdClientError("Missing request rsalt")
self.ExpireRequests()
if request.rsalt in self._requests:
raise errors.ConfdClientError("Duplicate request rsalt")
if request.type not in constants.CONFD_REQS:
raise errors.ConfdClientError("Invalid request type")
random.shuffle(self._peers)
targets = self._peers[:coverage]
now = time.time()
payload = self._PackRequest(request, now=now)
for target in targets:
try:
self._socket.enqueue_send(target, self._confd_port, payload)
except errors.UdpDataSizeError:
raise errors.ConfdClientError("Request too big")
expire_time = now + constants.CONFD_CLIENT_EXPIRE_TIMEOUT
self._requests[request.rsalt] = _Request(request, args, expire_time,
targets)
if not async:
self.FlushSendQueue()
def HandleResponse(self, payload, ip, port):
"""Asynchronous handler for a confd reply
Call the relevant callback associated to the current request.
"""
try:
try:
answer, salt = self._UnpackReply(payload)
except (errors.SignatureError, errors.ConfdMagicError), err:
if self._logger:
self._logger.debug("Discarding broken package: %s" % err)
return
try:
rq = self._requests[salt]
except KeyError:
if self._logger:
self._logger.debug("Discarding unknown (expired?) reply: %s" % err)
return
rq.rcvd.add(ip)
client_reply = ConfdUpcallPayload(salt=salt,
type=UPCALL_REPLY,
server_reply=answer,
orig_request=rq.request,
server_ip=ip,
server_port=port,
extra_args=rq.args,
client=self,
)
self._callback(client_reply)
finally:
self.ExpireRequests()
def FlushSendQueue(self):
"""Send out all pending requests.
Can be used for synchronous client use.
"""
while self._socket.writable():
self._socket.handle_write()
def ReceiveReply(self, timeout=1):
"""Receive one reply.
@type timeout: float
@param timeout: how long to wait for the reply
@rtype: boolean
@return: True if some data has been handled, False otherwise
"""
return self._socket.process_next_packet(timeout=timeout)
@staticmethod
def _NeededReplies(peer_cnt):
"""Compute the minimum safe number of replies for a query.
The algorithm is designed to work well for both small and big
number of peers:
- for less than three, we require all responses
- for less than five, we allow one miss
- otherwise, half the number plus one
This guarantees that we progress monotonically: 1->1, 2->2, 3->2,
4->2, 5->3, 6->3, 7->4, etc.
@type peer_cnt: int
@param peer_cnt: the number of peers contacted
@rtype: int
@return: the number of replies which should give a safe coverage
"""
if peer_cnt < 3:
return peer_cnt
elif peer_cnt < 5:
return peer_cnt - 1
else:
return int(peer_cnt / 2) + 1
def WaitForReply(self, salt, timeout=constants.CONFD_CLIENT_EXPIRE_TIMEOUT):
"""Wait for replies to a given request.
This method will wait until either the timeout expires or a
minimum number (computed using L{_NeededReplies}) of replies are
received for the given salt. It is useful when doing synchronous
calls to this library.
@param salt: the salt of the request we want responses for
@param timeout: the maximum timeout (should be less or equal to
L{ganeti.constants.CONFD_CLIENT_EXPIRE_TIMEOUT}
@rtype: tuple
@return: a tuple of (timed_out, sent_cnt, recv_cnt); if the
request is unknown, timed_out will be true and the counters
will be zero
"""
def _CheckResponse():
if salt not in self._requests:
# expired?
if self._logger:
self._logger.debug("Discarding unknown/expired request: %s" % salt)
return MISSING
rq = self._requests[salt]
if len(rq.rcvd) >= expected:
# already got all replies
return (False, len(rq.sent), len(rq.rcvd))
# else wait, using default timeout
self.ReceiveReply()
raise utils.RetryAgain()
MISSING = (True, 0, 0)
if salt not in self._requests:
return MISSING
# extend the expire time with the current timeout, so that we
# don't get the request expired from under us
rq = self._requests[salt]
rq.expiry += timeout
sent = len(rq.sent)
expected = self._NeededReplies(sent)
try:
return utils.Retry(_CheckResponse, 0, timeout)
except utils.RetryTimeout:
if salt in self._requests:
rq = self._requests[salt]
return (True, len(rq.sent), len(rq.rcvd))
else:
return MISSING
def _SetPeersAddressFamily(self):
if not self._peers:
raise errors.ConfdClientError("Peer list empty")
try:
peer = self._peers[0]
self._family = netutils.IPAddress.GetAddressFamily(peer)
for peer in self._peers[1:]:
if netutils.IPAddress.GetAddressFamily(peer) != self._family:
raise errors.ConfdClientError("Peers must be of same address family")
except errors.IPAddressError:
raise errors.ConfdClientError("Peer address %s invalid" % peer)
# UPCALL_REPLY: server reply upcall
# has all ConfdUpcallPayload fields populated
UPCALL_REPLY = 1
# UPCALL_EXPIRE: internal library request expire
# has only salt, type, orig_request and extra_args
UPCALL_EXPIRE = 2
CONFD_UPCALL_TYPES = compat.UniqueFrozenset([
UPCALL_REPLY,
UPCALL_EXPIRE,
])
class ConfdUpcallPayload(objects.ConfigObject):
"""Callback argument for confd replies
@type salt: string
@ivar salt: salt associated with the query
@type type: one of confd.client.CONFD_UPCALL_TYPES
@ivar type: upcall type (server reply, expired request, ...)
@type orig_request: L{objects.ConfdRequest}
@ivar orig_request: original request
@type server_reply: L{objects.ConfdReply}
@ivar server_reply: server reply
@type server_ip: string
@ivar server_ip: answering server ip address
@type server_port: int
@ivar server_port: answering server port
@type extra_args: any
@ivar extra_args: 'args' argument of the SendRequest function
@type client: L{ConfdClient}
@ivar client: current confd client instance
"""
__slots__ = [
"salt",
"type",
"orig_request",
"server_reply",
"server_ip",
"server_port",
"extra_args",
"client",
]
class ConfdClientRequest(objects.ConfdRequest):
"""This is the client-side version of ConfdRequest.
This version of the class helps creating requests, on the client side, by
filling in some default values.
"""
def __init__(self, **kwargs):
objects.ConfdRequest.__init__(self, **kwargs)
if not self.rsalt:
self.rsalt = utils.NewUUID()
if not self.protocol:
self.protocol = constants.CONFD_PROTOCOL_VERSION
if self.type not in constants.CONFD_REQS:
raise errors.ConfdClientError("Invalid request type")
class ConfdFilterCallback:
"""Callback that calls another callback, but filters duplicate results.
@ivar consistent: a dictionary indexed by salt; for each salt, if
all responses ware identical, this will be True; this is the
expected state on a healthy cluster; on inconsistent or
partitioned clusters, this might be False, if we see answers
with the same serial but different contents
"""
def __init__(self, callback, logger=None):
"""Constructor for ConfdFilterCallback
@type callback: f(L{ConfdUpcallPayload})
@param callback: function to call when getting answers
@type logger: logging.Logger
@param logger: optional logger for internal conditions
"""
if not callable(callback):
raise errors.ProgrammerError("callback must be callable")
self._callback = callback
self._logger = logger
# answers contains a dict of salt -> answer
self._answers = {}
self.consistent = {}
def _LogFilter(self, salt, new_reply, old_reply):
if not self._logger:
return
if new_reply.serial > old_reply.serial:
self._logger.debug("Filtering confirming answer, with newer"
" serial for query %s" % salt)
elif new_reply.serial == old_reply.serial:
if new_reply.answer != old_reply.answer:
self._logger.warning("Got incoherent answers for query %s"
" (serial: %s)" % (salt, new_reply.serial))
else:
self._logger.debug("Filtering confirming answer, with same"
" serial for query %s" % salt)
else:
self._logger.debug("Filtering outdated answer for query %s"
" serial: (%d < %d)" % (salt, old_reply.serial,
new_reply.serial))
def _HandleExpire(self, up):
# if we have no answer we have received none, before the expiration.
if up.salt in self._answers:
del self._answers[up.salt]
if up.salt in self.consistent:
del self.consistent[up.salt]
def _HandleReply(self, up):
"""Handle a single confd reply, and decide whether to filter it.
@rtype: boolean
@return: True if the reply should be filtered, False if it should be passed
on to the up-callback
"""
filter_upcall = False
salt = up.salt
if salt not in self.consistent:
self.consistent[salt] = True
if salt not in self._answers:
# first answer for a query (don't filter, and record)
self._answers[salt] = up.server_reply
elif up.server_reply.serial > self._answers[salt].serial:
# newer answer (record, and compare contents)
old_answer = self._answers[salt]
self._answers[salt] = up.server_reply
if up.server_reply.answer == old_answer.answer:
# same content (filter) (version upgrade was unrelated)
filter_upcall = True
self._LogFilter(salt, up.server_reply, old_answer)
# else: different content, pass up a second answer
else:
# older or same-version answer (duplicate or outdated, filter)
if (up.server_reply.serial == self._answers[salt].serial and
up.server_reply.answer != self._answers[salt].answer):
self.consistent[salt] = False
filter_upcall = True
self._LogFilter(salt, up.server_reply, self._answers[salt])
return filter_upcall
def __call__(self, up):
"""Filtering callback
@type up: L{ConfdUpcallPayload}
@param up: upper callback
"""
filter_upcall = False
if up.type == UPCALL_REPLY:
filter_upcall = self._HandleReply(up)
elif up.type == UPCALL_EXPIRE:
self._HandleExpire(up)
if not filter_upcall:
self._callback(up)
class ConfdCountingCallback:
"""Callback that calls another callback, and counts the answers
"""
def __init__(self, callback, logger=None):
"""Constructor for ConfdCountingCallback
@type callback: f(L{ConfdUpcallPayload})
@param callback: function to call when getting answers
@type logger: logging.Logger
@param logger: optional logger for internal conditions
"""
if not callable(callback):
raise errors.ProgrammerError("callback must be callable")
self._callback = callback
self._logger = logger
# answers contains a dict of salt -> count
self._answers = {}
def RegisterQuery(self, salt):
if salt in self._answers:
raise errors.ProgrammerError("query already registered")
self._answers[salt] = 0
def AllAnswered(self):
"""Have all the registered queries received at least an answer?
"""
return compat.all(self._answers.values())
def _HandleExpire(self, up):
# if we have no answer we have received none, before the expiration.
if up.salt in self._answers:
del self._answers[up.salt]
def _HandleReply(self, up):
"""Handle a single confd reply, and decide whether to filter it.
@rtype: boolean
@return: True if the reply should be filtered, False if it should be passed
on to the up-callback
"""
if up.salt in self._answers:
self._answers[up.salt] += 1
def __call__(self, up):
"""Filtering callback
@type up: L{ConfdUpcallPayload}
@param up: upper callback
"""
if up.type == UPCALL_REPLY:
self._HandleReply(up)
elif up.type == UPCALL_EXPIRE:
self._HandleExpire(up)
self._callback(up)
class StoreResultCallback:
"""Callback that simply stores the most recent answer.
@ivar _answers: dict of salt to (have_answer, reply)
"""
_NO_KEY = (False, None)
def __init__(self):
"""Constructor for StoreResultCallback
"""
# answers contains a dict of salt -> best result
self._answers = {}
def GetResponse(self, salt):
"""Return the best match for a salt
"""
return self._answers.get(salt, self._NO_KEY)
def _HandleExpire(self, up):
"""Expiration handler.
"""
if up.salt in self._answers and self._answers[up.salt] == self._NO_KEY:
del self._answers[up.salt]
def _HandleReply(self, up):
"""Handle a single confd reply, and decide whether to filter it.
"""
self._answers[up.salt] = (True, up)
def __call__(self, up):
"""Filtering callback
@type up: L{ConfdUpcallPayload}
@param up: upper callback
"""
if up.type == UPCALL_REPLY:
self._HandleReply(up)
elif up.type == UPCALL_EXPIRE:
self._HandleExpire(up)
def GetConfdClient(callback):
"""Return a client configured using the given callback.
This is handy to abstract the MC list and HMAC key reading.
@attention: This should only be called on nodes which are part of a
cluster, since it depends on a valid (ganeti) data directory;
for code running outside of a cluster, you need to create the
client manually
"""
ss = ssconf.SimpleStore()
mc_file = ss.KeyToFilename(constants.SS_MASTER_CANDIDATES_IPS)
mc_list = utils.ReadFile(mc_file).splitlines()
hmac_key = utils.ReadFile(pathutils.CONFD_HMAC_KEY)
return ConfdClient(hmac_key, mc_list, callback)
| gpl-2.0 |
md-5/jdk10 | test/hotspot/jtreg/vmTestbase/gc/ArrayJuggle/Juggle10/TestDescription.java | 1416 | /*
* Copyright (c) 2017, 2018, 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
* @key stress gc
*
* @summary converted from VM Testbase gc/ArrayJuggle/Juggle10.
* VM Testbase keywords: [gc, stress, stressopt, nonconcurrent]
*
* @library /vmTestbase
* /test/lib
* @run driver jdk.test.lib.FileInstaller . .
* @run main/othervm -Xlog:gc=debug:gc.log gc.ArrayJuggle.Juggle01.Juggle01 -gp charArr -ms low
*/
| gpl-2.0 |
nmcgill/UOReturns | Scripts/Items/Skill Items/Fishing/Misc/SOS.cs | 11028 | using System;
using Server.Network;
using Server.Gumps;
namespace Server.Items
{
[Flipable( 0x14ED, 0x14EE )]
public class SOS : Item
{
public override int LabelNumber
{
get
{
if ( IsAncient )
return 1063450; // an ancient SOS
return 1041081; // a waterstained SOS
}
}
private int m_Level;
private Map m_TargetMap;
private Point3D m_TargetLocation;
private int m_MessageIndex;
[CommandProperty( AccessLevel.GameMaster )]
public bool IsAncient
{
get{ return ( m_Level >= 4 ); }
}
[CommandProperty( AccessLevel.GameMaster )]
public int Level
{
get{ return m_Level; }
set
{
m_Level = Math.Max( 1, Math.Min( value, 4 ) );
UpdateHue();
InvalidateProperties();
}
}
[CommandProperty( AccessLevel.GameMaster )]
public Map TargetMap
{
get{ return m_TargetMap; }
set{ m_TargetMap = value; }
}
[CommandProperty( AccessLevel.GameMaster )]
public Point3D TargetLocation
{
get{ return m_TargetLocation; }
set{ m_TargetLocation = value; }
}
[CommandProperty( AccessLevel.GameMaster )]
public int MessageIndex
{
get{ return m_MessageIndex; }
set{ m_MessageIndex = value; }
}
public void UpdateHue()
{
if ( IsAncient )
Hue = 0x481;
else
Hue = 0;
}
[Constructable]
public SOS() : this( Map.Trammel )
{
}
[Constructable]
public SOS( Map map ) : this( map, MessageInABottle.GetRandomLevel() )
{
}
[Constructable]
public SOS( Map map, int level ) : base( 0x14EE )
{
Weight = 1.0;
m_Level = level;
m_MessageIndex = Utility.Random( MessageEntry.Entries.Length );
m_TargetMap = map;
m_TargetLocation = FindLocation( m_TargetMap );
UpdateHue();
}
public SOS( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 4 ); // version
writer.Write( m_Level );
writer.Write( m_TargetMap );
writer.Write( m_TargetLocation );
writer.Write( m_MessageIndex );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch ( version )
{
case 4:
case 3:
case 2:
{
m_Level = reader.ReadInt();
goto case 1;
}
case 1:
{
m_TargetMap = reader.ReadMap();
m_TargetLocation = reader.ReadPoint3D();
m_MessageIndex = reader.ReadInt();
break;
}
case 0:
{
m_TargetMap = this.Map;
if ( m_TargetMap == null || m_TargetMap == Map.Internal )
m_TargetMap = Map.Trammel;
m_TargetLocation = FindLocation( m_TargetMap );
m_MessageIndex = Utility.Random( MessageEntry.Entries.Length );
break;
}
}
if ( version < 2 )
m_Level = MessageInABottle.GetRandomLevel();
if ( version < 3 )
UpdateHue();
if( version < 4 && m_TargetMap == Map.Tokuno )
m_TargetMap = Map.Trammel;
}
public override void OnDoubleClick( Mobile from )
{
if ( IsChildOf( from.Backpack ) )
{
MessageEntry entry;
if ( m_MessageIndex >= 0 && m_MessageIndex < MessageEntry.Entries.Length )
entry = MessageEntry.Entries[m_MessageIndex];
else
entry = MessageEntry.Entries[m_MessageIndex = Utility.Random( MessageEntry.Entries.Length )];
//from.CloseGump( typeof( MessageGump ) );
from.SendGump( new MessageGump( entry, m_TargetMap, m_TargetLocation ) );
}
else
{
from.SendLocalizedMessage( 1042001 ); // That must be in your pack for you to use it.
}
}
private static int[] m_WaterTiles = new int[]
{
0x00A8, 0x00AB,
0x0136, 0x0137
};
private static Rectangle2D[] m_BritRegions = new Rectangle2D[]{ new Rectangle2D( 0, 0, 5120, 4096 ) };
private static Rectangle2D[] m_IlshRegions = new Rectangle2D[]{ new Rectangle2D( 1472, 272, 304, 240 ), new Rectangle2D( 1240, 1000, 312, 160 ) };
private static Rectangle2D[] m_MalasRegions = new Rectangle2D[]{ new Rectangle2D( 1376, 1520, 464, 280 ) };
public static Point3D FindLocation( Map map )
{
if ( map == null || map == Map.Internal )
return Point3D.Zero;
Rectangle2D[] regions;
if ( map == Map.Felucca || map == Map.Trammel )
regions = m_BritRegions;
else if ( map == Map.Ilshenar )
regions = m_IlshRegions;
else if ( map == Map.Malas )
regions = m_MalasRegions;
else
regions = new Rectangle2D[]{ new Rectangle2D( 0, 0, map.Width, map.Height ) };
if ( regions.Length == 0 )
return Point3D.Zero;
for ( int i = 0; i < 50; ++i )
{
Rectangle2D reg = regions[Utility.Random( regions.Length )];
int x = Utility.Random( reg.X, reg.Width );
int y = Utility.Random( reg.Y, reg.Height );
if ( !ValidateDeepWater( map, x, y ) )
continue;
bool valid = true;
for ( int j = 1, offset = 5; valid && j <= 5; ++j, offset += 5 )
{
if ( !ValidateDeepWater( map, x + offset, y + offset ) )
valid = false;
else if ( !ValidateDeepWater( map, x + offset, y - offset ) )
valid = false;
else if ( !ValidateDeepWater( map, x - offset, y + offset ) )
valid = false;
else if ( !ValidateDeepWater( map, x - offset, y - offset ) )
valid = false;
}
if ( valid )
return new Point3D( x, y, 0 );
}
return Point3D.Zero;
}
private static bool ValidateDeepWater( Map map, int x, int y )
{
int tileID = map.Tiles.GetLandTile( x, y ).ID;
bool water = false;
for ( int i = 0; !water && i < m_WaterTiles.Length; i += 2 )
water = ( tileID >= m_WaterTiles[i] && tileID <= m_WaterTiles[i + 1] );
return water;
}
#if false
private class MessageGump : Gump
{
public MessageGump( MessageEntry entry, Map map, Point3D loc ) : base( (640 - entry.Width) / 2, (480 - entry.Height) / 2 )
{
int xLong = 0, yLat = 0;
int xMins = 0, yMins = 0;
bool xEast = false, ySouth = false;
string fmt;
if ( Sextant.Format( loc, map, ref xLong, ref yLat, ref xMins, ref yMins, ref xEast, ref ySouth ) )
fmt = String.Format( "{0}°{1}'{2},{3}°{4}'{5}", yLat, yMins, ySouth ? "S" : "N", xLong, xMins, xEast ? "E" : "W" );
else
fmt = "?????";
AddPage( 0 );
AddBackground( 0, 0, entry.Width, entry.Height, 2520 );
AddHtml( 38, 38, entry.Width - 83, entry.Height - 86, String.Format( entry.Message, fmt ), false, false );
}
}
#else
private class MessageGump : Gump
{
public MessageGump( MessageEntry entry, Map map, Point3D loc ) : base( 150, 50 )
{
int xLong = 0, yLat = 0;
int xMins = 0, yMins = 0;
bool xEast = false, ySouth = false;
string fmt;
if ( Sextant.Format( loc, map, ref xLong, ref yLat, ref xMins, ref yMins, ref xEast, ref ySouth ) )
fmt = String.Format( "{0}°{1}'{2},{3}°{4}'{5}", yLat, yMins, ySouth ? "S" : "N", xLong, xMins, xEast ? "E" : "W" );
else
fmt = "?????";
AddPage( 0 );
AddBackground( 0, 40, 350, 300, 2520 );
AddHtmlLocalized( 30, 80, 285, 160, 1018326, true, true ); /* This is a message hastily scribbled by a passenger aboard a sinking ship.
* While it is probably too late to save the passengers and crew,
* perhaps some treasure went down with the ship!
* The message gives the ship's last known sextant co-ordinates.
*/
AddHtml( 35, 240, 230, 20, fmt, false, false );
AddButton( 35, 265, 4005, 4007, 0, GumpButtonType.Reply, 0 );
AddHtmlLocalized( 70, 265, 100, 20, 1011036, false, false ); // OKAY
}
}
#endif
private class MessageEntry
{
private int m_Width, m_Height;
private string m_Message;
public int Width{ get{ return m_Width; } }
public int Height{ get{ return m_Height; } }
public string Message{ get{ return m_Message; } }
public MessageEntry( int width, int height, string message )
{
m_Width = width;
m_Height = height;
m_Message = message;
}
private static MessageEntry[] m_Entries = new MessageEntry[]
{
new MessageEntry( 280, 180, "...Ar! {0} and a fair wind! No chance... storms, though--ar! Is that a sea serp...<br><br>uh oh." ),
new MessageEntry( 280, 215, "...been inside this whale for three days now. I've run out of food I can pick out of his teeth. I took a sextant reading through the blowhole: {0}. I'll never see my treasure again..." ),
new MessageEntry( 280, 285, "...grand adventure! Captain Quacklebush had me swab down the decks daily...<br> ...pirates came, I was in the rigging practicing with my sextant. {0} if I am not mistaken...<br> ....scuttled the ship, and our precious cargo went with her and the screaming pirates, down to the bottom of the sea..." ),
new MessageEntry( 280, 180, "Help! Ship going dow...n heavy storms...precious cargo...st reach dest...current coordinates {0}...ve any survivors... ease!" ),
new MessageEntry( 280, 215, "...know that the wreck is near {0} but have not found it. Could the message passed down in my family for generations be wrong? No... I swear on the soul of my grandfather, I will find..." ),
new MessageEntry( 280, 195, "...never expected an iceberg...silly woman on bow crushed instantly...send help to {0}...ey'll never forget the tragedy of the sinking of the Miniscule..." ),
new MessageEntry( 280, 265, "...nobody knew I was a girl. They just assumed I was another sailor...then we met the undine. {0}. It was demanded sacrifice...I was youngset, they figured...<br> ...grabbed the captain's treasure, screamed, 'It'll go down with me!'<br> ...they took me up on it." ),
new MessageEntry( 280, 230, "...so I threw the treasure overboard, before the curse could get me too. But I was too late. Now I am doomed to wander these seas, a ghost forever. Join me: seek ye at {0} if thou wishest my company..." ),
new MessageEntry( 280, 285, "...then the ship exploded. A dragon swooped by. The slime swallowed Bertie whole--he screamed, it was amazing. The sky glowed orange. A sextant reading put us at {0}. Norma was chattering about sailing over the edge of the world. I looked at my hands and saw through them..." ),
new MessageEntry( 280, 285, "...trapped on a deserted island, with a magic fountain supplying wood, fresh water springs, gorgeous scenery, and my lovely young wife. I know the ship with all our life's earnings sank at {0} but I don't know what our coordinates are... someone has GOT to rescue me before Sunday's finals game or I'll go mad..." ),
new MessageEntry( 280, 160, "WANTED: divers exp...d in shipwre...overy. Must have own vess...pply at {0}<br>...good benefits, flexible hours..." ),
new MessageEntry( 280, 250, "...was a cad and a boor, no matter what momma s...rew him overboard! Oh, Anna, 'twas so exciting!<br> Unfort...y he grabbe...est, and all his riches went with him!<br> ...sked the captain, and he says we're at {0}<br>...so maybe..." )
};
public static MessageEntry[] Entries
{
get{ return m_Entries; }
}
}
}
} | gpl-2.0 |
chippyjacob123/newzbuzz | modules/contrib/tvi/tests/src/Functional/TaxonomyViewsIntegratorTest.php | 4158 | <?php
namespace Drupal\Tests\tvi\Functional;
use Drupal\Tests\tvi\Functional\TaxonomyViewsIntegratorTestBase;
/**
* Tests TaxonomyViewsIntegrator and various term configurations.
*
* @group tvi
*/
class TaxonomyViewsIntegratorTest extends TaxonomyViewsIntegratorTestBase {
public function setUp() {
parent::setUp();
$permissions = [
'access content',
'administer site configuration',
'administer views',
'administer nodes',
'administer taxonomy',
'access administration pages',
'define view for vocabulary ' . $this->vocabulary1->id(),
'define view for terms in ' . $this->vocabulary1->id(),
'define view for vocabulary ' . $this->vocabulary2->id(),
'define view for terms in ' . $this->vocabulary2->id(),
];
$admin_user = $this->drupalCreateUser($permissions);
$this->drupalLogin($admin_user);
}
/**
* Test that the user can see the form to set Taxonomy Views Integrator settings on a given term.
*/
public function testTaxonomyHasTaxonomyViewsIntegratorSettingForm() {
$this->drupalGet('taxonomy/term/' . $this->term1->id() . '/edit');
$this->assertSession()->responseContains('Taxonomy Views Integrator Settings');
$this->assertSession()->responseContains('The default view to use for this term page.');
}
/**
* Test that the right view loads when visiting a term that has configured
* Taxonomy Views Integrator for that term.
*/
public function testViewLoadsFromTermSettings() {
// For term1, we should see the page_1 display of tvi_test_view and not the default taxonomy view.
$this->drupalGet('taxonomy/term/' . $this->term1->id());
$this->assertSession()->responseContains('TVI Foo View');
// For term2, we should see the page_2 display of tvi_test_view and not the default taxonomy view.
$this->drupalGet('taxonomy/term/' . $this->term2->id());
$this->assertSession()->responseContains('TVI Bar View');
// For term3, we should see the page_1 display of tvi_test_view and not the default taxonomy view.
$this->drupalGet('taxonomy/term/' . $this->term3->id());
$this->assertSession()->responseContains('TVI Foo View');
// For term4, we should see the page_1 display of tvi_test_view and not the default taxonomy view.
$this->drupalGet('taxonomy/term/' . $this->term4->id());
$this->assertSession()->responseContains('TVI Foo View');
// For term5, we should see page_1 display, it should override term2 settings.
$this->drupalGet('taxonomy/term/' . $this->term5->id());
$this->assertSession()->responseContains('TVI Foo View');
// For term6, it should inherit term2 settings.
$this->drupalGet('taxonomy/term/' . $this->term6->id());
$this->assertSession()->responseContains('TVI Bar View');
// For term7, it should inherit the vocab settings.
$this->drupalGet('taxonomy/term/' . $this->term7->id());
$this->assertSession()->responseContains('TVI Foo View');
// For term8, we should see the page_1 display of tvi_test_view and not the default taxonomy view.
$this->drupalGet('taxonomy/term/' . $this->term8->id());
$this->assertSession()->responseContains('TVI Foo View');
// For term9, we should only see the default taxonomy view, since it has no associated configuration and the vocab override is disabled.
$this->drupalGet('taxonomy/term/' . $this->term9->id());
$this->assertSession()->responseNotContains('TVI Foo View');
$this->assertSession()->responseContains($this->term9->label());
// For term10, we should see the page_2 display of tvi_test_view and not the default taxonomy view.
$this->drupalGet('taxonomy/term/' . $this->term10->id());
$this->assertSession()->responseContains('TVI Bar View');
// For term11, it should inherit term10 settings.
$this->drupalGet('taxonomy/term/' . $this->term11->id());
$this->assertSession()->responseContains('TVI Bar View');
// For term12, we should see the page_1 display of tvi_test_view
$this->drupalGet('taxonomy/term/' . $this->term12->id());
$this->assertSession()->responseContains('TVI Foo View');
}
} | gpl-2.0 |
findepi/synergy | src/test/integtests/platform/CXWindowsClipboardTests.cpp | 3884 | /*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2012 Bolton Software Ltd.
* Copyright (C) 2011 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file COPYING that should have accompanied this file.
*
* This package 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, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <gtest/gtest.h>
#include "CXWindowsClipboard.h"
class CXWindowsClipboardTests : public ::testing::Test
{
protected:
virtual void
SetUp()
{
m_display = XOpenDisplay(NULL);
int screen = DefaultScreen(m_display);
Window root = XRootWindow(m_display, screen);
XSetWindowAttributes attr;
attr.do_not_propagate_mask = 0;
attr.override_redirect = True;
attr.cursor = Cursor();
m_window = XCreateWindow(
m_display, root, 0, 0, 1, 1, 0, 0,
InputOnly, CopyFromParent, 0, &attr);
}
virtual void
TearDown()
{
XDestroyWindow(m_display, m_window);
XCloseDisplay(m_display);
}
CXWindowsClipboard&
createClipboard()
{
CXWindowsClipboard* clipboard;
clipboard = new CXWindowsClipboard(m_display, m_window, 0);
clipboard->open(0); // needed to empty the clipboard
clipboard->empty(); // needed to own the clipboard
return *clipboard;
}
Display* m_display;
Window m_window;
};
TEST_F(CXWindowsClipboardTests, empty_openCalled_returnsTrue)
{
CXWindowsClipboard clipboard = createClipboard();
bool actual = clipboard.empty();
EXPECT_EQ(true, actual);
}
TEST_F(CXWindowsClipboardTests, empty_singleFormat_hasReturnsFalse)
{
CXWindowsClipboard clipboard = createClipboard();
clipboard.add(CXWindowsClipboard::kText, "synergy rocks!");
clipboard.empty();
bool actual = clipboard.has(CXWindowsClipboard::kText);
EXPECT_FALSE(actual);
}
TEST_F(CXWindowsClipboardTests, add_newValue_valueWasStored)
{
CXWindowsClipboard clipboard = createClipboard();
clipboard.add(IClipboard::kText, "synergy rocks!");
CString actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("synergy rocks!", actual);
}
TEST_F(CXWindowsClipboardTests, add_replaceValue_valueWasReplaced)
{
CXWindowsClipboard clipboard = createClipboard();
clipboard.add(IClipboard::kText, "synergy rocks!");
clipboard.add(IClipboard::kText, "maxivista sucks"); // haha, just kidding.
CString actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("maxivista sucks", actual);
}
TEST_F(CXWindowsClipboardTests, close_isOpen_noErrors)
{
CXWindowsClipboard clipboard = createClipboard();
// clipboard opened in createClipboard()
clipboard.close();
// can't assert anything
}
TEST_F(CXWindowsClipboardTests, has_withFormatAdded_returnsTrue)
{
CXWindowsClipboard clipboard = createClipboard();
clipboard.add(IClipboard::kText, "synergy rocks!");
bool actual = clipboard.has(IClipboard::kText);
EXPECT_EQ(true, actual);
}
TEST_F(CXWindowsClipboardTests, has_withNoFormats_returnsFalse)
{
CXWindowsClipboard clipboard = createClipboard();
bool actual = clipboard.has(IClipboard::kText);
EXPECT_FALSE(actual);
}
TEST_F(CXWindowsClipboardTests, get_withNoFormats_returnsEmpty)
{
CXWindowsClipboard clipboard = createClipboard();
CString actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("", actual);
}
TEST_F(CXWindowsClipboardTests, get_withFormatAdded_returnsExpected)
{
CXWindowsClipboard clipboard = createClipboard();
clipboard.add(IClipboard::kText, "synergy rocks!");
CString actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("synergy rocks!", actual);
}
| gpl-2.0 |
Rud5G/diffDotProject | classes/customfieldsparser.class.php | 8882 | <?php
// $Id: customfieldsparser.class.php 5905 2009-08-13 00:40:21Z merlinyoda $
if (!defined('DP_BASE_DIR')) {
die('You should not access this file directly.');
}
class CustomFieldsParser{
var $fields_array = array();
var $custom_record_type;
var $previous_data = array();
var $row_id = 0;
var $custom_record_types = array();
var $table_name = 'tasks';
var $field_name = 'task_custom';
var $id_field_name = 'task_id';
/**
* @return CustomFieldsParser
* @param char Field type: TaskCustomFields, CompanyCustomFields
* @desc Constructor
*/
function CustomFieldsParser($custom_record_type, $row_id = 0) {
$this->custom_record_type = $custom_record_type;
$this->_fetchFields();
$this->_fetchCustomRecordTypes();
switch ($this->custom_record_type) {
case 'TaskCustomFields':
$this->table_name = 'tasks';
$this->field_name = 'task_custom';
$this->id_field_name = 'task_id';
break;
case 'CompanyCustomFields':
$this->table_name = 'companies';
$this->field_name = 'company_custom';
$this->id_field_name = 'company_id';
break;
default:
$AppUI->setMsg("Invalid custom field record type: $custom_record_type");
break;
}
$this->row_id = $row_id;
if ($this->row_id != 0) {
$this->_fetchPreviousData();
}
}
function _fetchFields() {
$this->fields_array = dPgetSysVal($this->custom_record_type);
}
function _fetchCustomRecordTypes() {
switch ($this->custom_record_type) {
case 'TaskCustomFields':
$field_types = 'TaskType';
break;
case 'CompanyCustomFields':
$field_types = 'CompanyType';
break;
}
$this->custom_record_types = dPgetSysVal($field_types);
}
function _fetchPreviousData() {
$q = new DBQuery;
$q->addTable($this->table_name);
$q->addQuery($this->field_name);
$q->addWhere("{$this->id_field_name} = {$this->row_id}");
$previous_data = $q->loadResult();
if ($previous_data != '') {
$previous_data = unserialize($previous_data);
$previous_data = !is_array($previous_data) ? array() : $previous_data;
} else {
$previous_data = array();
}
$this->previous_data = $previous_data;
}
function _getLabelHTML($field_config) {
if ($field_config['type'] == 'label') {
$colspan = ' colspan="2"';
$field_config['name'] = '<b>' . dPformSafe($field_config['name']) . '</b>';
} else {
$separator = ':';
$field_config['name'] = dPformSafe($field_config['name']);
}
return "<td" . $colspan . ">" . $field_config['name'] . $separator . '</td>';
}
function parseEditField($key) {
$field_config = unserialize($this->fields_array[$key]);
$parsed = '<tr id="custom_tr_' . $key . '">';
$parsed .= $this->_getLabelHTML($field_config);
switch ($field_config['type']) {
case 'text':
case 'href':
$parsed .= ('<td align="left"><input type="text" name="custom_' . $key
. '" class="text" ' . $field_config['options'] . ' value="'
. dPformSafe((isset($this->previous_data[$key])
? $this->previous_data[$key] : ''))
. '" /></td>');
break;
case 'select':
$parsed .= ('<td align="left">'
. arraySelect(explode(',', $field_config['selects']),
dPformSafe('custom_' . $key),
('size="1" class="text" ' . $field_config['options']),
dPformSafe(isset($this->previous_data[$key])
? $this->previous_data[$key] : '')) . '</td>');
break;
case 'textarea':
$parsed .= ('<td align="left"><textarea name="custom_' . dPformSafe($key)
. '" class="textarea" ' . $field_config['options'] . ' >'
. dPformSafe(isset($this->previous_data[$key])
? $this->previous_data[$key] : '') . '</textarea></td>');
break;
case 'checkbox':
$options_array = explode(',', $field_config['selects']);
$parsed .= '<td align="left">';
foreach ($options_array as $option) {
$checked = '';
if (isset($this->previous_data[$key])
&& array_key_exists($option, array_flip($this->previous_data[$key]))) {
$checked = ' checked="checked"';
}
$parsed .= ('<input type="checkbox" value="' . dPformSafe($option)
. '" name="custom_' . dPformSafe($key)
. '[]" class="text" style="border:0"' . $checked . ' '
. $field_config['options'] . ' />' . dPformSafe($option)
. '<br />');
$checked = '';
}
$parsed .= '</td>';
break;
}
$parsed .= '</tr>';
return $parsed;
}
function parseViewField($key) {
$field_config = unserialize($this->fields_array[$key]);
$parsed = ('<tr id="custom_tr_' . $key . '">');
$parsed .= $this->_getLabelHTML($field_config);
switch ($field_config['type']) {
case 'text':
$parsed .= ('<td class="hilite">'
. dPformSafe((isset($this->previous_data[$key])
? $this->previous_data[$key] : ''))
. '</td>');
break;
case 'href':
$parsed .= ('<td class="hilite"><a href="'
. dPformSafe((isset($this->previous_data[$key])
? $this->previous_data[$key] : ''), false, true)
. '">'
. dPformSafe((isset($this->previous_data[$key])
? $this->previous_data[$key] : '')) . '</a></td>');
break;
case 'select':
$optionarray = explode(',', $field_config['selects']);
$parsed .= ('<td class="hilite" width="300">'
. dPformSafe((isset($this->previous_data[$key])
? $optionarray[$this->previous_data[$key]] : ''))
. '</td>');
break;
case 'textarea':
$parsed .= ('<td valign="top" class="hilite">'
. dPformSafe((isset($this->previous_data[$key])
? $this->previous_data[$key] : '')) . '</td>');
break;
case 'checkbox':
$optionarray = explode(',', $field_config['selects']);
$parsed .= '<td align="left">';
foreach ($optionarray as $option) {
$checked = '';
if (isset($this->previous_data[$key])
&& array_key_exists($option, array_flip($this->previous_data[$key]))) {
$checked = ' checked="checked"';
}
$parsed .= ('<input type="checkbox" value="' . $option . ' name="custom_'
. $key . '[]" class="text" style="border:0"' . $checked
. ' ' . $field_config['options']
. ' disabled="disabled" />' . $option . '<br />');
}
$parsed .= '</td>';
break;
}
$parsed .= '</tr>';
return $parsed;
}
function parseTableForm($edit = false, $record_type = null) {
$parsed = '<table>';
$visible_keys = array();
if (!is_null($record_type)) {
$visible_keys = $this->_getVisibleKeysForType($record_type);
}
foreach ($this->fields_array as $key => $field) {
$field_config = unserialize($field);
$fnc_name = (($edit) ? 'parseEditField' : 'parseViewField');
if (in_array($key, $visible_keys)) {
$parsed .= $this->$fnc_name($key);
} else if (is_null($record_type)) {
$parsed .= $this->$fnc_name($key);
}
}
$parsed .= '</table>';
return $parsed;
}
function _getVisibleKeysForType($record_type) {
if (!isset($this->visible_keys)) {
$this->visible_keys = array();
}
if (isset($this->visible_keys[$record_type])) {
return $this->visible_keys[$record_type];
} else {
$this->visible_keys[$record_type] = array();
}
foreach ($this->fields_array as $key => $field) {
$field_config = unserialize($field);
if ($field_config['record_type'] == $record_type
|| $field_config['record_type'] == '') {
$this->visible_keys[$record_type][] = $key;
}
}
return $this->visible_keys[$record_type];
}
function _parseShowFunction($key) {
$parsed = '';
$record_type = $this->custom_record_types[$key];
$record_type = str_replace(' ', '_', $record_type);
$parsed .= "function show$record_type() {\n";
foreach ($this->_getVisibleKeysForType($record_type) as $visible_key) {
$parsed .= "document.getElementById('custom_tr_$visible_key').style.display='';\n";
}
$parsed .= "}\n";
return $parsed;
}
function parseShowFunctions() {
$parsed = '';
foreach ($this->custom_record_types as $key => $record_type) {
$parsed .= $this->_parseShowFunction($key);
}
return $parsed;
}
function showHideAllRowsFunction() {
$parsed = "function hideAllRows() {\n";
foreach ($this->fields_array as $key => $field_config) {
$field_config = unserialize($field_config);
if ($field_config['record_type'] != '') {
$parsed .= "document.getElementById('custom_tr_$key').style.display='none';\n";
}
}
$parsed .= "}\n";
return $parsed;
}
}
?>
| gpl-2.0 |
tommeir/mifgaim | sites/all/themes/genesis/genesis/js/jquery.equalizeheights.js | 4220 | // $Id: jquery.equalizeheights.js,v 1.1.2.1 2009/04/28 09:41:25 jmburnz Exp $
/*--------------------------------------------------------------------
* javascript method: "pxToEm"
* by:
Scott Jehl (scott@filamentgroup.com)
Maggie Wachs (maggie@filamentgroup.com)
http://www.filamentgroup.com
*
* Copyright (c) 2008 Filament Group
* Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
*
* Description: Extends the native Number and String objects with pxToEm method. pxToEm converts a pixel value to ems depending on inherited font size.
* Article: http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/
* Demo: http://www.filamentgroup.com/examples/pxToEm/
*
* Options:
scope: string or jQuery selector for font-size scoping
reverse: Boolean, true reverses the conversion to em-px
* Dependencies: jQuery library
* Usage Example: myPixelValue.pxToEm(); or myPixelValue.pxToEm({'scope':'#navigation', reverse: true});
*
* Version: 2.0, 08.01.2008
* Changelog:
* 08.02.2007 initial Version 1.0
* 08.01.2008 - fixed font-size calculation for IE
--------------------------------------------------------------------*/
Number.prototype.pxToEm = String.prototype.pxToEm = function(settings){
//set defaults
settings = jQuery.extend({
scope: 'body',
reverse: false
}, settings);
var pxVal = (this == '') ? 0 : parseFloat(this);
var scopeVal;
var getWindowWidth = function(){
var de = document.documentElement;
return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
};
/* When a percentage-based font-size is set on the body, IE returns that percent of the window width as the font-size.
For example, if the body font-size is 62.5% and the window width is 1000px, IE will return 625px as the font-size.
When this happens, we calculate the correct body font-size (%) and multiply it by 16 (the standard browser font size)
to get an accurate em value. */
if (settings.scope == 'body' && $.browser.msie && (parseFloat($('body').css('font-size')) / getWindowWidth()).toFixed(1) > 0.0) {
var calcFontSize = function(){
return (parseFloat($('body').css('font-size'))/getWindowWidth()).toFixed(3) * 16;
};
scopeVal = calcFontSize();
}
else { scopeVal = parseFloat(jQuery(settings.scope).css("font-size")); };
var result = (settings.reverse == true) ? (pxVal * scopeVal).toFixed(2) + 'px' : (pxVal / scopeVal).toFixed(2) + 'em';
return result;
};
/*--------------------------------------------------------------------
* JQuery Plugin: "EqualHeights"
* by: Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
*
* Copyright (c) 2008 Filament Group
* Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
*
* Description: Compares the heights or widths of the top-level children of a provided element
and sets their min-height to the tallest height (or width to widest width). Sets in em units
by default if pxToEm() method is available.
* Dependencies: jQuery library, pxToEm method (article:
http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)
* Usage Example: $(element).equalHeights();
Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
* Version: 2.0, 08.01.2008
--------------------------------------------------------------------*/
$.fn.equalHeights = function(px) {
$(this).each(function(){
var currentTallest = 0;
$(this).children().each(function(i){
if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
});
if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
// for ie6, set height since min-height isn't supported
if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
$(this).children().css({'min-height': currentTallest});
});
return this;
};
if (Drupal.jsEnabled) {
$(document).ready(function() {
$('#columns').equalHeights();
});
} | gpl-2.0 |
alexandergurov/vagrant-chef-drupal-stack | cookbooks/drupal-cookbooks/drupal/recipes/dev.rb | 383 | # Install Drupal dev tools.
include_recipe "apt"
include_recipe "build-essential"
# Install Git, since Drupal devs probably need that.
package 'git-core'
php_pear "xdebug" do
action :install
end
template "/etc/php5/apache2/conf.d/xdebug.ini" do
source "xdebug.ini.erb"
owner "root"
group "root"
mode 0644
notifies :restart, resources("service[apache2]"), :delayed
end
| gpl-2.0 |
Jitendra-Patidar/discourse-IB | spec/controllers/list_controller_spec.rb | 5750 | require 'spec_helper'
describe ListController do
# we need some data
before do
@user = Fabricate(:coding_horror)
@post = Fabricate(:post, user: @user)
# forces tests down some code paths
SiteSetting.stubs(:top_menu).returns('latest,-video|new|unread|favorited|categories|category/beer')
end
describe 'indexes' do
Discourse.anonymous_filters.each do |filter|
context "#{filter}" do
before { xhr :get, filter }
it { should respond_with(:success) }
end
end
Discourse.logged_in_filters.each do |filter|
context "#{filter}" do
it { expect { xhr :get, filter }.to raise_error(Discourse::NotLoggedIn) }
end
end
it 'allows users to filter on a set of topic ids' do
p = create_post
xhr :get, :latest, format: :json, topic_ids: "#{p.topic_id}"
response.should be_success
parsed = JSON.parse(response.body)
parsed["topic_list"]["topics"].length.should == 1
end
end
describe 'RSS feeds' do
Discourse.anonymous_filters.each do |filter|
it 'renders RSS' do
get "#{filter}_feed", format: :rss
response.should be_success
response.content_type.should == 'application/rss+xml'
end
end
end
context 'category' do
context 'in a category' do
let(:category) { Fabricate(:category) }
context 'with access to see the category' do
before do
xhr :get, :category, category: category.slug
end
it { should respond_with(:success) }
end
context 'with a link that includes an id' do
before do
xhr :get, :category, category: "#{category.id}-#{category.slug}"
end
it { should respond_with(:success) }
end
context 'another category exists with a number at the beginning of its name' do
# One category has another category's id at the beginning of its name
let!(:other_category) { Fabricate(:category, name: "#{category.id} name") }
before do
xhr :get, :category, category: other_category.slug
end
it { should respond_with(:success) }
it 'uses the correct category' do
assigns(:category).should == other_category
end
end
context 'a child category' do
let(:sub_category) { Fabricate(:category, parent_category_id: category.id) }
context 'when parent and child are requested' do
before do
xhr :get, :category, parent_category: category.slug, category: sub_category.slug
end
it { should respond_with(:success) }
end
context 'when child is requested with the wrong parent' do
before do
xhr :get, :category, parent_category: 'not_the_right_slug', category: sub_category.slug
end
it { should_not respond_with(:success) }
end
end
describe 'feed' do
it 'renders RSS' do
get :category_feed, category: category.slug, format: :rss
response.should be_success
response.content_type.should == 'application/rss+xml'
end
end
end
end
describe "topics_by" do
let!(:user) { log_in }
it "should respond with a list" do
xhr :get, :topics_by, username: @user.username
response.should be_success
end
end
context "private_messages" do
let!(:user) { log_in }
it "raises an error when can_see_private_messages? is false " do
Guardian.any_instance.expects(:can_see_private_messages?).returns(false)
xhr :get, :private_messages, username: @user.username
response.should be_forbidden
end
it "succeeds when can_see_private_messages? is false " do
Guardian.any_instance.expects(:can_see_private_messages?).returns(true)
xhr :get, :private_messages, username: @user.username
response.should be_success
end
end
context "private_messages_sent" do
let!(:user) { log_in }
it "raises an error when can_see_private_messages? is false " do
Guardian.any_instance.expects(:can_see_private_messages?).returns(false)
xhr :get, :private_messages_sent, username: @user.username
response.should be_forbidden
end
it "succeeds when can_see_private_messages? is false " do
Guardian.any_instance.expects(:can_see_private_messages?).returns(true)
xhr :get, :private_messages_sent, username: @user.username
response.should be_success
end
end
context "private_messages_unread" do
let!(:user) { log_in }
it "raises an error when can_see_private_messages? is false " do
Guardian.any_instance.expects(:can_see_private_messages?).returns(false)
xhr :get, :private_messages_unread, username: @user.username
response.should be_forbidden
end
it "succeeds when can_see_private_messages? is false " do
Guardian.any_instance.expects(:can_see_private_messages?).returns(true)
xhr :get, :private_messages_unread, username: @user.username
response.should be_success
end
end
context 'favorited' do
it 'raises an error when not logged in' do
lambda { xhr :get, :favorited }.should raise_error(Discourse::NotLoggedIn)
end
context 'when logged in' do
before do
log_in_user(@user)
xhr :get, :favorited
end
it { should respond_with(:success) }
end
end
context 'read' do
it 'raises an error when not logged in' do
lambda { xhr :get, :read }.should raise_error(Discourse::NotLoggedIn)
end
context 'when logged in' do
before do
log_in_user(@user)
xhr :get, :read
end
it { should respond_with(:success) }
end
end
end
| gpl-2.0 |
SpoonLabs/astor | examples/chart_1/source/org/jfree/data/statistics/HistogramDataset.java | 17721 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* 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 Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ---------------------
* HistogramDataset.java
* ---------------------
* (C) Copyright 2003-2008, by Jelai Wang and Contributors.
*
* Original Author: Jelai Wang (jelaiw AT mindspring.com);
* Contributor(s): David Gilbert (for Object Refinery Limited);
* Cameron Hayne;
* Rikard Bj?rklind;
*
* Changes
* -------
* 06-Jul-2003 : Version 1, contributed by Jelai Wang (DG);
* 07-Jul-2003 : Changed package and added Javadocs (DG);
* 15-Oct-2003 : Updated Javadocs and removed array sorting (JW);
* 09-Jan-2004 : Added fix by "Z." posted in the JFreeChart forum (DG);
* 01-Mar-2004 : Added equals() and clone() methods and implemented
* Serializable. Also added new addSeries() method (DG);
* 06-May-2004 : Now extends AbstractIntervalXYDataset (DG);
* 15-Jul-2004 : Switched getX() with getXValue() and getY() with
* getYValue() (DG);
* 20-May-2005 : Speed up binning - see patch 1026151 contributed by Cameron
* Hayne (DG);
* 08-Jun-2005 : Fixed bug in getSeriesKey() method (DG);
* 22-Nov-2005 : Fixed cast in getSeriesKey() method - see patch 1329287 (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 03-Aug-2006 : Improved precision of bin boundary calculation (DG);
* 07-Sep-2006 : Fixed bug 1553088 (DG);
* 21-Jun-2007 : Removed JCommon dependencies (DG);
* 22-May-2008 : Implemented clone() method override (DG);
*
*/
package org.jfree.data.statistics;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jfree.chart.event.DatasetChangeInfo;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.data.event.DatasetChangeEvent;
import org.jfree.data.xy.AbstractIntervalXYDataset;
import org.jfree.data.xy.IntervalXYDataset;
/**
* A dataset that can be used for creating histograms.
*
* @see SimpleHistogramDataset
*/
public class HistogramDataset extends AbstractIntervalXYDataset
implements IntervalXYDataset, Cloneable, PublicCloneable,
Serializable {
/** For serialization. */
private static final long serialVersionUID = -6341668077370231153L;
/** A list of maps. */
private List list;
/** The histogram type. */
private HistogramType type;
/**
* Creates a new (empty) dataset with a default type of
* {@link HistogramType}.FREQUENCY.
*/
public HistogramDataset() {
this.list = new ArrayList();
this.type = HistogramType.FREQUENCY;
}
/**
* Returns the histogram type.
*
* @return The type (never <code>null</code>).
*/
public HistogramType getType() {
return this.type;
}
/**
* Sets the histogram type and sends a {@link DatasetChangeEvent} to all
* registered listeners.
*
* @param type the type (<code>null</code> not permitted).
*/
public void setType(HistogramType type) {
if (type == null) {
throw new IllegalArgumentException("Null 'type' argument");
}
this.type = type;
fireDatasetChanged(new DatasetChangeInfo());
//TODO: fill in real change info
}
/**
* Adds a series to the dataset, using the specified number of bins.
*
* @param key the series key (<code>null</code> not permitted).
* @param values the values (<code>null</code> not permitted).
* @param bins the number of bins (must be at least 1).
*/
public void addSeries(Comparable key, double[] values, int bins) {
// defer argument checking...
double minimum = getMinimum(values);
double maximum = getMaximum(values);
addSeries(key, values, bins, minimum, maximum);
}
/**
* Adds a series to the dataset. Any data value less than minimum will be
* assigned to the first bin, and any data value greater than maximum will
* be assigned to the last bin. Values falling on the boundary of
* adjacent bins will be assigned to the higher indexed bin.
*
* @param key the series key (<code>null</code> not permitted).
* @param values the raw observations.
* @param bins the number of bins (must be at least 1).
* @param minimum the lower bound of the bin range.
* @param maximum the upper bound of the bin range.
*/
public void addSeries(Comparable key,
double[] values,
int bins,
double minimum,
double maximum) {
if (key == null) {
throw new IllegalArgumentException("Null 'key' argument.");
}
if (values == null) {
throw new IllegalArgumentException("Null 'values' argument.");
}
else if (bins < 1) {
throw new IllegalArgumentException(
"The 'bins' value must be at least 1.");
}
double binWidth = (maximum - minimum) / bins;
double lower = minimum;
double upper;
List binList = new ArrayList(bins);
for (int i = 0; i < bins; i++) {
HistogramBin bin;
// make sure bins[bins.length]'s upper boundary ends at maximum
// to avoid the rounding issue. the bins[0] lower boundary is
// guaranteed start from min
if (i == bins - 1) {
bin = new HistogramBin(lower, maximum);
}
else {
upper = minimum + (i + 1) * binWidth;
bin = new HistogramBin(lower, upper);
lower = upper;
}
binList.add(bin);
}
// fill the bins
for (int i = 0; i < values.length; i++) {
int binIndex = bins - 1;
if (values[i] < maximum) {
double fraction = (values[i] - minimum) / (maximum - minimum);
if (fraction < 0.0) {
fraction = 0.0;
}
binIndex = (int) (fraction * bins);
// rounding could result in binIndex being equal to bins
// which will cause an IndexOutOfBoundsException - see bug
// report 1553088
if (binIndex >= bins) {
binIndex = bins - 1;
}
}
HistogramBin bin = (HistogramBin) binList.get(binIndex);
bin.incrementCount();
}
// generic map for each series
Map map = new HashMap();
map.put("key", key);
map.put("bins", binList);
map.put("values.length", new Integer(values.length));
map.put("bin width", new Double(binWidth));
this.list.add(map);
}
/**
* Returns the minimum value in an array of values.
*
* @param values the values (<code>null</code> not permitted and
* zero-length array not permitted).
*
* @return The minimum value.
*/
private double getMinimum(double[] values) {
if (values == null || values.length < 1) {
throw new IllegalArgumentException(
"Null or zero length 'values' argument.");
}
double min = Double.MAX_VALUE;
for (int i = 0; i < values.length; i++) {
if (values[i] < min) {
min = values[i];
}
}
return min;
}
/**
* Returns the maximum value in an array of values.
*
* @param values the values (<code>null</code> not permitted and
* zero-length array not permitted).
*
* @return The maximum value.
*/
private double getMaximum(double[] values) {
if (values == null || values.length < 1) {
throw new IllegalArgumentException(
"Null or zero length 'values' argument.");
}
double max = -Double.MAX_VALUE;
for (int i = 0; i < values.length; i++) {
if (values[i] > max) {
max = values[i];
}
}
return max;
}
/**
* Returns the bins for a series.
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
*
* @return A list of bins.
*
* @throws IndexOutOfBoundsException if <code>series</code> is outside the
* specified range.
*/
List getBins(int series) {
Map map = (Map) this.list.get(series);
return (List) map.get("bins");
}
/**
* Returns the total number of observations for a series.
*
* @param series the series index.
*
* @return The total.
*/
private int getTotal(int series) {
Map map = (Map) this.list.get(series);
return ((Integer) map.get("values.length")).intValue();
}
/**
* Returns the bin width for a series.
*
* @param series the series index (zero based).
*
* @return The bin width.
*/
private double getBinWidth(int series) {
Map map = (Map) this.list.get(series);
return ((Double) map.get("bin width")).doubleValue();
}
/**
* Returns the number of series in the dataset.
*
* @return The series count.
*/
public int getSeriesCount() {
return this.list.size();
}
/**
* Returns the key for a series.
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
*
* @return The series key.
*
* @throws IndexOutOfBoundsException if <code>series</code> is outside the
* specified range.
*/
public Comparable getSeriesKey(int series) {
Map map = (Map) this.list.get(series);
return (Comparable) map.get("key");
}
/**
* Returns the number of data items for a series.
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
*
* @return The item count.
*
* @throws IndexOutOfBoundsException if <code>series</code> is outside the
* specified range.
*/
public int getItemCount(int series) {
return getBins(series).size();
}
/**
* Returns the X value for a bin. This value won't be used for plotting
* histograms, since the renderer will ignore it. But other renderers can
* use it (for example, you could use the dataset to create a line
* chart).
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
* @param item the item index (zero based).
*
* @return The start value.
*
* @throws IndexOutOfBoundsException if <code>series</code> is outside the
* specified range.
*/
public Number getX(int series, int item) {
List bins = getBins(series);
HistogramBin bin = (HistogramBin) bins.get(item);
double x = (bin.getStartBoundary() + bin.getEndBoundary()) / 2.;
return new Double(x);
}
/**
* Returns the y-value for a bin (calculated to take into account the
* histogram type).
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
* @param item the item index (zero based).
*
* @return The y-value.
*
* @throws IndexOutOfBoundsException if <code>series</code> is outside the
* specified range.
*/
public Number getY(int series, int item) {
List bins = getBins(series);
HistogramBin bin = (HistogramBin) bins.get(item);
double total = getTotal(series);
double binWidth = getBinWidth(series);
if (this.type == HistogramType.FREQUENCY) {
return new Double(bin.getCount());
}
else if (this.type == HistogramType.RELATIVE_FREQUENCY) {
return new Double(bin.getCount() / total);
}
else if (this.type == HistogramType.SCALE_AREA_TO_1) {
return new Double(bin.getCount() / (binWidth * total));
}
else { // pretty sure this shouldn't ever happen
throw new IllegalStateException();
}
}
/**
* Returns the start value for a bin.
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
* @param item the item index (zero based).
*
* @return The start value.
*
* @throws IndexOutOfBoundsException if <code>series</code> is outside the
* specified range.
*/
public Number getStartX(int series, int item) {
List bins = getBins(series);
HistogramBin bin = (HistogramBin) bins.get(item);
return new Double(bin.getStartBoundary());
}
/**
* Returns the end value for a bin.
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
* @param item the item index (zero based).
*
* @return The end value.
*
* @throws IndexOutOfBoundsException if <code>series</code> is outside the
* specified range.
*/
public Number getEndX(int series, int item) {
List bins = getBins(series);
HistogramBin bin = (HistogramBin) bins.get(item);
return new Double(bin.getEndBoundary());
}
/**
* Returns the start y-value for a bin (which is the same as the y-value,
* this method exists only to support the general form of the
* {@link IntervalXYDataset} interface).
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
* @param item the item index (zero based).
*
* @return The y-value.
*
* @throws IndexOutOfBoundsException if <code>series</code> is outside the
* specified range.
*/
public Number getStartY(int series, int item) {
return getY(series, item);
}
/**
* Returns the end y-value for a bin (which is the same as the y-value,
* this method exists only to support the general form of the
* {@link IntervalXYDataset} interface).
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
* @param item the item index (zero based).
*
* @return The Y value.
*
* @throws IndexOutOfBoundsException if <code>series</code> is outside the
* specified range.
*/
public Number getEndY(int series, int item) {
return getY(series, item);
}
/**
* Tests this dataset for equality with an arbitrary object.
*
* @param obj the object to test against (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof HistogramDataset)) {
return false;
}
HistogramDataset that = (HistogramDataset) obj;
if (!ObjectUtilities.equal(this.type, that.type)) {
return false;
}
if (!ObjectUtilities.equal(this.list, that.list)) {
return false;
}
return true;
}
/**
* Returns a clone of the dataset.
*
* @return A clone of the dataset.
*
* @throws CloneNotSupportedException if the object cannot be cloned.
*/
public Object clone() throws CloneNotSupportedException {
HistogramDataset clone = (HistogramDataset) super.clone();
int seriesCount = getSeriesCount();
clone.list = new java.util.ArrayList(seriesCount);
for (int i = 0; i < seriesCount; i++) {
clone.list.add(new HashMap((Map) this.list.get(i)));
}
return clone;
}
}
| gpl-2.0 |
cuongnd/etravelservice | libraries/fof30/Model/DataModel/Relation/Exception/RelationTypeNotFound.php | 271 | <?php
/**
* @package FOF
* @copyright 2010-2016 Nicholas K. Dionysopoulos / Akeeba Ltd
* @license GNU GPL version 2 or later
*/
namespace FOF30\Model\DataModel\Relation\Exception;
defined('_JEXEC') or die;
class RelationTypeNotFound extends \Exception {} | gpl-2.0 |
potherca-contrib/tuxdroidserver | test/vendor/ceedling/lib/file_path_utils.rb | 7743 | require 'rubygems'
require 'rake' # for ext()
require 'fileutils'
require 'system_wrapper'
# global utility methods (for plugins, project files, etc.)
def ceedling_form_filepath(destination_path, original_filepath, new_extension=nil)
filename = File.basename(original_filepath)
filename.replace(filename.ext(new_extension)) if (!new_extension.nil?)
return File.join( destination_path.gsub(/\\/, '/'), filename )
end
class FilePathUtils
GLOB_MATCHER = /[\*\?\{\}\[\]]/
constructor :configurator, :file_wrapper
######### class methods ##########
# standardize path to use '/' path separator & begin with './' & have no trailing path separator
def self.standardize(path)
path.strip!
path.gsub!(/\\/, '/')
path.gsub!(/^((\+|-):)?\.\//, '')
path.chomp!('/')
return path
end
def self.os_executable_ext(executable)
return executable.ext('.exe') if SystemWrapper.windows?
return executable
end
# extract directory path from between optional add/subtract aggregation modifiers and up to glob specifiers
# note: slightly different than File.dirname in that /files/foo remains /files/foo and does not become /files
def self.extract_path(path)
path = path.sub(/^(\+|-):/, '')
# find first occurrence of path separator followed by directory glob specifier: *, ?, {, }, [, ]
find_index = (path =~ GLOB_MATCHER)
# no changes needed (lop off final path separator)
return path.chomp('/') if (find_index.nil?)
# extract up to first glob specifier
path = path[0..(find_index-1)]
# lop off everything up to and including final path separator
find_index = path.rindex('/')
return path[0..(find_index-1)] if (not find_index.nil?)
# return string up to first glob specifier if no path separator found
return path
end
# return whether the given path is to be aggregated (no aggregation modifier defaults to same as +:)
def self.add_path?(path)
return (path =~ /^-:/).nil?
end
# get path (and glob) lopping off optional +: / -: prefixed aggregation modifiers
def self.extract_path_no_aggregation_operators(path)
return path.sub(/^(\+|-):/, '')
end
# all the globs that may be in a path string work fine with one exception;
# to recurse through all subdirectories, the glob is dir/**/** but our paths use
# convention of only dir/**
def self.reform_glob(path)
return path if (path =~ /\/\*\*$/).nil?
return path + '/**'
end
def self.form_ceedling_vendor_path(*filepaths)
return File.join( CEEDLING_VENDOR, filepaths )
end
######### instance methods ##########
def form_temp_path(filepath, prefix='')
return File.join( @configurator.project_temp_path, prefix + File.basename(filepath) )
end
### release ###
def form_release_build_cache_path(filepath)
return File.join( @configurator.project_release_build_cache_path, File.basename(filepath) )
end
def form_release_dependencies_filepath(filepath)
return File.join( @configurator.project_release_dependencies_path, File.basename(filepath).ext(@configurator.extension_dependencies) )
end
def form_release_build_c_object_filepath(filepath)
return File.join( @configurator.project_release_build_output_c_path, File.basename(filepath).ext(@configurator.extension_object) )
end
def form_release_build_asm_object_filepath(filepath)
return File.join( @configurator.project_release_build_output_asm_path, File.basename(filepath).ext(@configurator.extension_object) )
end
def form_release_build_c_objects_filelist(files)
return (@file_wrapper.instantiate_file_list(files)).pathmap("#{@configurator.project_release_build_output_c_path}/%n#{@configurator.extension_object}")
end
def form_release_build_asm_objects_filelist(files)
return (@file_wrapper.instantiate_file_list(files)).pathmap("#{@configurator.project_release_build_output_asm_path}/%n#{@configurator.extension_object}")
end
def form_release_build_c_list_filepath(filepath)
return File.join( @configurator.project_release_build_output_c_path, File.basename(filepath).ext(@configurator.extension_list) )
end
def form_release_dependencies_filelist(files)
return (@file_wrapper.instantiate_file_list(files)).pathmap("#{@configurator.project_release_dependencies_path}/%n#{@configurator.extension_dependencies}")
end
### tests ###
def form_test_build_cache_path(filepath)
return File.join( @configurator.project_test_build_cache_path, File.basename(filepath) )
end
def form_pass_results_filepath(filepath)
return File.join( @configurator.project_test_results_path, File.basename(filepath).ext(@configurator.extension_testpass) )
end
def form_fail_results_filepath(filepath)
return File.join( @configurator.project_test_results_path, File.basename(filepath).ext(@configurator.extension_testfail) )
end
def form_runner_filepath_from_test(filepath)
return File.join( @configurator.project_test_runners_path, File.basename(filepath, @configurator.extension_source)) + @configurator.test_runner_file_suffix + @configurator.extension_source
end
def form_test_filepath_from_runner(filepath)
return filepath.sub(/#{TEST_RUNNER_FILE_SUFFIX}/, '')
end
def form_runner_object_filepath_from_test(filepath)
return (form_test_build_object_filepath(filepath)).sub(/(#{@configurator.extension_object})$/, "#{@configurator.test_runner_file_suffix}\\1")
end
def form_test_build_object_filepath(filepath)
return File.join( @configurator.project_test_build_output_path, File.basename(filepath).ext(@configurator.extension_object) )
end
def form_test_executable_filepath(filepath)
return File.join( @configurator.project_test_build_output_path, File.basename(filepath).ext(@configurator.extension_executable) )
end
def form_test_build_map_filepath(filepath)
return File.join( @configurator.project_test_build_output_path, File.basename(filepath).ext(@configurator.extension_map) )
end
def form_test_build_list_filepath(filepath)
return File.join( @configurator.project_test_build_output_path, File.basename(filepath).ext(@configurator.extension_list) )
end
def form_preprocessed_file_filepath(filepath)
return File.join( @configurator.project_test_preprocess_files_path, File.basename(filepath) )
end
def form_preprocessed_includes_list_filepath(filepath)
return File.join( @configurator.project_test_preprocess_includes_path, File.basename(filepath) )
end
def form_test_build_objects_filelist(sources)
return (@file_wrapper.instantiate_file_list(sources)).pathmap("#{@configurator.project_test_build_output_path}/%n#{@configurator.extension_object}")
end
def form_preprocessed_mockable_headers_filelist(mocks)
# pathmapping note: "%{#{@configurator.cmock_mock_prefix},}n" replaces mock_prefix with nothing (signified by absence of anything after comma inside replacement brackets)
return (@file_wrapper.instantiate_file_list(mocks)).pathmap("#{@configurator.project_test_preprocess_files_path}/%{#{@configurator.cmock_mock_prefix},}n#{@configurator.extension_header}")
end
def form_mocks_source_filelist(mocks)
return (@file_wrapper.instantiate_file_list(mocks)).pathmap("#{@configurator.cmock_mock_path}/%n#{@configurator.extension_source}")
end
def form_test_dependencies_filelist(files)
return (@file_wrapper.instantiate_file_list(files)).pathmap("#{@configurator.project_test_dependencies_path}/%n#{@configurator.extension_dependencies}")
end
def form_pass_results_filelist(path, files)
return (@file_wrapper.instantiate_file_list(files)).pathmap("#{path}/%n#{@configurator.extension_testpass}")
end
end
| gpl-2.0 |
UAReformers/Petitions-Deploy-Distributive | profiles/petitions/modules/contrib/services_documentation/theme/services-documentation-method-example-implementations-bundles.tpl.php | 653 | <?php
/**
* @file
* services-documentation-method-example-implementations-bundles.tpl.php
*
* Template file for theming an example implementations bundle for a given
* Services method.
*
* Available custom variables:
* - $language:
* - $examples:
*/
?>
<!-- services-documentation-method-example-implementations-bundle -->
<div class="services-documentation-method-example-implementations-bundle">
<h6 class="examples-language"><?php print $language; ?></h6>
<?php foreach ($examples as $example): ?>
<?php print render($example); ?>
<?php endforeach; ?>
</div>
<!-- /services-documentation-method-example-implementations-bundle -->
| gpl-2.0 |
mibischo/freemind | freemind/controller/filter/util/SortedComboBoxModel.java | 1585 | /*FreeMind - A Program for creating and viewing Mindmaps
*Copyright (C) 2000-2006 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitri Polivaev and others.
*
*See COPYING for Details
*
*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.
*/
/*
* Created on 10.07.2005
* Copyright (C) 2005 Dimitri Polivaev
*/
package freemind.controller.filter.util;
import javax.swing.ComboBoxModel;
/**
* @author Dimitri Polivaev 10.07.2005
*/
public class SortedComboBoxModel extends SortedMapListModel implements
SortedListModel, ComboBoxModel {
private Object selectedItem;
/*
* (non-Javadoc)
*
* @see javax.swing.ComboBoxModel#setSelectedItem(java.lang.Object)
*/
public void setSelectedItem(Object o) {
selectedItem = o;
fireContentsChanged(this, -1, -1);
}
/*
* (non-Javadoc)
*
* @see javax.swing.ComboBoxModel#getSelectedItem()
*/
public Object getSelectedItem() {
return selectedItem;
}
}
| gpl-2.0 |
xamarindevelopervietnaminc/XGravatar | XGravatar/XGravatar/XGravatar.Droid/obj/Debug/android/src/md5b60ffeb829f638581ab2bb9b1a7f4f3f/MasterDetailContainer.java | 3978 | package md5b60ffeb829f638581ab2bb9b1a7f4f3f;
public class MasterDetailContainer
extends android.view.ViewGroup
implements
mono.android.IGCUserPeer
{
static final String __md_methods;
static {
__md_methods =
"n_onLayout:(ZIIII)V:GetOnLayout_ZIIIIHandler\n" +
"n_onInterceptTouchEvent:(Landroid/view/MotionEvent;)Z:GetOnInterceptTouchEvent_Landroid_view_MotionEvent_Handler\n" +
"";
mono.android.Runtime.register ("Xamarin.Forms.Platform.Android.MasterDetailContainer, Xamarin.Forms.Platform.Android, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", MasterDetailContainer.class, __md_methods);
}
public MasterDetailContainer (android.content.Context p0) throws java.lang.Throwable
{
super (p0);
if (getClass () == MasterDetailContainer.class)
mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.MasterDetailContainer, Xamarin.Forms.Platform.Android, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", "Android.Content.Context, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065", this, new java.lang.Object[] { p0 });
}
public MasterDetailContainer (android.content.Context p0, android.util.AttributeSet p1) throws java.lang.Throwable
{
super (p0, p1);
if (getClass () == MasterDetailContainer.class)
mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.MasterDetailContainer, Xamarin.Forms.Platform.Android, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", "Android.Content.Context, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:Android.Util.IAttributeSet, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065", this, new java.lang.Object[] { p0, p1 });
}
public MasterDetailContainer (android.content.Context p0, android.util.AttributeSet p1, int p2) throws java.lang.Throwable
{
super (p0, p1, p2);
if (getClass () == MasterDetailContainer.class)
mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.MasterDetailContainer, Xamarin.Forms.Platform.Android, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", "Android.Content.Context, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:Android.Util.IAttributeSet, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:System.Int32, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", this, new java.lang.Object[] { p0, p1, p2 });
}
public MasterDetailContainer (android.content.Context p0, android.util.AttributeSet p1, int p2, int p3) throws java.lang.Throwable
{
super (p0, p1, p2, p3);
if (getClass () == MasterDetailContainer.class)
mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.MasterDetailContainer, Xamarin.Forms.Platform.Android, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", "Android.Content.Context, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:Android.Util.IAttributeSet, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:System.Int32, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e:System.Int32, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", this, new java.lang.Object[] { p0, p1, p2, p3 });
}
public void onLayout (boolean p0, int p1, int p2, int p3, int p4)
{
n_onLayout (p0, p1, p2, p3, p4);
}
private native void n_onLayout (boolean p0, int p1, int p2, int p3, int p4);
public boolean onInterceptTouchEvent (android.view.MotionEvent p0)
{
return n_onInterceptTouchEvent (p0);
}
private native boolean n_onInterceptTouchEvent (android.view.MotionEvent p0);
java.util.ArrayList refList;
public void monodroidAddReference (java.lang.Object obj)
{
if (refList == null)
refList = new java.util.ArrayList ();
refList.add (obj);
}
public void monodroidClearReferences ()
{
if (refList != null)
refList.clear ();
}
}
| gpl-2.0 |
sergiobenrocha2/libretro-ppsspp | GPU/GLES/DepalettizeShader.cpp | 7699 | // Copyright (c) 2014- PPSSPP Project.
// 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.0 or later versions.
// 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 2.0 for more details.
// A copy of the GPL 2.0 should have been included with the program.
// If not, see http://www.gnu.org/licenses/
// Official git repository and contact information can be found at
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
#include <map>
#include "base/logging.h"
#include "Common/Log.h"
#include "Core/Reporting.h"
#include "DepalettizeShader.h"
#include "GPU/GLES/TextureCache.h"
#include "GPU/Common/DepalettizeShaderCommon.h"
static const int DEPAL_TEXTURE_OLD_AGE = 120;
#ifdef _WIN32
#define SHADERLOG
#endif
static const char *depalVShader100 =
#ifdef USING_GLES2
"#version 100\n"
"precision highp float;\n"
#endif
"attribute vec4 a_position;\n"
"attribute vec2 a_texcoord0;\n"
"varying vec2 v_texcoord0;\n"
"void main() {\n"
" v_texcoord0 = a_texcoord0;\n"
" gl_Position = a_position;\n"
"}\n";
static const char *depalVShader300 =
#ifdef USING_GLES2
"#version 300 es\n"
"precision highp float;\n"
#else
"#version 330\n"
#endif
"in vec4 a_position;\n"
"in vec2 a_texcoord0;\n"
"out vec2 v_texcoord0;\n"
"void main() {\n"
" v_texcoord0 = a_texcoord0;\n"
" gl_Position = a_position;\n"
"}\n";
static bool CheckShaderCompileSuccess(GLuint shader, const char *code) {
GLint success;
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success) {
#define MAX_INFO_LOG_SIZE 2048
GLchar infoLog[MAX_INFO_LOG_SIZE];
GLsizei len;
glGetShaderInfoLog(shader, MAX_INFO_LOG_SIZE, &len, infoLog);
infoLog[len] = '\0';
#ifdef ANDROID
ELOG("Error in shader compilation! %s\n", infoLog);
ELOG("Shader source:\n%s\n", (const char *)code);
#endif
ERROR_LOG(G3D, "Error in shader compilation!\n");
ERROR_LOG(G3D, "Info log: %s\n", infoLog);
ERROR_LOG(G3D, "Shader source:\n%s\n", (const char *)code);
#ifdef SHADERLOG
OutputDebugStringUTF8(infoLog);
#endif
shader = 0;
return false;
} else {
DEBUG_LOG(G3D, "Compiled shader:\n%s\n", (const char *)code);
#ifdef SHADERLOG
OutputDebugStringUTF8(code);
#endif
return true;
}
}
DepalShaderCache::DepalShaderCache() {
// Pre-build the vertex program
useGL3_ = gl_extensions.GLES3 || gl_extensions.VersionGEThan(3, 3);
vertexShaderFailed_ = false;
vertexShader_ = 0;
}
DepalShaderCache::~DepalShaderCache() {
Clear();
}
bool DepalShaderCache::CreateVertexShader() {
if (vertexShaderFailed_) {
return false;
}
vertexShader_ = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader_, 1, useGL3_ ? &depalVShader300 : &depalVShader100, 0);
glCompileShader(vertexShader_);
if (!CheckShaderCompileSuccess(vertexShader_, useGL3_ ? depalVShader300 : depalVShader100)) {
glDeleteShader(vertexShader_);
vertexShader_ = 0;
// Don't try to recompile.
vertexShaderFailed_ = true;
}
return !vertexShaderFailed_;
}
u32 DepalShaderCache::GenerateShaderID(GEPaletteFormat clutFormat, GEBufferFormat pixelFormat) {
return (gstate.clutformat & 0xFFFFFF) | (pixelFormat << 24);
}
GLuint DepalShaderCache::GetClutTexture(GEPaletteFormat clutFormat, const u32 clutID, u32 *rawClut) {
const u32 realClutID = clutID ^ clutFormat;
auto oldtex = texCache_.find(realClutID);
if (oldtex != texCache_.end()) {
oldtex->second->lastFrame = gpuStats.numFlips;
return oldtex->second->texture;
}
GLuint dstFmt = getClutDestFormat(clutFormat);
int texturePixels = clutFormat == GE_CMODE_32BIT_ABGR8888 ? 256 : 512;
bool useBGRA = UseBGRA8888() && dstFmt == GL_UNSIGNED_BYTE;
DepalTexture *tex = new DepalTexture();
glGenTextures(1, &tex->texture);
glBindTexture(GL_TEXTURE_2D, tex->texture);
GLuint components = dstFmt == GL_UNSIGNED_SHORT_5_6_5 ? GL_RGB : GL_RGBA;
GLuint components2 = components;
if (useBGRA) {
components2 = GL_BGRA_EXT;
}
glTexImage2D(GL_TEXTURE_2D, 0, components, texturePixels, 1, 0, components2, dstFmt, (void *)rawClut);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
tex->lastFrame = gpuStats.numFlips;
texCache_[realClutID] = tex;
return tex->texture;
}
void DepalShaderCache::Clear() {
for (auto shader = cache_.begin(); shader != cache_.end(); ++shader) {
glDeleteShader(shader->second->fragShader);
if (shader->second->program) {
glDeleteProgram(shader->second->program);
}
delete shader->second;
}
cache_.clear();
for (auto tex = texCache_.begin(); tex != texCache_.end(); ++tex) {
glDeleteTextures(1, &tex->second->texture);
delete tex->second;
}
texCache_.clear();
if (vertexShader_) {
glDeleteShader(vertexShader_);
vertexShader_ = 0;
}
}
void DepalShaderCache::Decimate() {
for (auto tex = texCache_.begin(); tex != texCache_.end(); ) {
if (tex->second->lastFrame + DEPAL_TEXTURE_OLD_AGE < gpuStats.numFlips) {
glDeleteTextures(1, &tex->second->texture);
delete tex->second;
texCache_.erase(tex++);
} else {
++tex;
}
}
}
DepalShader *DepalShaderCache::GetDepalettizeShader(GEPaletteFormat clutFormat, GEBufferFormat pixelFormat) {
u32 id = GenerateShaderID(clutFormat, pixelFormat);
auto shader = cache_.find(id);
if (shader != cache_.end()) {
return shader->second;
}
if (vertexShader_ == 0) {
if (!CreateVertexShader()) {
// The vertex shader failed, no need to bother trying the fragment.
return nullptr;
}
}
char *buffer = new char[2048];
GenerateDepalShader(buffer, pixelFormat, useGL3_ ? GLSL_300 : GLSL_140);
GLuint fragShader = glCreateShader(GL_FRAGMENT_SHADER);
const char *buf = buffer;
glShaderSource(fragShader, 1, &buf, 0);
glCompileShader(fragShader);
CheckShaderCompileSuccess(fragShader, buffer);
GLuint program = glCreateProgram();
glAttachShader(program, vertexShader_);
glAttachShader(program, fragShader);
glBindAttribLocation(program, 0, "a_position");
glBindAttribLocation(program, 1, "a_texcoord0");
glLinkProgram(program);
glUseProgram(program);
GLint u_tex = glGetUniformLocation(program, "tex");
GLint u_pal = glGetUniformLocation(program, "pal");
glUniform1i(u_tex, 0);
glUniform1i(u_pal, 3);
DepalShader *depal = new DepalShader();
depal->program = program;
depal->fragShader = fragShader;
cache_[id] = depal;
GLint linkStatus = GL_FALSE;
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
if (linkStatus != GL_TRUE) {
GLint bufLength = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength);
if (bufLength) {
char* errorbuf = new char[bufLength];
glGetProgramInfoLog(program, bufLength, NULL, errorbuf);
#ifdef SHADERLOG
OutputDebugStringUTF8(buffer);
OutputDebugStringUTF8(errorbuf);
#endif
ERROR_LOG(G3D, "Could not link program:\n %s \n\n %s", errorbuf, buf);
delete[] errorbuf; // we're dead!
}
// Since it failed, let's mark it in the cache so we don't keep retrying.
// That will only make it slower.
depal->program = 0;
// We will delete the shader later in Clear().
glDeleteProgram(program);
} else {
depal->a_position = glGetAttribLocation(program, "a_position");
depal->a_texcoord0 = glGetAttribLocation(program, "a_texcoord0");
}
delete[] buffer;
return depal->program ? depal : nullptr;
}
| gpl-2.0 |
abhishekmurthy/Calligra | plan/plugins/scripting/tests/calendar_readwrite.py | 1381 | #!/usr/bin/env kross
# -*- coding: utf-8 -*-
import traceback
import Kross
import Plan
import TestResult
TestResult.setResult( True )
asserttext1 = "Test of property '{0}' failed:\n Expected: '{2}'\n Result: '{1}'"
asserttext2 = "Failed to set property '{0}' to '{1}'. Result: {2}"
try:
project = Plan.project()
assert project is not None
calendar = project.createCalendar( 0 )
assert calendar is not None, "Could not create calendar"
property = 'Name'
data = "Calendar name"
res = project.setData(calendar, property, data)
text = asserttext2.format(property, data, res)
assert res == 'Success', text
property = 'Name'
data = 2 # Checked
res = project.setData(calendar, property, data, 'CheckStateRole')
text = asserttext2.format(property, data, res)
assert res == 'Success', text + " role = CheckStateRole"
c2 = project.createCalendar( 0 )
assert c2 is not None, "Could not create calendar"
props = project.calendarPropertyList()
for p in props:
data = project.data(calendar, p, 'ProgramRole')
res = project.setData(c2, p, data)
if res != 'ReadOnly':
text = asserttext2.format(property, data, res)
assert res == 'Success', text
except:
TestResult.setResult( False )
TestResult.setMessage("\n" + traceback.format_exc(1))
| gpl-2.0 |
jagnoha/website | profiles/varbase/profiles/varbase/libraries/ckeditor/plugins/image/lang/bn.js | 1309 | /*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'image', 'bn', {
alt: 'বিকল্প টেক্সট',
border: 'বর্ডার',
btnUpload: 'ইহাকে সার্ভারে প্রেরন কর',
button2Img: 'Do you want to transform the selected image button on a simple image?', // MISSING
hSpace: 'হরাইজন্টাল স্পেস',
img2Button: 'Do you want to transform the selected image on a image button?', // MISSING
infoTab: 'ছবির তথ্য',
linkTab: 'লিংক',
lockRatio: 'অনুপাত লক কর',
menu: 'ছবির প্রোপার্টি',
resetSize: 'সাইজ পূর্বাবস্থায় ফিরিয়ে দাও',
title: 'ছবির প্রোপার্টি',
titleButton: 'ছবির বাটন সম্বন্ধীয়',
upload: 'আপলোড',
urlMissing: 'Image source URL is missing.', // MISSING
vSpace: 'ভার্টিকেল স্পেস',
validateBorder: 'Border must be a whole number.', // MISSING
validateHSpace: 'HSpace must be a whole number.', // MISSING
validateVSpace: 'VSpace must be a whole number.' // MISSING
} );
| gpl-2.0 |
pdebuyl/lammps | lib/kokkos/core/unit_test/TestAtomicOperations_longint.hpp | 3602 | /*
//@HEADER
// ************************************************************************
//
// Kokkos v. 2.0
// Copyright (2014) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA 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 SANDIA CORPORATION OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#include<TestAtomicOperations.hpp>
namespace Test {
TEST_F( TEST_CATEGORY , atomic_operations_long )
{
const int start = 1; // Avoid zero for division.
const int end = 11;
for ( int i = start; i < end; ++i )
{
ASSERT_TRUE( ( TestAtomicOperations::AtomicOperationsTestIntegralType< long int, TEST_EXECSPACE >( start, end - i, 1 ) ) );
ASSERT_TRUE( ( TestAtomicOperations::AtomicOperationsTestIntegralType< long int, TEST_EXECSPACE >( start, end - i, 2 ) ) );
ASSERT_TRUE( ( TestAtomicOperations::AtomicOperationsTestIntegralType< long int, TEST_EXECSPACE >( start, end - i, 3 ) ) );
ASSERT_TRUE( ( TestAtomicOperations::AtomicOperationsTestIntegralType< long int, TEST_EXECSPACE >( start, end - i, 4 ) ) );
ASSERT_TRUE( ( TestAtomicOperations::AtomicOperationsTestIntegralType< long int, TEST_EXECSPACE >( start, end - i, 5 ) ) );
ASSERT_TRUE( ( TestAtomicOperations::AtomicOperationsTestIntegralType< long int, TEST_EXECSPACE >( start, end - i, 6 ) ) );
ASSERT_TRUE( ( TestAtomicOperations::AtomicOperationsTestIntegralType< long int, TEST_EXECSPACE >( start, end - i, 7 ) ) );
ASSERT_TRUE( ( TestAtomicOperations::AtomicOperationsTestIntegralType< long int, TEST_EXECSPACE >( start, end - i, 8 ) ) );
ASSERT_TRUE( ( TestAtomicOperations::AtomicOperationsTestIntegralType< long int, TEST_EXECSPACE >( start, end - i, 9 ) ) );
ASSERT_TRUE( ( TestAtomicOperations::AtomicOperationsTestIntegralType< long int, TEST_EXECSPACE >( start, end - i, 11 ) ) );
ASSERT_TRUE( ( TestAtomicOperations::AtomicOperationsTestIntegralType< long int, TEST_EXECSPACE >( start, end - i, 12 ) ) );
}
}
}
| gpl-2.0 |
joshpfosi/gbn | .waf-1.8.12-f00e5b53f6bbeab1384a38c9cc5d51f7/waflib/Tools/c_config.py | 23239 | #! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file
import os,re,shlex,sys
from waflib import Build,Utils,Task,Options,Logs,Errors,Runner
from waflib.TaskGen import after_method,feature
from waflib.Configure import conf
WAF_CONFIG_H='config.h'
DEFKEYS='define_key'
INCKEYS='include_key'
cfg_ver={'atleast-version':'>=','exact-version':'==','max-version':'<=',}
SNIP_FUNCTION='''
int main(int argc, char **argv) {
void *p;
(void)argc; (void)argv;
p=(void*)(%s);
return (int)p;
}
'''
SNIP_TYPE='''
int main(int argc, char **argv) {
(void)argc; (void)argv;
if ((%(type_name)s *) 0) return 0;
if (sizeof (%(type_name)s)) return 0;
return 1;
}
'''
SNIP_EMPTY_PROGRAM='''
int main(int argc, char **argv) {
(void)argc; (void)argv;
return 0;
}
'''
SNIP_FIELD='''
int main(int argc, char **argv) {
char *off;
(void)argc; (void)argv;
off = (char*) &((%(type_name)s*)0)->%(field_name)s;
return (size_t) off < sizeof(%(type_name)s);
}
'''
MACRO_TO_DESTOS={'__linux__':'linux','__GNU__':'gnu','__FreeBSD__':'freebsd','__NetBSD__':'netbsd','__OpenBSD__':'openbsd','__sun':'sunos','__hpux':'hpux','__sgi':'irix','_AIX':'aix','__CYGWIN__':'cygwin','__MSYS__':'cygwin','_UWIN':'uwin','_WIN64':'win32','_WIN32':'win32','__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__':'darwin','__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__':'darwin','__QNX__':'qnx','__native_client__':'nacl'}
MACRO_TO_DEST_CPU={'__x86_64__':'x86_64','__amd64__':'x86_64','__i386__':'x86','__ia64__':'ia','__mips__':'mips','__sparc__':'sparc','__alpha__':'alpha','__aarch64__':'aarch64','__thumb__':'thumb','__arm__':'arm','__hppa__':'hppa','__powerpc__':'powerpc','__ppc__':'powerpc','__convex__':'convex','__m68k__':'m68k','__s390x__':'s390x','__s390__':'s390','__sh__':'sh',}
@conf
def parse_flags(self,line,uselib_store,env=None,force_static=False,posix=None):
assert(isinstance(line,str))
env=env or self.env
if posix is None:
posix=True
if'\\'in line:
posix=('\\ 'in line)or('\\\\'in line)
lex=shlex.shlex(line,posix=posix)
lex.whitespace_split=True
lex.commenters=''
lst=list(lex)
app=env.append_value
appu=env.append_unique
uselib=uselib_store
static=False
while lst:
x=lst.pop(0)
st=x[:2]
ot=x[2:]
if st=='-I'or st=='/I':
if not ot:ot=lst.pop(0)
appu('INCLUDES_'+uselib,[ot])
elif st=='-i':
tmp=[x,lst.pop(0)]
app('CFLAGS',tmp)
app('CXXFLAGS',tmp)
elif st=='-D'or(env.CXX_NAME=='msvc'and st=='/D'):
if not ot:ot=lst.pop(0)
app('DEFINES_'+uselib,[ot])
elif st=='-l':
if not ot:ot=lst.pop(0)
prefix=(force_static or static)and'STLIB_'or'LIB_'
appu(prefix+uselib,[ot])
elif st=='-L':
if not ot:ot=lst.pop(0)
prefix=(force_static or static)and'STLIBPATH_'or'LIBPATH_'
appu(prefix+uselib,[ot])
elif x.startswith('/LIBPATH:'):
prefix=(force_static or static)and'STLIBPATH_'or'LIBPATH_'
appu(prefix+uselib,[x.replace('/LIBPATH:','')])
elif x=='-pthread'or x.startswith('+')or x.startswith('-std'):
app('CFLAGS_'+uselib,[x])
app('CXXFLAGS_'+uselib,[x])
app('LINKFLAGS_'+uselib,[x])
elif x=='-framework':
appu('FRAMEWORK_'+uselib,[lst.pop(0)])
elif x.startswith('-F'):
appu('FRAMEWORKPATH_'+uselib,[x[2:]])
elif x=='-Wl,-rpath'or x=='-Wl,-R':
app('RPATH_'+uselib,lst.pop(0).lstrip('-Wl,'))
elif x.startswith('-Wl,-R,'):
app('RPATH_'+uselib,x[7:])
elif x.startswith('-Wl,-R'):
app('RPATH_'+uselib,x[6:])
elif x.startswith('-Wl,-rpath,'):
app('RPATH_'+uselib,x[11:])
elif x=='-Wl,-Bstatic'or x=='-Bstatic':
static=True
elif x=='-Wl,-Bdynamic'or x=='-Bdynamic':
static=False
elif x.startswith('-Wl'):
app('LINKFLAGS_'+uselib,[x])
elif x.startswith('-m')or x.startswith('-f')or x.startswith('-dynamic'):
app('CFLAGS_'+uselib,[x])
app('CXXFLAGS_'+uselib,[x])
elif x.startswith('-bundle'):
app('LINKFLAGS_'+uselib,[x])
elif x.startswith('-undefined')or x.startswith('-Xlinker'):
arg=lst.pop(0)
app('LINKFLAGS_'+uselib,[x,arg])
elif x.startswith('-arch')or x.startswith('-isysroot'):
tmp=[x,lst.pop(0)]
app('CFLAGS_'+uselib,tmp)
app('CXXFLAGS_'+uselib,tmp)
app('LINKFLAGS_'+uselib,tmp)
elif x.endswith('.a')or x.endswith('.so')or x.endswith('.dylib')or x.endswith('.lib'):
appu('LINKFLAGS_'+uselib,[x])
@conf
def validate_cfg(self,kw):
if not'path'in kw:
if not self.env.PKGCONFIG:
self.find_program('pkg-config',var='PKGCONFIG')
kw['path']=self.env.PKGCONFIG
if'atleast_pkgconfig_version'in kw:
if not'msg'in kw:
kw['msg']='Checking for pkg-config version >= %r'%kw['atleast_pkgconfig_version']
return
if not'okmsg'in kw:
kw['okmsg']='yes'
if not'errmsg'in kw:
kw['errmsg']='not found'
if'modversion'in kw:
if not'msg'in kw:
kw['msg']='Checking for %r version'%kw['modversion']
return
for x in cfg_ver.keys():
y=x.replace('-','_')
if y in kw:
if not'package'in kw:
raise ValueError('%s requires a package'%x)
if not'msg'in kw:
kw['msg']='Checking for %r %s %s'%(kw['package'],cfg_ver[x],kw[y])
return
if not'define_name'in kw:
pkgname=kw.get('uselib_store',kw['package'].upper())
kw['define_name']=self.have_define(pkgname)
if not'uselib_store'in kw:
self.undefine(kw['define_name'])
if not'msg'in kw:
kw['msg']='Checking for %r'%(kw['package']or kw['path'])
@conf
def exec_cfg(self,kw):
path=Utils.to_list(kw['path'])
def define_it():
pkgname=kw.get('uselib_store',kw['package'].upper())
if kw.get('global_define'):
self.define(self.have_define(kw['package']),1,False)
else:
self.env.append_unique('DEFINES_%s'%pkgname,"%s=1"%self.have_define(pkgname))
self.env[self.have_define(pkgname)]=1
if'atleast_pkgconfig_version'in kw:
cmd=path+['--atleast-pkgconfig-version=%s'%kw['atleast_pkgconfig_version']]
self.cmd_and_log(cmd)
if not'okmsg'in kw:
kw['okmsg']='yes'
return
for x in cfg_ver:
y=x.replace('-','_')
if y in kw:
self.cmd_and_log(path+['--%s=%s'%(x,kw[y]),kw['package']])
if not'okmsg'in kw:
kw['okmsg']='yes'
define_it()
break
if'modversion'in kw:
version=self.cmd_and_log(path+['--modversion',kw['modversion']]).strip()
self.define('%s_VERSION'%Utils.quote_define_name(kw.get('uselib_store',kw['modversion'])),version)
return version
lst=[]+path
defi=kw.get('define_variable',None)
if not defi:
defi=self.env.PKG_CONFIG_DEFINES or{}
for key,val in defi.items():
lst.append('--define-variable=%s=%s'%(key,val))
static=kw.get('force_static',False)
if'args'in kw:
args=Utils.to_list(kw['args'])
if'--static'in args or'--static-libs'in args:
static=True
lst+=args
lst.extend(Utils.to_list(kw['package']))
if'variables'in kw:
env=kw.get('env',self.env)
uselib=kw.get('uselib_store',kw['package'].upper())
vars=Utils.to_list(kw['variables'])
for v in vars:
val=self.cmd_and_log(lst+['--variable='+v]).strip()
var='%s_%s'%(uselib,v)
env[var]=val
if not'okmsg'in kw:
kw['okmsg']='yes'
return
ret=self.cmd_and_log(lst)
if not'okmsg'in kw:
kw['okmsg']='yes'
define_it()
self.parse_flags(ret,kw.get('uselib_store',kw['package'].upper()),kw.get('env',self.env),force_static=static,posix=kw.get('posix',None))
return ret
@conf
def check_cfg(self,*k,**kw):
if k:
lst=k[0].split()
kw['package']=lst[0]
kw['args']=' '.join(lst[1:])
self.validate_cfg(kw)
if'msg'in kw:
self.start_msg(kw['msg'],**kw)
ret=None
try:
ret=self.exec_cfg(kw)
except self.errors.WafError:
if'errmsg'in kw:
self.end_msg(kw['errmsg'],'YELLOW',**kw)
if Logs.verbose>1:
raise
else:
self.fatal('The configuration failed')
else:
if not ret:
ret=True
kw['success']=ret
if'okmsg'in kw:
self.end_msg(self.ret_msg(kw['okmsg'],kw),**kw)
return ret
def build_fun(bld):
if bld.kw['compile_filename']:
node=bld.srcnode.make_node(bld.kw['compile_filename'])
node.write(bld.kw['code'])
o=bld(features=bld.kw['features'],source=bld.kw['compile_filename'],target='testprog')
for k,v in bld.kw.items():
setattr(o,k,v)
if not bld.kw.get('quiet',None):
bld.conf.to_log("==>\n%s\n<=="%bld.kw['code'])
@conf
def validate_c(self,kw):
if not'build_fun'in kw:
kw['build_fun']=build_fun
if not'env'in kw:
kw['env']=self.env.derive()
env=kw['env']
if not'compiler'in kw and not'features'in kw:
kw['compiler']='c'
if env['CXX_NAME']and Task.classes.get('cxx',None):
kw['compiler']='cxx'
if not self.env['CXX']:
self.fatal('a c++ compiler is required')
else:
if not self.env['CC']:
self.fatal('a c compiler is required')
if not'compile_mode'in kw:
kw['compile_mode']='c'
if'cxx'in Utils.to_list(kw.get('features',[]))or kw.get('compiler','')=='cxx':
kw['compile_mode']='cxx'
if not'type'in kw:
kw['type']='cprogram'
if not'features'in kw:
kw['features']=[kw['compile_mode'],kw['type']]
else:
kw['features']=Utils.to_list(kw['features'])
if not'compile_filename'in kw:
kw['compile_filename']='test.c'+((kw['compile_mode']=='cxx')and'pp'or'')
def to_header(dct):
if'header_name'in dct:
dct=Utils.to_list(dct['header_name'])
return''.join(['#include <%s>\n'%x for x in dct])
return''
if'framework_name'in kw:
fwkname=kw['framework_name']
if not'uselib_store'in kw:
kw['uselib_store']=fwkname.upper()
if not kw.get('no_header',False):
if not'header_name'in kw:
kw['header_name']=[]
fwk='%s/%s.h'%(fwkname,fwkname)
if kw.get('remove_dot_h',None):
fwk=fwk[:-2]
kw['header_name']=Utils.to_list(kw['header_name'])+[fwk]
kw['msg']='Checking for framework %s'%fwkname
kw['framework']=fwkname
if'function_name'in kw:
fu=kw['function_name']
if not'msg'in kw:
kw['msg']='Checking for function %s'%fu
kw['code']=to_header(kw)+SNIP_FUNCTION%fu
if not'uselib_store'in kw:
kw['uselib_store']=fu.upper()
if not'define_name'in kw:
kw['define_name']=self.have_define(fu)
elif'type_name'in kw:
tu=kw['type_name']
if not'header_name'in kw:
kw['header_name']='stdint.h'
if'field_name'in kw:
field=kw['field_name']
kw['code']=to_header(kw)+SNIP_FIELD%{'type_name':tu,'field_name':field}
if not'msg'in kw:
kw['msg']='Checking for field %s in %s'%(field,tu)
if not'define_name'in kw:
kw['define_name']=self.have_define((tu+'_'+field).upper())
else:
kw['code']=to_header(kw)+SNIP_TYPE%{'type_name':tu}
if not'msg'in kw:
kw['msg']='Checking for type %s'%tu
if not'define_name'in kw:
kw['define_name']=self.have_define(tu.upper())
elif'header_name'in kw:
if not'msg'in kw:
kw['msg']='Checking for header %s'%kw['header_name']
l=Utils.to_list(kw['header_name'])
assert len(l)>0,'list of headers in header_name is empty'
kw['code']=to_header(kw)+SNIP_EMPTY_PROGRAM
if not'uselib_store'in kw:
kw['uselib_store']=l[0].upper()
if not'define_name'in kw:
kw['define_name']=self.have_define(l[0])
if'lib'in kw:
if not'msg'in kw:
kw['msg']='Checking for library %s'%kw['lib']
if not'uselib_store'in kw:
kw['uselib_store']=kw['lib'].upper()
if'stlib'in kw:
if not'msg'in kw:
kw['msg']='Checking for static library %s'%kw['stlib']
if not'uselib_store'in kw:
kw['uselib_store']=kw['stlib'].upper()
if'fragment'in kw:
kw['code']=kw['fragment']
if not'msg'in kw:
kw['msg']='Checking for code snippet'
if not'errmsg'in kw:
kw['errmsg']='no'
for(flagsname,flagstype)in(('cxxflags','compiler'),('cflags','compiler'),('linkflags','linker')):
if flagsname in kw:
if not'msg'in kw:
kw['msg']='Checking for %s flags %s'%(flagstype,kw[flagsname])
if not'errmsg'in kw:
kw['errmsg']='no'
if not'execute'in kw:
kw['execute']=False
if kw['execute']:
kw['features'].append('test_exec')
if not'errmsg'in kw:
kw['errmsg']='not found'
if not'okmsg'in kw:
kw['okmsg']='yes'
if not'code'in kw:
kw['code']=SNIP_EMPTY_PROGRAM
if self.env[INCKEYS]:
kw['code']='\n'.join(['#include <%s>'%x for x in self.env[INCKEYS]])+'\n'+kw['code']
if not kw.get('success'):kw['success']=None
if'define_name'in kw:
self.undefine(kw['define_name'])
if not'msg'in kw:
self.fatal('missing "msg" in conf.check(...)')
@conf
def post_check(self,*k,**kw):
is_success=0
if kw['execute']:
if kw['success']is not None:
if kw.get('define_ret',False):
is_success=kw['success']
else:
is_success=(kw['success']==0)
else:
is_success=(kw['success']==0)
if'define_name'in kw:
if'header_name'in kw or'function_name'in kw or'type_name'in kw or'fragment'in kw:
if kw['execute']and kw.get('define_ret',None)and isinstance(is_success,str):
self.define(kw['define_name'],is_success,quote=kw.get('quote',1))
else:
self.define_cond(kw['define_name'],is_success)
else:
self.define_cond(kw['define_name'],is_success)
if'header_name'in kw:
if kw.get('auto_add_header_name',False):
self.env.append_value(INCKEYS,Utils.to_list(kw['header_name']))
if is_success and'uselib_store'in kw:
from waflib.Tools import ccroot
_vars=set([])
for x in kw['features']:
if x in ccroot.USELIB_VARS:
_vars|=ccroot.USELIB_VARS[x]
for k in _vars:
lk=k.lower()
if lk in kw:
val=kw[lk]
if isinstance(val,str):
val=val.rstrip(os.path.sep)
self.env.append_unique(k+'_'+kw['uselib_store'],Utils.to_list(val))
return is_success
@conf
def check(self,*k,**kw):
self.validate_c(kw)
self.start_msg(kw['msg'],**kw)
ret=None
try:
ret=self.run_build(*k,**kw)
except self.errors.ConfigurationError:
self.end_msg(kw['errmsg'],'YELLOW',**kw)
if Logs.verbose>1:
raise
else:
self.fatal('The configuration failed')
else:
kw['success']=ret
ret=self.post_check(*k,**kw)
if not ret:
self.end_msg(kw['errmsg'],'YELLOW',**kw)
self.fatal('The configuration failed %r'%ret)
else:
self.end_msg(self.ret_msg(kw['okmsg'],kw),**kw)
return ret
class test_exec(Task.Task):
color='PINK'
def run(self):
if getattr(self.generator,'rpath',None):
if getattr(self.generator,'define_ret',False):
self.generator.bld.retval=self.generator.bld.cmd_and_log([self.inputs[0].abspath()])
else:
self.generator.bld.retval=self.generator.bld.exec_command([self.inputs[0].abspath()])
else:
env=self.env.env or{}
env.update(dict(os.environ))
for var in('LD_LIBRARY_PATH','DYLD_LIBRARY_PATH','PATH'):
env[var]=self.inputs[0].parent.abspath()+os.path.pathsep+env.get(var,'')
if getattr(self.generator,'define_ret',False):
self.generator.bld.retval=self.generator.bld.cmd_and_log([self.inputs[0].abspath()],env=env)
else:
self.generator.bld.retval=self.generator.bld.exec_command([self.inputs[0].abspath()],env=env)
@feature('test_exec')
@after_method('apply_link')
def test_exec_fun(self):
self.create_task('test_exec',self.link_task.outputs[0])
@conf
def check_cxx(self,*k,**kw):
kw['compiler']='cxx'
return self.check(*k,**kw)
@conf
def check_cc(self,*k,**kw):
kw['compiler']='c'
return self.check(*k,**kw)
@conf
def define(self,key,val,quote=True):
assert key and isinstance(key,str)
if val is True:
val=1
elif val in(False,None):
val=0
if isinstance(val,int)or isinstance(val,float):
s='%s=%s'
else:
s=quote and'%s="%s"'or'%s=%s'
app=s%(key,str(val))
ban=key+'='
lst=self.env['DEFINES']
for x in lst:
if x.startswith(ban):
lst[lst.index(x)]=app
break
else:
self.env.append_value('DEFINES',app)
self.env.append_unique(DEFKEYS,key)
@conf
def undefine(self,key):
assert key and isinstance(key,str)
ban=key+'='
lst=[x for x in self.env['DEFINES']if not x.startswith(ban)]
self.env['DEFINES']=lst
self.env.append_unique(DEFKEYS,key)
@conf
def define_cond(self,key,val):
assert key and isinstance(key,str)
if val:
self.define(key,1)
else:
self.undefine(key)
@conf
def is_defined(self,key):
assert key and isinstance(key,str)
ban=key+'='
for x in self.env['DEFINES']:
if x.startswith(ban):
return True
return False
@conf
def get_define(self,key):
assert key and isinstance(key,str)
ban=key+'='
for x in self.env['DEFINES']:
if x.startswith(ban):
return x[len(ban):]
return None
@conf
def have_define(self,key):
return(self.env.HAVE_PAT or'HAVE_%s')%Utils.quote_define_name(key)
@conf
def write_config_header(self,configfile='',guard='',top=False,defines=True,headers=False,remove=True,define_prefix=''):
if not configfile:configfile=WAF_CONFIG_H
waf_guard=guard or'W_%s_WAF'%Utils.quote_define_name(configfile)
node=top and self.bldnode or self.path.get_bld()
node=node.make_node(configfile)
node.parent.mkdir()
lst=['/* WARNING! All changes made to this file will be lost! */\n']
lst.append('#ifndef %s\n#define %s\n'%(waf_guard,waf_guard))
lst.append(self.get_config_header(defines,headers,define_prefix=define_prefix))
lst.append('\n#endif /* %s */\n'%waf_guard)
node.write('\n'.join(lst))
self.env.append_unique(Build.CFG_FILES,[node.abspath()])
if remove:
for key in self.env[DEFKEYS]:
self.undefine(key)
self.env[DEFKEYS]=[]
@conf
def get_config_header(self,defines=True,headers=False,define_prefix=''):
lst=[]
if headers:
for x in self.env[INCKEYS]:
lst.append('#include <%s>'%x)
if defines:
tbl={}
for k in self.env['DEFINES']:
a,_,b=k.partition('=')
tbl[a]=b
for k in self.env[DEFKEYS]:
try:
txt='#define %s%s %s'%(define_prefix,k,tbl[k])
except KeyError:
txt='/* #undef %s%s */'%(define_prefix,k)
lst.append(txt)
return"\n".join(lst)
@conf
def cc_add_flags(conf):
conf.add_os_flags('CPPFLAGS',dup=False)
conf.add_os_flags('CFLAGS',dup=False)
@conf
def cxx_add_flags(conf):
conf.add_os_flags('CPPFLAGS',dup=False)
conf.add_os_flags('CXXFLAGS',dup=False)
@conf
def link_add_flags(conf):
conf.add_os_flags('LINKFLAGS',dup=False)
conf.add_os_flags('LDFLAGS',dup=False)
@conf
def cc_load_tools(conf):
if not conf.env.DEST_OS:
conf.env.DEST_OS=Utils.unversioned_sys_platform()
conf.load('c')
@conf
def cxx_load_tools(conf):
if not conf.env.DEST_OS:
conf.env.DEST_OS=Utils.unversioned_sys_platform()
conf.load('cxx')
@conf
def get_cc_version(conf,cc,gcc=False,icc=False,clang=False):
cmd=cc+['-dM','-E','-']
env=conf.env.env or None
try:
p=Utils.subprocess.Popen(cmd,stdin=Utils.subprocess.PIPE,stdout=Utils.subprocess.PIPE,stderr=Utils.subprocess.PIPE,env=env)
p.stdin.write('\n')
out=p.communicate()[0]
except Exception:
conf.fatal('Could not determine the compiler version %r'%cmd)
if not isinstance(out,str):
out=out.decode(sys.stdout.encoding or'iso8859-1')
if gcc:
if out.find('__INTEL_COMPILER')>=0:
conf.fatal('The intel compiler pretends to be gcc')
if out.find('__GNUC__')<0 and out.find('__clang__')<0:
conf.fatal('Could not determine the compiler type')
if icc and out.find('__INTEL_COMPILER')<0:
conf.fatal('Not icc/icpc')
if clang and out.find('__clang__')<0:
conf.fatal('Not clang/clang++')
if not clang and out.find('__clang__')>=0:
conf.fatal('Could not find gcc/g++ (only Clang), if renamed try eg: CC=gcc48 CXX=g++48 waf configure')
k={}
if icc or gcc or clang:
out=out.splitlines()
for line in out:
lst=shlex.split(line)
if len(lst)>2:
key=lst[1]
val=lst[2]
k[key]=val
def isD(var):
return var in k
def isT(var):
return var in k and k[var]!='0'
if not conf.env.DEST_OS:
conf.env.DEST_OS=''
for i in MACRO_TO_DESTOS:
if isD(i):
conf.env.DEST_OS=MACRO_TO_DESTOS[i]
break
else:
if isD('__APPLE__')and isD('__MACH__'):
conf.env.DEST_OS='darwin'
elif isD('__unix__'):
conf.env.DEST_OS='generic'
if isD('__ELF__'):
conf.env.DEST_BINFMT='elf'
elif isD('__WINNT__')or isD('__CYGWIN__')or isD('_WIN32'):
conf.env.DEST_BINFMT='pe'
conf.env.LIBDIR=conf.env.BINDIR
elif isD('__APPLE__'):
conf.env.DEST_BINFMT='mac-o'
if not conf.env.DEST_BINFMT:
conf.env.DEST_BINFMT=Utils.destos_to_binfmt(conf.env.DEST_OS)
for i in MACRO_TO_DEST_CPU:
if isD(i):
conf.env.DEST_CPU=MACRO_TO_DEST_CPU[i]
break
Logs.debug('ccroot: dest platform: '+' '.join([conf.env[x]or'?'for x in('DEST_OS','DEST_BINFMT','DEST_CPU')]))
if icc:
ver=k['__INTEL_COMPILER']
conf.env['CC_VERSION']=(ver[:-2],ver[-2],ver[-1])
else:
if isD('__clang__'):
try:
conf.env['CC_VERSION']=(k['__clang_major__'],k['__clang_minor__'],k['__clang_patchlevel__'])
except KeyError:
conf.env['CC_VERSION']=(k['__GNUC__'],k['__GNUC_MINOR__'],k['__GNUC_PATCHLEVEL__'])
else:
try:
conf.env['CC_VERSION']=(k['__GNUC__'],k['__GNUC_MINOR__'],k['__GNUC_PATCHLEVEL__'])
except KeyError:
conf.env['CC_VERSION']=(k['__GNUC__'],k['__GNUC_MINOR__'],0)
return k
@conf
def get_xlc_version(conf,cc):
cmd=cc+['-qversion']
try:
out,err=conf.cmd_and_log(cmd,output=0)
except Errors.WafError:
conf.fatal('Could not find xlc %r'%cmd)
for v in(r"IBM XL C/C\+\+.* V(?P<major>\d*)\.(?P<minor>\d*)",):
version_re=re.compile(v,re.I).search
match=version_re(out or err)
if match:
k=match.groupdict()
conf.env['CC_VERSION']=(k['major'],k['minor'])
break
else:
conf.fatal('Could not determine the XLC version.')
@conf
def get_suncc_version(conf,cc):
cmd=cc+['-V']
try:
out,err=conf.cmd_and_log(cmd,output=0)
except Errors.WafError ,e:
if not(hasattr(e,'returncode')and hasattr(e,'stdout')and hasattr(e,'stderr')):
conf.fatal('Could not find suncc %r'%cmd)
out=e.stdout
err=e.stderr
version=(out or err)
version=version.splitlines()[0]
version_re=re.compile(r'cc:\s+sun\s+(c\+\+|c)\s+(?P<major>\d*)\.(?P<minor>\d*)',re.I).search
match=version_re(version)
if match:
k=match.groupdict()
conf.env['CC_VERSION']=(k['major'],k['minor'])
else:
conf.fatal('Could not determine the suncc version.')
@conf
def add_as_needed(self):
if self.env.DEST_BINFMT=='elf'and'gcc'in(self.env.CXX_NAME,self.env.CC_NAME):
self.env.append_unique('LINKFLAGS','-Wl,--as-needed')
class cfgtask(Task.TaskBase):
def display(self):
return''
def runnable_status(self):
return Task.RUN_ME
def uid(self):
return Utils.SIG_NIL
def run(self):
conf=self.conf
bld=Build.BuildContext(top_dir=conf.srcnode.abspath(),out_dir=conf.bldnode.abspath())
bld.env=conf.env
bld.init_dirs()
bld.in_msg=1
bld.logger=self.logger
try:
bld.check(**self.args)
except Exception:
return 1
@conf
def multicheck(self,*k,**kw):
self.start_msg(kw.get('msg','Executing %d configuration tests'%len(k)),**kw)
class par(object):
def __init__(self):
self.keep=False
self.returned_tasks=[]
self.task_sigs={}
self.progress_bar=0
def total(self):
return len(tasks)
def to_log(self,*k,**kw):
return
bld=par()
tasks=[]
for dct in k:
x=cfgtask(bld=bld)
tasks.append(x)
x.args=dct
x.bld=bld
x.conf=self
x.args=dct
x.logger=Logs.make_mem_logger(str(id(x)),self.logger)
def it():
yield tasks
while 1:
yield[]
p=Runner.Parallel(bld,Options.options.jobs)
p.biter=it()
p.start()
for x in tasks:
x.logger.memhandler.flush()
if p.error:
for x in p.error:
if getattr(x,'err_msg',None):
self.to_log(x.err_msg)
self.end_msg('fail',color='RED')
raise Errors.WafError('There is an error in the library, read config.log for more information')
for x in tasks:
if x.hasrun!=Task.SUCCESS:
self.end_msg(kw.get('errmsg','no'),color='YELLOW',**kw)
self.fatal(kw.get('fatalmsg',None)or'One of the tests has failed, read config.log for more information')
self.end_msg('ok',**kw)
| gpl-2.0 |
fritsch/xbmc | xbmc/interfaces/python/PyContext.cpp | 3420 | /*
* Copyright (C) 2005-2013 Team XBMC
* http://kodi.tv
*
* 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, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include <Python.h>
#include "PyContext.h"
#include "utils/log.h"
namespace XBMCAddon
{
namespace Python
{
struct PyContextState
{
inline explicit PyContextState(bool pcreatedByGilRelease = false) :
value(0), state(NULL), gilReleasedDepth(0), createdByGilRelease(pcreatedByGilRelease) {}
int value;
PyThreadState* state;
int gilReleasedDepth;
bool createdByGilRelease;
};
static thread_local PyContextState* tlsPyContextState;
void* PyContext::enterContext()
{
PyContextState* cur = tlsPyContextState;
if (cur == NULL)
{
cur = new PyContextState();
tlsPyContextState = cur;
}
// increment the count
cur->value++;
return cur;
}
void PyContext::leaveContext()
{
// here we ASSUME that the constructor was called.
PyContextState* cur = tlsPyContextState;
cur->value--;
int curlevel = cur->value;
// this is a hack but ...
if (curlevel < 0)
{
CLog::Log(LOGERROR, "FATAL: PyContext closed more than opened");
curlevel = cur->value = 0;
}
if (curlevel == 0)
{
// clear the tlsPyContextState
tlsPyContextState = NULL;
delete cur;
}
}
void PyGILLock::releaseGil()
{
PyContextState* cur = tlsPyContextState;
// This means we're not within the python context, but
// because we may be in a thread spawned by python itself,
// we need to handle this.
if (!cur)
{
cur = static_cast<PyContextState*>(PyContext::enterContext());
cur->createdByGilRelease = true;
}
if (cur->gilReleasedDepth == 0) // true if we are at the outermost
{
PyThreadState* _save;
// this macro sets _save
{
Py_UNBLOCK_THREADS
}
cur->state = _save;
}
cur->gilReleasedDepth++; // the first time this goes to 1
}
void PyGILLock::acquireGil()
{
PyContextState* cur = tlsPyContextState;
// it's not possible for cur to be NULL (and if it is, we want to fail anyway).
// decrement the depth and make sure we're in the right place.
cur->gilReleasedDepth--;
if (cur->gilReleasedDepth == 0) // are we back to zero?
{
PyThreadState* _save = cur->state;
// This macros uses _save
{
Py_BLOCK_THREADS
}
cur->state = NULL; // clear the state to indicate we've reacquired the gil
// we clear it only if we created it on this level.
if (cur->createdByGilRelease)
PyContext::leaveContext();
}
}
}
}
| gpl-2.0 |
andyhebear/DOLSharp | GameServer/propertycalc/EnduranceRegenerationRateCalculator.cs | 3013 | /*
* DAWN OF LIGHT - The first free open source DAoC server emulator
*
* 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.
*
*/
using System;
namespace DOL.GS.PropertyCalc
{
/// <summary>
/// The health regen rate calculator
///
/// BuffBonusCategory1 is used for all buffs
/// BuffBonusCategory2 is used for all debuffs (positive values expected here)
/// BuffBonusCategory3 unused
/// BuffBonusCategory4 unused
/// BuffBonusMultCategory1 unused
/// </summary>
[PropertyCalculator(eProperty.EnduranceRegenerationRate)]
public class EnduranceRegenerationRateCalculator : PropertyCalculator
{
public EnduranceRegenerationRateCalculator() {}
/// <summary>
/// calculates the final property value
/// </summary>
/// <param name="living"></param>
/// <param name="property"></param>
/// <returns></returns>
public override int CalcValue(GameLiving living, eProperty property)
{
int debuff = living.SpecBuffBonusCategory[(int)property];
if (debuff < 0)
debuff = -debuff;
// buffs allow to regenerate endurance even in combat and while moving
double regen =
living.BaseBuffBonusCategory[(int)property]
+living.ItemBonus[(int)property];
if (regen == 0 && living is GamePlayer) //&& ((GamePlayer)living).HasAbility(Abilities.Tireless))
regen++;
/* Patch 1.87 - COMBAT AND REGENERATION CHANGES
- The bonus to regeneration while standing out of combat has been greatly increased. The amount of ticks
a player receives while standing has been doubled and it will now match the bonus to regeneration while sitting.
Players will no longer need to sit to regenerate faster.
- Fatigue now regenerates at the standing rate while moving.
*/
if (!living.InCombat)
{
if (living is GamePlayer)
{
if (!((GamePlayer)living).IsSprinting)
{
regen += 4;
}
}
}
regen -= debuff;
if (regen < 0)
regen = 0;
if (regen != 0 && ServerProperties.Properties.ENDURANCE_REGEN_RATE != 1)
regen *= ServerProperties.Properties.ENDURANCE_REGEN_RATE;
double decimals = regen - (int)regen;
if (Util.ChanceDouble(decimals))
{
regen += 1; // compensate int rounding error
}
return (int)regen;
}
}
}
| gpl-2.0 |
ohnmarsoe/uverworld | data/class/SC_SmartphoneUserAgent.php | 2032 | <?php
/*
* This file is part of EC-CUBE
*
* Copyright(c) 2000-2012 LOCKON CO.,LTD. All Rights Reserved.
*
* http://www.lockon.co.jp/
*
* 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.
*/
/**
* スマートフォンの情報を扱うクラス.
*
* @auther Yu Nobira
*/
class SC_SmartphoneUserAgent {
/**
* スマートフォンかどうかを判別する。
* $_SESSION['pc_disp'] = true の場合はPC表示。
*
* @return boolean
*/
function isSmartphone() {
$nu = new Net_UserAgent_Mobile();
// SPでかつPC表示OFFの場合
return $nu->isSmartphone() && !SC_SmartphoneUserAgent_Ex::getSmartphonePcFlag();
}
/**
* スマートフォンかどうかを判別する。
*
* @return boolean
*/
function isNonSmartphone() {
return !SC_SmartphoneUserAgent_Ex::isSmartphone();
}
/**
* PC表示フラグの取得
*
* @return string
*/
function getSmartphonePcFlag() {
$_SESSION['pc_disp'] = empty($_SESSION['pc_disp']) ? false : $_SESSION['pc_disp'];
return $_SESSION['pc_disp'];
}
/**
* PC表示ON
*/
function setPcDisplayOn() {
$_SESSION['pc_disp'] = true;
}
/**
* PC表示OFF
*/
function setPcDisplayOff() {
$_SESSION['pc_disp'] = false;
}
}
| gpl-2.0 |
phenix-factory/fci-obedience | plugins-dist/compresseur/lib/csstidy/testing/unit-tests.php | 1441 | <?php
/**@file
* Script for unit testing, allows for more fine grained error reporting
* when things go wrong.
* @author Edward Z. Yang <admin@htmlpurifier.org>
*
* Required
* unit-tets/Text : http://download.pear.php.net/package/Text_Diff-1.1.1.tgz
* unit-tests/simpletest/ : http://downloads.sourceforge.net/project/simpletest/simpletest/simpletest_1.0.1/simpletest_1.0.1.tar.gz?r=&ts=1289748853&use_mirror=freefr
*
*/
error_reporting(E_ALL ^ 8192/*E_DEPRECATED*/);
// Configuration
$simpletest_location = 'simpletest/';
if (file_exists('../test-settings.php')) include_once '../test-settings.php';
// Includes
require_once '../class.csstidy.php';
require_once 'Text/Diff.php';
require_once 'Text/Diff/Renderer.php';
require_once $simpletest_location . 'unit_tester.php';
require_once $simpletest_location . 'reporter.php';
require_once 'unit-tests/class.csstidy_reporter.php';
require_once 'unit-tests/class.csstidy_harness.php';
require_once 'unit-tests.inc';
// Test files
$test_files = array();
require 'unit-tests/_files.php';
// Setup test files
$test = new GroupTest('CSSTidy unit tests');
foreach ($test_files as $test_file) {
require_once "unit-tests/$test_file";
list($x, $class_suffix) = explode('.', $test_file);
$test->addTestClass("csstidy_test_$class_suffix");
}
if (SimpleReporter::inCli()) $reporter = new TextReporter();
else $reporter = new csstidy_reporter('UTF-8');
$test->run($reporter);
| gpl-3.0 |
micaelbatista/neeist_wiki | wiki/includes/specials/SpecialResetTokens.php | 3922 | <?php
/**
* Implements Special:ResetTokens
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup SpecialPage
*/
/**
* Let users reset tokens like the watchlist token.
*
* @ingroup SpecialPage
* @deprecated since 1.26
*/
class SpecialResetTokens extends FormSpecialPage {
private $tokensList;
public function __construct() {
parent::__construct( 'ResetTokens' );
}
public function doesWrites() {
return true;
}
/**
* Returns the token information list for this page after running
* the hook and filtering out disabled preferences.
*
* @return array
*/
protected function getTokensList() {
if ( !isset( $this->tokensList ) ) {
$tokens = [
[ 'preference' => 'watchlisttoken', 'label-message' => 'resettokens-watchlist-token' ],
];
Hooks::run( 'SpecialResetTokensTokens', [ &$tokens ] );
$hiddenPrefs = $this->getConfig()->get( 'HiddenPrefs' );
$tokens = array_filter( $tokens, function ( $tok ) use ( $hiddenPrefs ) {
return !in_array( $tok['preference'], $hiddenPrefs );
} );
$this->tokensList = $tokens;
}
return $this->tokensList;
}
public function execute( $par ) {
// This is a preferences page, so no user JS for y'all.
$this->getOutput()->disallowUserJs();
$this->requireLogin();
parent::execute( $par );
$this->getOutput()->addReturnTo( SpecialPage::getTitleFor( 'Preferences' ) );
}
public function onSuccess() {
$this->getOutput()->wrapWikiMsg(
"<div class='successbox'>\n$1\n</div>",
'resettokens-done'
);
}
/**
* Display appropriate message if there's nothing to do.
* The submit button is also suppressed in this case (see alterForm()).
* @return array
*/
protected function getFormFields() {
$user = $this->getUser();
$tokens = $this->getTokensList();
if ( $tokens ) {
$tokensForForm = [];
foreach ( $tokens as $tok ) {
$label = $this->msg( 'resettokens-token-label' )
->rawParams( $this->msg( $tok['label-message'] )->parse() )
->params( $user->getTokenFromOption( $tok['preference'] ) )
->escaped();
$tokensForForm[$label] = $tok['preference'];
}
$desc = [
'label-message' => 'resettokens-tokens',
'type' => 'multiselect',
'options' => $tokensForForm,
];
} else {
$desc = [
'label-message' => 'resettokens-no-tokens',
'type' => 'info',
];
}
return [
'tokens' => $desc,
];
}
/**
* Suppress the submit button if there's nothing to do;
* provide additional message on it otherwise.
* @param HTMLForm $form
*/
protected function alterForm( HTMLForm $form ) {
if ( $this->getTokensList() ) {
$form->setSubmitTextMsg( 'resettokens-resetbutton' );
} else {
$form->suppressDefaultSubmit();
}
}
protected function getDisplayFormat() {
return 'ooui';
}
public function onSubmit( array $formData ) {
if ( $formData['tokens'] ) {
$user = $this->getUser();
foreach ( $formData['tokens'] as $tokenPref ) {
$user->resetTokenFromOption( $tokenPref );
}
$user->saveSettings();
return true;
}
return false;
}
protected function getGroupName() {
return 'users';
}
public function isListed() {
return (bool)$this->getTokensList();
}
}
| gpl-3.0 |
ahmedsalahos/livemega | vqmod/vqmod.php | 26086 | <?php
/**
* VQMod
* @description Main Object used
*/
abstract class VQMod {
public static $_vqversion = '2.5.1'; // Current version number
private static $_modFileList = array(); // Array of xml files
private static $_mods = array(); // Array of modifications to apply
private static $_filesModded = array(); // Array of already modified files
private static $_doNotMod = array(); // Array of files not to apply modifications to
private static $_cwd = ''; // Current working directory path
private static $_folderChecks = false; // Flag for already checked log/cache folders exist
private static $_cachePathFull = ''; // Full cache folder path
private static $_lastModifiedTime = 0; // Integer representing the last time anything was modified
private static $_devMode = false; // Flag for developer mode - disables caching while true
public static $logFolder = 'vqmod/logs/'; // Path log folders are stored in
public static $vqCachePath = 'vqmod/vqcache/'; // Relative path to cache file directory
public static $modCache = 'vqmod/mods.cache'; // Relative path to serialized mods array cache file
public static $checkedCache = 'vqmod/checked.cache'; // Relative path to already checked files array cache file
public static $protectedFilelist = 'vqmod/vqprotect.txt'; // Relative path to protected files array cache file
public static $pathReplaces = 'vqmod/pathReplaces.php'; // Relative path to dynamic path replacement file
public static $logging = true; // Flag to enabled/disable logging
public static $log; // Log object reference
public static $fileModding = false; // Reference to the current file being modified by vQmod for logging
public static $directorySeparator = ''; // System directory separator (/ or \ depending on OS)
public static $replaces = array(); // Array of regex replaces to perform on file paths
public static $windows = false; // Flag determining if windows or *nix based
/**
* VQMod::bootup()
*
* @param bool $path File path to use
* @param bool $logging Enable/disabled logging
* @return null
* @description Startup of VQMod
*/
public static function bootup($path = false, $logging = true) {
if(!class_exists('DOMDocument')) {
die('VQMod::bootup - ERROR - YOU NEED THE PHP "DOMDocument" EXTENSION INSTALLED TO USE VQMod');
}
if(strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
self::$windows = true;
}
self::$directorySeparator = defined('DIRECTORY_SEPARATOR') ? DIRECTORY_SEPARATOR : '/';
if(!$path){
$path = dirname(dirname(__FILE__));
}
self::_setCwd($path);
self::$logging = (bool) $logging;
self::$log = new VQModLog();
$replacesPath = self::path(self::$pathReplaces);
$replaces = array();
if($replacesPath) {
include_once($replacesPath);
self::$_lastModifiedTime = filemtime($replacesPath);
}
self::$replaces = !is_array($replaces) ? array() : $replaces;
self::_getMods();
self::_loadProtected();
self::_loadChecked();
}
/**
* VQMod::modCheck()
*
* @param string $sourceFile path for file to be modified
* @param string $modificationFile path for mods to be applied to file
* @return string
* @description Checks if a file has modifications and applies them, returning cache files or the file name
*/
public static function modCheck($sourceFile, $modificationFile = false) {
if(!self::$_folderChecks) {
if(self::$logging) {
// Create log folder if it doesn't exist
$log_folder = self::path(self::$logFolder, true);
self::dirCheck($log_folder);
}
// Create cache folder if it doesn't exist
$cache_folder = self::path(self::$vqCachePath, true);
self::dirCheck($cache_folder);
// Store cache folder path to save on repeat checks for path validity
self::$_cachePathFull = self::path(self::$vqCachePath);
self::$_folderChecks = true;
}
if(!preg_match('%^([a-z]:)?[\\\\/]%i', $sourceFile)) {
$sourcePath = self::path($sourceFile);
} else {
$sourcePath = self::_realpath($sourceFile);
}
if($modificationFile !== false) {
if(!preg_match('%^([a-z]:)?[\\\\/]%i', $modificationFile)) {
$modificationsPath = self::path($modificationFile);
} else {
$modificationsPath = self::_realpath($modificationFile);
}
} else {
$modificationsPath = $sourcePath;
}
if(!$sourcePath || is_dir($sourcePath) || in_array($sourcePath, self::$_doNotMod)) {
return $sourceFile;
}
$stripped_filename = preg_replace('~^' . preg_quote(self::getCwd(), '~i') . '~', '', $sourcePath);
$cacheFile = self::_cacheName($stripped_filename);
$file_last_modified = filemtime($sourcePath);
if(file_exists($cacheFile) && filemtime($cacheFile) >= self::$_lastModifiedTime && filemtime($cacheFile) >= $file_last_modified) {
return $cacheFile;
}
if(isset(self::$_filesModded[$sourcePath])) {
return self::$_filesModded[$sourcePath]['cached'] ? $cacheFile : $sourceFile;
}
$changed = false;
$fileHash = sha1_file($sourcePath);
$fileData = file_get_contents($sourcePath);
foreach(self::$_mods as $modObject) {
foreach($modObject->mods as $path => $mods) {
if(self::_checkMatch($path, $modificationsPath)) {
$modObject->applyMod($mods, $fileData);
}
}
}
if (sha1($fileData) != $fileHash) {
$writePath = $cacheFile;
if(!file_exists($writePath) || is_writable($writePath)) {
file_put_contents($writePath, $fileData, LOCK_EX);
$changed = true;
}
} else {
file_put_contents(self::path(self::$checkedCache, true), $stripped_filename . PHP_EOL, FILE_APPEND | LOCK_EX);
self::$_doNotMod[] = $sourcePath;
}
self::$_filesModded[$sourcePath] = array('cached' => $changed);
return $changed ? $writePath : $sourcePath;
}
/**
* VQMod::path()
*
* @param string $path File path
* @param bool $skip_real If true path is full not relative
* @return bool, string
* @description Returns the full true path of a file if it exists, otherwise false
*/
public static function path($path, $skip_real = false) {
$tmp = self::$_cwd . $path;
$realpath = $skip_real ? $tmp : self::_realpath($tmp);
if(!$realpath) {
return false;
}
return $realpath;
}
/**
* VQMod::getCwd()
*
* @return string
* @description Returns current working directory
*/
public static function getCwd() {
return self::$_cwd;
}
/**
* VQMod::dirCheck()
*
* @param string $path
* @return null
* @description Creates $path folder if it doesn't exist
*/
public static function dirCheck($path) {
if(!is_dir($path)) {
if(!mkdir($path)) {
die('VQMod::dirCheck - CANNOT CREATE "' . $path . '" DIRECTORY');
}
}
}
/**
* VQMod::handleXMLError()
*
* @description Error handler for bad XML files
*/
public static function handleXMLError($errno, $errstr, $errfile, $errline) {
if ($errno == E_WARNING && (substr_count($errstr, 'DOMDocument::load()') > 0)) {
throw new DOMException(str_replace('DOMDocument::load()', '', $errstr));
} else {
return false;
}
}
/**
* VQMod::_getMods()
*
* @return null
* @description Gets list of XML files in vqmod xml folder for processing
*/
private static function _getMods() {
self::$_modFileList = glob(self::path('vqmod/xml/', true) . '*.xml');
foreach(self::$_modFileList as $file) {
if(file_exists($file)) {
$lastMod = filemtime($file);
if($lastMod > self::$_lastModifiedTime){
self::$_lastModifiedTime = $lastMod;
}
}
}
$xml_folder_time = filemtime(self::path('vqmod/xml'));
if($xml_folder_time > self::$_lastModifiedTime){
self::$_lastModifiedTime = $xml_folder_time;
}
$modCache = self::path(self::$modCache);
if(self::$_devMode || !file_exists($modCache)) {
self::$_lastModifiedTime = time();
} elseif(file_exists($modCache) && filemtime($modCache) >= self::$_lastModifiedTime) {
$mods = file_get_contents($modCache);
if(!empty($mods))
self::$_mods = unserialize($mods);
if(self::$_mods !== false) {
return;
}
}
// Clear checked cache if rebuilding
file_put_contents(self::path(self::$checkedCache, true), '', LOCK_EX);
if(self::$_modFileList) {
self::_parseMods();
} else {
self::$log->write('VQMod::_getMods - NO XML FILES READABLE IN XML FOLDER');
}
}
/**
* VQMod::_parseMods()
*
* @return null
* @description Loops through xml files and attempts to load them as VQModObject's
*/
private static function _parseMods() {
set_error_handler(array('VQMod', 'handleXMLError'));
$dom = new DOMDocument('1.0', 'UTF-8');
foreach(self::$_modFileList as $modFileKey => $modFile) {
if(file_exists($modFile)) {
try {
$dom->load($modFile);
$mod = $dom->getElementsByTagName('modification')->item(0);
$vqmver = $mod->getElementsByTagName('vqmver')->item(0);
if($vqmver) {
$version_check = $vqmver->getAttribute('required');
if(strtolower($version_check) == 'true') {
if(version_compare(self::$_vqversion, $vqmver->nodeValue, '<')) {
self::$log->write('VQMod::_parseMods - FILE "' . $modFile . '" REQUIRES VQMOD "' . $vqmver->nodeValue . '" OR ABOVE AND HAS BEEN SKIPPED');
continue;
}
}
}
self::$_mods[] = new VQModObject($mod, $modFile);
} catch (Exception $e) {
self::$log->write('VQMod::_parseMods - INVALID XML FILE: ' . $e->getMessage());
}
} else {
self::$log->write('VQMod::_parseMods - FILE NOT FOUND: ' . $modFile);
}
}
restore_error_handler();
$modCache = self::path(self::$modCache, true);
$result = file_put_contents($modCache, serialize(self::$_mods), LOCK_EX);
if(!$result) {
die('VQMod::_parseMods - "/vqmod/mods.cache" FILE NOT WRITEABLE');
}
}
/**
* VQMod::_loadProtected()
*
* @return null
* @description Loads protected list and adds them to _doNotMod array
*/
private static function _loadProtected() {
$file = self::path(self::$protectedFilelist);
if($file && is_file($file)) {
$paths = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if(!empty($paths)) {
foreach($paths as $path) {
$fullPath = self::path($path);
if($fullPath && !in_array($fullPath, self::$_doNotMod)) {
self::$_doNotMod[] = $fullPath;
}
}
}
}
}
/**
* VQMod::_loadChecked()
*
* @return null
* @description Loads already checked files and adds them to _doNotMod array
*/
private static function _loadChecked() {
$file = self::path(self::$checkedCache);
if($file && is_file($file)) {
$paths = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if(!empty($paths)) {
foreach($paths as $path) {
$fullPath = self::path($path, true);
if($fullPath) {
self::$_doNotMod[] = $fullPath;
}
}
}
}
}
/**
* VQMod::_cacheName()
*
* @param string $file Filename to be converted to cache filename
* @return string
* @description Returns cache file name for a path
*/
private static function _cacheName($file) {
return self::$_cachePathFull . 'vq2-' . preg_replace('~[/\\\\]+~', '_', $file);
}
/**
* VQMod::_setCwd()
*
* @param string $path Path to be used as current working directory
* @return null
* @description Sets the current working directory variable
*/
private static function _setCwd($path) {
self::$_cwd = self::_realpath($path);
}
/**
* VQMod::_realpath()
*
* @param string $file
* @return string
* @description Returns real path of any path, adding directory slashes if necessary
*/
private static function _realpath($file) {
$path = realpath($file);
if(!$path) {
return false;
}
if(is_dir($path)) {
$path = rtrim($path, self::$directorySeparator) . self::$directorySeparator;
}
return $path;
}
/**
* VQMod::_checkMatch()
*
* @param string $modFilePath Modification path from a <file> node
* @param string $checkFilePath File path
* @return bool
* @description Checks a modification path against a file path
*/
private static function _checkMatch($modFilePath, $checkFilePath) {
$modFilePath = str_replace('\\', '/', $modFilePath);
$checkFilePath = str_replace('\\', '/', $checkFilePath);
if(self::$windows) {
$modFilePath = strtolower($modFilePath);
$checkFilePath = strtolower($checkFilePath);
}
if($modFilePath == $checkFilePath) {
$return = true;
} elseif(strpos($modFilePath, '*') !== false) {
$return = true;
$modParts = explode('/', $modFilePath);
$checkParts = explode('/', $checkFilePath);
if(count($modParts) !== count($checkParts)) {
$return = false;
} else {
$toCheck = array_diff_assoc($modParts, $checkParts);
foreach($toCheck as $k => $part) {
if($part === '*') {
continue;
} elseif(strpos($part, '*') !== false) {
$part = preg_replace_callback('~([^*]+)~', array('self', '_quotePath'), $part);
$part = str_replace('*', '[^/]*', $part);
$part = (bool) preg_match('~^' . $part . '$~', $checkParts[$k]);
if($part) {
continue;
}
} elseif($part === $checkParts[$k]) {
continue;
}
$return = false;
break;
}
}
} else {
$return = false;
}
return $return;
}
/**
* VQMod::_quotePath()
*
* @param string $matches callback matches
* @return string
* @description apply's preg_quote to string from callback
*/
private static function _quotePath($matches) {
return preg_quote($matches[1], '~');
}
}
/**
* VQModLog
* @description Object to log information to a file
*/
class VQModLog {
private $_sep;
private $_defhash = 'da39a3ee5e6b4b0d3255bfef95601890afd80709';
private $_logs = array();
/**
* VQModLog::__construct()
*
* @return null
* @description Object instantiation method
*/
public function __construct() {
$this->_sep = str_repeat('-', 70);
}
/**
* VQModLog::__destruct()
*
* @return null
* @description Logs any messages to the log file just before object is destroyed
*/
public function __destruct() {
if(empty($this->_logs) || VQMod::$logging == false) {
return;
}
$logPath = VQMod::path(VQMod::$logFolder . date('w_D') . '.log', true);
$txt = array();
$txt[] = str_repeat('-', 10) . ' Date: ' . date('Y-m-d H:i:s') . ' ~ IP : ' . (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'N/A') . ' ' . str_repeat('-', 10);
$txt[] = 'REQUEST URI : ' . $_SERVER['REQUEST_URI'];
foreach($this->_logs as $count => $log) {
if($log['obj']) {
$vars = get_object_vars($log['obj']);
$txt[] = 'MOD DETAILS:';
foreach($vars as $k => $v) {
if(is_string($v)) {
$txt[] = ' ' . str_pad($k, 10, ' ', STR_PAD_RIGHT) . ': ' . $v;
}
}
}
foreach($log['log'] as $msg) {
$txt[] = $msg;
}
if ($count > count($this->_logs)-1) {
$txt[] = '';
}
}
$txt[] = $this->_sep;
$txt[] = str_repeat(PHP_EOL, 2);
$append = true;
if(!file_exists($logPath)) {
$append = false;
} else {
$content = file_get_contents($logPath);
if(!empty($content) && strpos($content, ' Date: ' . date('Y-m-d ')) === false) {
$append = false;
}
}
$result = file_put_contents($logPath, implode(PHP_EOL, $txt), ($append ? FILE_APPEND | LOCK_EX : LOCK_EX));
if(!$result) {
die('VQModLog::__destruct - LOG FILE "' . $logPath . '" COULD NOT BE WRITTEN');
}
}
/**
* VQModLog::write()
*
* @param string $data Text to be added to log file
* @param VQModObject $obj Modification the error belongs to
* @return null
* @description Adds error to log object ready to be output
*/
public function write($data, VQModObject $obj = NULL) {
if($obj) {
$hash = sha1($obj->id);
} else {
$hash = $this->_defhash;
}
if(empty($this->_logs[$hash])) {
$this->_logs[$hash] = array(
'obj' => $obj,
'log' => array()
);
}
if(VQMod::$fileModding) {
$this->_logs[$hash]['log'][] = PHP_EOL . 'File Name : ' . VQMod::$fileModding;
}
$this->_logs[$hash]['log'][] = $data;
}
}
/**
* VQModObject
* @description Object for the <modification> that orchestrates each applied modification
*/
class VQModObject {
public $modFile = '';
public $id = '';
public $version = '';
public $vqmver = '';
public $author = '';
public $mods = array();
private $_skip = false;
/**
* VQModObject::__construct()
*
* @param DOMNode $node <modification> node
* @param string $modFile File modification is from
* @return null
* @description Loads modification meta information
*/
public function __construct(DOMNode $node, $modFile) {
if($node->hasChildNodes()) {
foreach($node->childNodes as $child) {
$name = (string) $child->nodeName;
if(isset($this->$name)) {
$this->$name = (string) $child->nodeValue;
}
}
}
$this->modFile = $modFile;
$this->_parseMods($node);
}
/**
* VQModObject::skip()
*
* @return bool
* @description Returns the skip status of a modification
*/
public function skip() {
return $this->_skip;
}
/**
* VQModObject::applyMod()
*
* @param array $mods Array of search add nodes
* @param string $data File contents to be altered
* @return null
* @description Applies all modifications to the text data
*/
public function applyMod($mods, &$data) {
if($this->_skip) return;
$tmp = $data;
foreach($mods as $mod) {
VQMod::$fileModding = $mod['fileToMod'] . '(' . $mod['opIndex'] . ')';
if(!empty($mod['ignoreif'])) {
if($mod['ignoreif']->regex == 'true') {
if (preg_match($mod['ignoreif']->getContent(), $tmp)) {
continue;
}
} else {
if (strpos($tmp, $mod['ignoreif']->getContent()) !== false) {
continue;
}
}
}
$indexCount = 0;
$tmp = $this->_explodeData($tmp);
$lineMax = count($tmp) - 1;
switch($mod['search']->position) {
case 'top':
$tmp[$mod['search']->offset] = $mod['add']->getContent() . $tmp[$mod['search']->offset];
break;
case 'bottom':
$offset = $lineMax - $mod['search']->offset;
if($offset < 0){
$tmp[-1] = $mod['add']->getContent();
} else {
$tmp[$offset] .= $mod['add']->getContent();
}
break;
default:
$changed = false;
foreach($tmp as $lineNum => $line) {
if(strlen($mod['search']->getContent()) == 0) {
if($mod['error'] == 'log' || $mod['error'] == 'abort') {
VQMod::$log->write('VQModObject::applyMod - EMPTY SEARCH CONTENT ERROR', $this);
}
break;
}
if($mod['search']->regex == 'true') {
$pos = @preg_match($mod['search']->getContent(), $line);
if($pos === false) {
if($mod['error'] == 'log' || $mod['error'] == 'abort' ) {
VQMod::$log->write('VQModObject::applyMod - INVALID REGEX ERROR - ' . $mod['search']->getContent(), $this);
}
continue 2;
} elseif($pos == 0) {
$pos = false;
}
} else {
$pos = strpos($line, $mod['search']->getContent());
}
if($pos !== false) {
$indexCount++;
$changed = true;
if(!$mod['search']->indexes() || ($mod['search']->indexes() && in_array($indexCount, $mod['search']->indexes()))) {
switch($mod['search']->position) {
case 'before':
$offset = ($lineNum - $mod['search']->offset < 0) ? -1 : $lineNum - $mod['search']->offset;
$tmp[$offset] = empty($tmp[$offset]) ? $mod['add']->getContent() : $mod['add']->getContent() . "\n" . $tmp[$offset];
break;
case 'after':
$offset = ($lineNum + $mod['search']->offset > $lineMax) ? $lineMax : $lineNum + $mod['search']->offset;
$tmp[$offset] = $tmp[$offset] . "\n" . $mod['add']->getContent();
break;
case 'ibefore':
$tmp[$lineNum] = str_replace($mod['search']->getContent(), $mod['add']->getContent() . $mod['search']->getContent(), $line);
break;
case 'iafter':
$tmp[$lineNum] = str_replace($mod['search']->getContent(), $mod['search']->getContent() . $mod['add']->getContent(), $line);
break;
default:
if(!empty($mod['search']->offset)) {
if($mod['search']->offset > 0) {
for($i = 1; $i <= $mod['search']->offset; $i++) {
if(isset($tmp[$lineNum + $i])) {
$tmp[$lineNum + $i] = '';
}
}
} elseif($mod['search']->offset < 0) {
for($i = -1; $i >= $mod['search']->offset; $i--) {
if(isset($tmp[$lineNum + $i])) {
$tmp[$lineNum + $i] = '';
}
}
}
}
if($mod['search']->regex == 'true') {
$tmp[$lineNum] = preg_replace($mod['search']->getContent(), $mod['add']->getContent(), $line);
} else {
$tmp[$lineNum] = str_replace($mod['search']->getContent(), $mod['add']->getContent(), $line);
}
break;
}
}
}
}
if(!$changed) {
$skip = ($mod['error'] == 'skip' || $mod['error'] == 'log') ? ' (SKIPPED)' : ' (ABORTING MOD)';
if($mod['error'] == 'log' || $mod['error'] == 'abort') {
VQMod::$log->write('VQModObject::applyMod - SEARCH NOT FOUND' . $skip . ': ' . $mod['search']->getContent(), $this);
}
if($mod['error'] == 'abort') {
$this->_skip = true;
return;
}
}
break;
}
ksort($tmp);
$tmp = $this->_implodeData($tmp);
}
VQMod::$fileModding = false;
$data = $tmp;
}
/**
* VQModObject::_parseMods()
*
* @param DOMNode $node <modification> node to be parsed
* @return null
* @description Parses modifications in preparation for the applyMod method to work
*/
private function _parseMods(DOMNode $node){
$files = $node->getElementsByTagName('file');
$replaces = VQMod::$replaces;
foreach($files as $file) {
$path = $file->getAttribute('path') ? $file->getAttribute('path') : '';
$filesToMod = explode(',', $file->getAttribute('name'));
foreach($filesToMod as $filename) {
$fileToMod = $path . $filename;
if(!empty($replaces)) {
foreach($replaces as $r) {
if(count($r) == 2) {
$fileToMod = preg_replace($r[0], $r[1], $fileToMod);
}
}
}
$error = ($file->hasAttribute('error')) ? $file->getAttribute('error') : 'log';
$fullPath = VQMod::path($fileToMod);
if(!$fullPath || !file_exists($fullPath)){
if(strpos($fileToMod, '*') !== false) {
$fullPath = VQMod::getCwd() . $fileToMod;
} else {
if ($error == 'log' || $error == 'abort') {
$skip = ($error == 'log') ? ' (SKIPPED)' : ' (ABORTING MOD)';
VQMod::$log->write('VQModObject::parseMods - Could not resolve path for [' . $fileToMod . ']' . $skip, $this);
}
if ($error == 'log' || $error == 'skip') {
continue;
} elseif ($error == 'abort') {
return false;
}
}
}
$operations = $file->getElementsByTagName('operation');
foreach($operations as $opIndex => $operation) {
VQMod::$fileModding = $fileToMod . '(' . $opIndex . ')';
$skipOperation = false;
$error = ($operation->hasAttribute('error')) ? $operation->getAttribute('error') : 'abort';
$ignoreif = $operation->getElementsByTagName('ignoreif')->item(0);
if($ignoreif) {
$ignoreif = new VQSearchNode($ignoreif);
} else {
$ignoreif = false;
}
$search = $operation->getElementsByTagName('search')->item(0);
$add = $operation->getElementsByTagName('add')->item(0);
if(!$search) {
VQMod::$log->write('Operation <search> tag missing', $this);
$skipOperation = true;
}
if(!$add) {
VQMod::$log->write('Operation <add> tag missing', $this);
$skipOperation = true;
}
if(!$skipOperation) {
$this->mods[$fullPath][] = array(
'search' => new VQSearchNode($search),
'add' => new VQAddNode($add),
'ignoreif' => $ignoreif,
'error' => $error,
'fileToMod' => $fileToMod,
'opIndex' => $opIndex,
);
}
}
VQMod::$fileModding = false;
}
}
}
/**
* VQModObject::_explodeData()
*
* @param string $data File contents
* @return string
* @description Splits a file into an array of individual lines
*/
private function _explodeData($data) {
return explode("\n", $data);
}
/**
* VQModObject::_implodeData()
*
* @param array $data Array of lines
* @return string
* @description Joins an array of lines back into a text file
*/
private function _implodeData($data) {
return implode("\n", $data);
}
}
/**
* VQNode
* @description Basic node object blueprint
*/
class VQNode {
public $trim = 'false';
private $_content = '';
/**
* VQNode::__construct()
*
* @param DOMNode $node Search/add node
* @return null
* @description Parses the node attributes and sets the node property
*/
public function __construct(DOMNode $node) {
$this->_content = $node->nodeValue;
if($node->hasAttributes()) {
foreach($node->attributes as $attr) {
$name = $attr->nodeName;
if(isset($this->$name)) {
$this->$name = $attr->nodeValue;
}
}
}
}
/**
* VQNode::getContent()
*
* @return string
* @description Returns the content, trimmed if applicable
*/
public function getContent() {
$content = ($this->trim == 'true') ? trim($this->_content) : $this->_content;
return $content;
}
}
/**
* VQSearchNode
* @description Object for the <search> xml tags
*/
class VQSearchNode extends VQNode {
public $position = 'replace';
public $offset = 0;
public $index = 'false';
public $regex = 'false';
public $trim = 'true';
/**
* VQSearchNode::indexes()
*
* @return bool, array
* @description Returns the index values to use the search on, or false if none
*/
public function indexes() {
if($this->index == 'false') {
return false;
}
$tmp = explode(',', $this->index);
foreach($tmp as $k => $v) {
if(!is_int($v)) {
unset($k);
}
}
$tmp = array_unique($tmp);
return empty($tmp) ? false : $tmp;
}
}
/**
* VQAddNode
* @description Object for the <add> xml tags
*/
class VQAddNode extends VQNode {
}
| gpl-3.0 |
sameesh/Myrepos | ImageServer/TestApp/Startup.Designer.cs | 10429 | #region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project 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.
//
// The ClearCanvas RIS/PACS open source project 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
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
namespace ClearCanvas.ImageServer.TestApp
{
partial class Startup
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.TestRule = new System.Windows.Forms.Button();
this.TestHeaderStreamButton = new System.Windows.Forms.Button();
this.buttonCompression = new System.Windows.Forms.Button();
this.TestEditStudyButton = new System.Windows.Forms.Button();
this.RandomImageSender = new System.Windows.Forms.Button();
this.ExtremeStreaming = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.UsageTracking = new System.Windows.Forms.Button();
this.DatabaseGenerator = new System.Windows.Forms.Button();
this.ProductVerify = new System.Windows.Forms.Button();
this._archiveTestBtn = new System.Windows.Forms.Button();
this._perfMon = new System.Windows.Forms.Button();
this._cfindPerformanceTest = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// TestRule
//
this.TestRule.Location = new System.Drawing.Point(28, 37);
this.TestRule.Name = "TestRule";
this.TestRule.Size = new System.Drawing.Size(183, 59);
this.TestRule.TabIndex = 0;
this.TestRule.Text = "DICOM File Tests";
this.TestRule.UseVisualStyleBackColor = true;
this.TestRule.Click += new System.EventHandler(this.TestRule_Click);
//
// TestHeaderStreamButton
//
this.TestHeaderStreamButton.Location = new System.Drawing.Point(258, 37);
this.TestHeaderStreamButton.Name = "TestHeaderStreamButton";
this.TestHeaderStreamButton.Size = new System.Drawing.Size(176, 59);
this.TestHeaderStreamButton.TabIndex = 1;
this.TestHeaderStreamButton.Text = "Header Retrieval Client";
this.TestHeaderStreamButton.UseVisualStyleBackColor = true;
this.TestHeaderStreamButton.Click += new System.EventHandler(this.TestHeaderStreamButton_Click);
//
// buttonCompression
//
this.buttonCompression.Location = new System.Drawing.Point(28, 135);
this.buttonCompression.Name = "buttonCompression";
this.buttonCompression.Size = new System.Drawing.Size(183, 59);
this.buttonCompression.TabIndex = 2;
this.buttonCompression.Text = "Compression";
this.buttonCompression.UseVisualStyleBackColor = true;
this.buttonCompression.Click += new System.EventHandler(this.buttonCompression_Click);
//
// TestEditStudyButton
//
this.TestEditStudyButton.Location = new System.Drawing.Point(258, 135);
this.TestEditStudyButton.Name = "TestEditStudyButton";
this.TestEditStudyButton.Size = new System.Drawing.Size(183, 59);
this.TestEditStudyButton.TabIndex = 2;
this.TestEditStudyButton.Text = "Edit Study";
this.TestEditStudyButton.UseVisualStyleBackColor = true;
this.TestEditStudyButton.Click += new System.EventHandler(this.buttonEditStudy_Click);
//
// RandomImageSender
//
this.RandomImageSender.Location = new System.Drawing.Point(28, 228);
this.RandomImageSender.Name = "RandomImageSender";
this.RandomImageSender.Size = new System.Drawing.Size(183, 59);
this.RandomImageSender.TabIndex = 2;
this.RandomImageSender.Text = "Random Image Sender";
this.RandomImageSender.UseVisualStyleBackColor = true;
this.RandomImageSender.Click += new System.EventHandler(this.RandomImageSender_Click);
//
// ExtremeStreaming
//
this.ExtremeStreaming.Location = new System.Drawing.Point(258, 228);
this.ExtremeStreaming.Name = "ExtremeStreaming";
this.ExtremeStreaming.Size = new System.Drawing.Size(183, 59);
this.ExtremeStreaming.TabIndex = 2;
this.ExtremeStreaming.Text = "Extreme Streaming";
this.ExtremeStreaming.UseVisualStyleBackColor = true;
this.ExtremeStreaming.Click += new System.EventHandler(this.ExtremeStreaming_Click);
//
// button1
//
this.button1.Location = new System.Drawing.Point(258, 316);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(183, 52);
this.button1.TabIndex = 3;
this.button1.Text = "Streaming";
this.button1.UseVisualStyleBackColor = true;
//
// UsageTracking
//
this.UsageTracking.Enabled = false;
this.UsageTracking.Location = new System.Drawing.Point(28, 312);
this.UsageTracking.Name = "UsageTracking";
this.UsageTracking.Size = new System.Drawing.Size(183, 52);
this.UsageTracking.TabIndex = 4;
this.UsageTracking.Text = "Usage Tracking";
this.UsageTracking.UseVisualStyleBackColor = true;
this.UsageTracking.Click += new System.EventHandler(this.UsageTracking_Click);
//
// DatabaseGenerator
//
this.DatabaseGenerator.Location = new System.Drawing.Point(259, 395);
this.DatabaseGenerator.Name = "DatabaseGenerator";
this.DatabaseGenerator.Size = new System.Drawing.Size(182, 51);
this.DatabaseGenerator.TabIndex = 4;
this.DatabaseGenerator.Text = "Database Generator";
this.DatabaseGenerator.UseVisualStyleBackColor = true;
this.DatabaseGenerator.Click += new System.EventHandler(this.DatabaseGenerator_Click);
//
// ProductVerify
//
this.ProductVerify.Location = new System.Drawing.Point(28, 395);
this.ProductVerify.Name = "ProductVerify";
this.ProductVerify.Size = new System.Drawing.Size(182, 51);
this.ProductVerify.TabIndex = 4;
this.ProductVerify.Text = "Product Verify";
this.ProductVerify.UseVisualStyleBackColor = true;
this.ProductVerify.Click += new System.EventHandler(this.ProductVerify_Click);
//
// _archiveTestBtn
//
this._archiveTestBtn.Location = new System.Drawing.Point(487, 37);
this._archiveTestBtn.Name = "_archiveTestBtn";
this._archiveTestBtn.Size = new System.Drawing.Size(183, 59);
this._archiveTestBtn.TabIndex = 2;
this._archiveTestBtn.Text = "Archive Test";
this._archiveTestBtn.UseVisualStyleBackColor = true;
this._archiveTestBtn.Click += new System.EventHandler(this._archiveTestBtn_Click);
//
// _perfMon
//
this._perfMon.Location = new System.Drawing.Point(487, 135);
this._perfMon.Name = "_perfMon";
this._perfMon.Size = new System.Drawing.Size(183, 59);
this._perfMon.TabIndex = 2;
this._perfMon.Text = "Performance Monitor";
this._perfMon.UseVisualStyleBackColor = true;
this._perfMon.Click += new System.EventHandler(this._perfMon_Click);
//
// _cfindPerformanceTest
//
this._cfindPerformanceTest.Location = new System.Drawing.Point(487, 228);
this._cfindPerformanceTest.Name = "_cfindPerformanceTest";
this._cfindPerformanceTest.Size = new System.Drawing.Size(183, 59);
this._cfindPerformanceTest.TabIndex = 2;
this._cfindPerformanceTest.Text = "DICOM C-FIND Performance";
this._cfindPerformanceTest.UseVisualStyleBackColor = true;
this._cfindPerformanceTest.Click += new System.EventHandler(this._perfMon_Click);
//
// Startup
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(738, 474);
this.Controls.Add(this.ProductVerify);
this.Controls.Add(this.DatabaseGenerator);
this.Controls.Add(this.UsageTracking);
this.Controls.Add(this.button1);
this.Controls.Add(this.ExtremeStreaming);
this.Controls.Add(this._cfindPerformanceTest);
this.Controls.Add(this._perfMon);
this.Controls.Add(this._archiveTestBtn);
this.Controls.Add(this.RandomImageSender);
this.Controls.Add(this.TestEditStudyButton);
this.Controls.Add(this.buttonCompression);
this.Controls.Add(this.TestHeaderStreamButton);
this.Controls.Add(this.TestRule);
this.Name = "Startup";
this.Text = "Startup";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button TestRule;
private System.Windows.Forms.Button TestHeaderStreamButton;
private System.Windows.Forms.Button buttonCompression;
private System.Windows.Forms.Button TestEditStudyButton;
private System.Windows.Forms.Button RandomImageSender;
private System.Windows.Forms.Button ExtremeStreaming;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button UsageTracking;
private System.Windows.Forms.Button DatabaseGenerator;
private System.Windows.Forms.Button ProductVerify;
private System.Windows.Forms.Button _archiveTestBtn;
private System.Windows.Forms.Button _perfMon;
private System.Windows.Forms.Button _cfindPerformanceTest;
}
} | gpl-3.0 |
DISID/ci-jenkins | spring-roo-petclinic/src/main/java/org/springframework/roo/petclinic/repository/VisitRepository.java | 679 | package org.springframework.roo.petclinic.repository;
import org.springframework.roo.addon.layers.repository.jpa.annotations.RooJpaRepository;
import org.springframework.roo.petclinic.domain.Visit;
import org.springframework.roo.addon.layers.repository.jpa.annotations.finder.RooFinder;
/**
* = VisitRepository
*
* TODO Auto-generated class documentation
*
*/
@RooJpaRepository(entity = Visit.class, finders = { @RooFinder(value = "findByDescriptionAndVisitDate", returnType = Visit.class), @RooFinder(value = "findByVisitDateBetween", returnType = Visit.class), @RooFinder(value = "findByDescriptionLike", returnType = Visit.class) })
public interface VisitRepository {
}
| gpl-3.0 |
tumbl3w33d/ansible | lib/ansible/modules/network/aci/mso_schema_site_anp.py | 5749 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Dag Wieers (@dagwieers) <dag@wieers.com>
# 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 = r'''
---
module: mso_schema_site_anp
short_description: Manage site-local Application Network Profiles (ANPs) in schema template
description:
- Manage site-local ANPs in schema template on Cisco ACI Multi-Site.
author:
- Dag Wieers (@dagwieers)
version_added: '2.8'
options:
schema:
description:
- The name of the schema.
type: str
required: yes
site:
description:
- The name of the site.
type: str
required: yes
template:
description:
- The name of the template.
type: str
required: yes
anp:
description:
- The name of the ANP to manage.
type: str
aliases: [ name ]
state:
description:
- Use C(present) or C(absent) for adding or removing.
- Use C(query) for listing an object or multiple objects.
type: str
choices: [ absent, present, query ]
default: present
seealso:
- module: mso_schema_site
- module: mso_schema_site_anp_epg
- module: mso_schema_template_anp
extends_documentation_fragment: mso
'''
EXAMPLES = r'''
- name: Add a new site ANP
mso_schema_site_anp:
host: mso_host
username: admin
password: SomeSecretPassword
schema: Schema1
site: Site1
template: Template1
anp: ANP1
state: present
delegate_to: localhost
- name: Remove a site ANP
mso_schema_site_anp:
host: mso_host
username: admin
password: SomeSecretPassword
schema: Schema1
site: Site1
template: Template1
anp: ANP1
state: absent
delegate_to: localhost
- name: Query a specific site ANPs
mso_schema_site_anp:
host: mso_host
username: admin
password: SomeSecretPassword
schema: Schema1
site: Site1
template: Template1
state: query
delegate_to: localhost
register: query_result
- name: Query all site ANPs
mso_schema_site_anp:
host: mso_host
username: admin
password: SomeSecretPassword
schema: Schema1
site: Site1
template: Template1
state: query
delegate_to: localhost
register: query_result
'''
RETURN = r'''
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.aci.mso import MSOModule, mso_argument_spec, issubset
def main():
argument_spec = mso_argument_spec()
argument_spec.update(
schema=dict(type='str', required=True),
site=dict(type='str', required=True),
template=dict(type='str', required=True),
anp=dict(type='str', aliases=['name']), # This parameter is not required for querying all objects
state=dict(type='str', default='present', choices=['absent', 'present', 'query']),
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
required_if=[
['state', 'absent', ['anp']],
['state', 'present', ['anp']],
],
)
schema = module.params.get('schema')
site = module.params.get('site')
template = module.params.get('template')
anp = module.params.get('anp')
state = module.params.get('state')
mso = MSOModule(module)
# Get schema_id
schema_obj = mso.get_obj('schemas', displayName=schema)
if not schema_obj:
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj)
schema_id = schema_obj.get('id')
# Get site
site_id = mso.lookup_site(site)
# Get site_idx
sites = [(s.get('siteId'), s.get('templateName')) for s in schema_obj.get('sites')]
if (site_id, template) not in sites:
mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites)))
# Schema-access uses indexes
site_idx = sites.index((site_id, template))
# Path-based access uses site_id-template
site_template = '{0}-{1}'.format(site_id, template)
# Get ANP
anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp)
anps = [a.get('anpRef') for a in schema_obj.get('sites')[site_idx]['anps']]
if anp is not None and anp_ref in anps:
anp_idx = anps.index(anp_ref)
anp_path = '/sites/{0}/anps/{1}'.format(site_template, anp)
mso.existing = schema_obj.get('sites')[site_idx]['anps'][anp_idx]
if state == 'query':
if anp is None:
mso.existing = schema_obj.get('sites')[site_idx]['anps']
elif not mso.existing:
mso.fail_json(msg="ANP '{anp}' not found".format(anp=anp))
mso.exit_json()
anps_path = '/sites/{0}/anps'.format(site_template)
ops = []
mso.previous = mso.existing
if state == 'absent':
if mso.existing:
mso.sent = mso.existing = {}
ops.append(dict(op='remove', path=anp_path))
elif state == 'present':
payload = dict(
anpRef=dict(
schemaId=schema_id,
templateName=template,
anpName=anp,
),
)
mso.sanitize(payload, collate=True)
if not mso.existing:
ops.append(dict(op='add', path=anps_path + '/-', value=mso.sent))
mso.existing = mso.proposed
if not module.check_mode:
mso.request(schema_path, method='PATCH', data=ops)
mso.exit_json()
if __name__ == "__main__":
main()
| gpl-3.0 |
loorenzooo/aslfc | plugins-dist/petitions/lang/petitions_cpf_hat.php | 1768 | <?php
// This is a SPIP language file -- Ceci est un fichier langue de SPIP
// extrait automatiquement de http://trad.spip.net/tradlang_module/petitions?lang_cible=cpf_hat
// ** ne pas modifier le fichier **
if (!defined('_ECRIRE_INC_VERSION')) return;
$GLOBALS[$GLOBALS['idx_lang']] = array(
// F
'form_pet_adresse_site' => 'Ladrès sit ou', # MODIF
'form_pet_aucune_signature' => 'Okenn siyati ka koresponn kod-la...', # MODIF
'form_pet_confirmation' => 'Mèsi konfime siyati ou :',
'form_pet_deja_signe' => 'W te deja sinye tèks-la.',
'form_pet_envoi_mail_confirmation' => 'Yon limèl pou konfine te fin voye a w. Fòk w vizite ladrès wèb te done nan limèl pou w konfime siyati ou.', # MODIF
'form_pet_mail_confirmation' => 'Bonjou,
W la domman mèt siyati nan petisyon-nan :
@titre@.
W te done tout ranséynman swivan :
Kouman rele: @nom_email@
sit ou: @nom_site@ - @url_site@
...
Pou konfime siyati-a, fòk sèlman w abòd ladrès anba (sinon, sitwèb-la ke pa enskri siyati ou) :
@url@
Mèsi w soutni petisyon-nan
', # MODIF
'form_pet_nom_site2' => 'Kouman sitwèb ou rele', # MODIF
'form_pet_probleme_technique' => 'Pwoblèm teknik, siyati se pa posib kounye-a. Tann pwoblèm-la ke aranje pou rete sispann a yo.',
'form_pet_signature_validee' => 'Siyati ou se konfime. Mèsi !',
'form_pet_site_deja_enregistre' => 'Sit-la se deja enskri',
'form_pet_url_invalide' => 'URL w te done se pa bon.',
'form_pet_votre_email' => 'Ladrès limèl ou',
'form_pet_votre_nom' => 'Kouman w rele', # MODIF
'form_pet_votre_site' => 'Si w ap gen sitwèb, se posib enskri ali isit-enba-mèm',
// I
'info_adresse_email' => 'LADRES LIMEL :',
'info_site_web' => 'SIT WEB :',
// L
'lien_reponse_article' => 'Réponn atik-la'
);
?>
| gpl-3.0 |
BigBoss424/a-zplumbing | Magento-CE-2/vendor/magento/magento2-base/lib/web/mage/captcha.js | 1070 | /**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
var Captcha = Class.create();
Captcha.prototype = {
initialize: function(url, formId){
this.url = url;
this.formId = formId;
},
refresh: function(elem) {
formId = this.formId;
if (elem) Element.addClassName(elem, 'refreshing');
new Ajax.Request(this.url, {
onSuccess: function (response) {
if (response.responseText.isJSON()) {
var json = response.responseText.evalJSON();
if (!json.error && json.imgSrc) {
$(formId).writeAttribute('src', json.imgSrc);
if (elem) Element.removeClassName(elem, 'refreshing');
} else {
if (elem) Element.removeClassName(elem, 'refreshing');
}
}
},
method: 'post',
parameters: {
'formId' : this.formId
}
});
}
};
| gpl-3.0 |
Passtechsoft/TPEAlpGen | blender/extern/carve/include/carve/edge_impl.hpp | 684 | // Begin License:
// Copyright (C) 2006-2014 Tobias Sargeant (tobias.sargeant@gmail.com).
// All rights reserved.
//
// This file is part of the Carve CSG Library (http://carve-csg.com/)
//
// This file may be used under the terms of either the GNU General
// Public License version 2 or 3 (at your option) as published by the
// Free Software Foundation and appearing in the files LICENSE.GPL2
// and LICENSE.GPL3 included in the packaging of this file.
//
// This file is provided "AS IS" with NO WARRANTY OF ANY KIND,
// INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE.
// End:
#pragma once
namespace carve {
namespace poly {
}
}
| gpl-3.0 |
phassoa/openelisglobal-core | app/src/us/mn/state/health/lims/testresult/valueholder/TestResultComparator.java | 1283 | /**
* 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 OpenELIS code.
*
* Copyright (C) The Minnesota Department of Health. All Rights Reserved.
*/
package us.mn.state.health.lims.testresult.valueholder;
import java.util.Comparator;
public class TestResultComparator implements Comparable {
String name;
// You can put the default sorting capability here
public int compareTo(Object obj) {
TestResult tr = (TestResult)obj;
return this.name.compareTo(tr.getValue());
}
public static final Comparator VALUE_COMPARATOR =
new Comparator() {
public int compare(Object a, Object b) {
TestResult tr_a = (TestResult)a;
TestResult tr_b = (TestResult)b;
return (((tr_a.getValue()).toLowerCase()).compareTo((tr_b.getValue()).toLowerCase()));
}
};
}
| mpl-2.0 |
kajigga/canvas-lms | public/javascripts/vendor/jquery.ui.core-1.9.js | 8015 | /*!
* jQuery UI @VERSION
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI
*/
(function( $, undefined ) {
// prevent duplicate loading
// this is only a problem because we proxy existing functions
// and we don't want to double proxy them
$.ui = $.ui || {};
if ( $.ui.version ) {
return;
}
$.extend( $.ui, {
version: "@VERSION",
keyCode: {
ALT: 18,
BACKSPACE: 8,
CAPS_LOCK: 20,
COMMA: 188,
COMMAND: 91,
COMMAND_LEFT: 91, // COMMAND
COMMAND_RIGHT: 93,
CONTROL: 17,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
MENU: 93, // COMMAND_RIGHT
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SHIFT: 16,
SPACE: 32,
TAB: 9,
UP: 38,
WINDOWS: 91 // COMMAND
}
});
// plugins
$.fn.extend({
_focus: $.fn.focus,
focus: function( delay, fn ) {
return typeof delay === "number" ?
this.each(function() {
var elem = this;
setTimeout(function() {
$( elem ).focus();
if ( fn ) {
fn.call( elem );
}
}, delay );
}) :
this._focus.apply( this, arguments );
},
scrollParent: function() {
var scrollParent;
if (($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
scrollParent = this.parents().filter(function() {
return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
}).eq(0);
} else {
scrollParent = this.parents().filter(function() {
return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
}).eq(0);
}
return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
},
zIndex: function( zIndex ) {
if ( zIndex !== undefined ) {
return this.css( "zIndex", zIndex );
}
if ( this.length ) {
var elem = $( this[ 0 ] ), position, value;
while ( elem.length && elem[ 0 ] !== document ) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css( "position" );
if ( position === "absolute" || position === "relative" || position === "fixed" ) {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt( elem.css( "zIndex" ), 10 );
if ( !isNaN( value ) && value !== 0 ) {
return value;
}
}
elem = elem.parent();
}
}
return 0;
},
disableSelection: function() {
return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
".ui-disableSelection", function( event ) {
event.preventDefault();
});
},
enableSelection: function() {
return this.unbind( ".ui-disableSelection" );
}
});
$.each( [ "Width", "Height" ], function( i, name ) {
var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
type = name.toLowerCase(),
orig = {
innerWidth: $.fn.innerWidth,
innerHeight: $.fn.innerHeight,
outerWidth: $.fn.outerWidth,
outerHeight: $.fn.outerHeight
};
function reduce( elem, size, border, margin ) {
$.each( side, function() {
size -= parseFloat( $.curCSS( elem, "padding" + this, true ) ) || 0;
if ( border ) {
size -= parseFloat( $.curCSS( elem, "border" + this + "Width", true ) ) || 0;
}
if ( margin ) {
size -= parseFloat( $.curCSS( elem, "margin" + this, true ) ) || 0;
}
});
return size;
}
$.fn[ "inner" + name ] = function( size ) {
if ( size === undefined ) {
return orig[ "inner" + name ].call( this );
}
return this.each(function() {
$( this ).css( type, reduce( this, size ) + "px" );
});
};
$.fn[ "outer" + name] = function( size, margin ) {
if ( typeof size !== "number" ) {
return orig[ "outer" + name ].call( this, size );
}
return this.each(function() {
$( this).css( type, reduce( this, size, true, margin ) + "px" );
});
};
});
// selectors
function focusable( element, isTabIndexNotNaN ) {
var nodeName = element.nodeName.toLowerCase();
if ( "area" === nodeName ) {
var map = element.parentNode,
mapName = map.name,
img;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap=#" + mapName + "]" )[0];
return !!img && visible( img );
}
return ( /input|select|textarea|button|object/.test( nodeName )
? !element.disabled
: "a" == nodeName
? element.href || isTabIndexNotNaN
: isTabIndexNotNaN)
// the element and all of its ancestors must be visible
&& visible( element );
}
function visible( element ) {
return !$( element ).parents().andSelf().filter(function() {
return $.curCSS( this, "visibility" ) === "hidden" ||
$.expr.filters.hidden( this );
}).length;
}
$.extend( $.expr[ ":" ], {
data: function( elem, i, match ) {
return !!$.data( elem, match[ 3 ] );
},
focusable: function( element ) {
return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
},
tabbable: function( element ) {
var tabIndex = $.attr( element, "tabindex" ),
isTabIndexNaN = isNaN( tabIndex );
return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
}
});
// support
$(function() {
var body = document.body,
div = body.appendChild( div = document.createElement( "div" ) );
$.extend( div.style, {
minHeight: "100px",
height: "auto",
padding: 0,
borderWidth: 0
});
$.support.minHeight = div.offsetHeight === 100;
$.support.selectstart = "onselectstart" in div;
// set display to none to avoid a layout bug in IE
// http://dev.jquery.com/ticket/4014
body.removeChild( div ).style.display = "none";
});
// deprecated
$.extend( $.ui, {
// $.ui.plugin is deprecated. Use the proxy pattern instead.
plugin: {
add: function( module, option, set ) {
var proto = $.ui[ module ].prototype;
for ( var i in set ) {
proto.plugins[ i ] = proto.plugins[ i ] || [];
proto.plugins[ i ].push( [ option, set[ i ] ] );
}
},
call: function( instance, name, args ) {
var set = instance.plugins[ name ];
if ( !set || !instance.element[ 0 ].parentNode ) {
return;
}
for ( var i = 0; i < set.length; i++ ) {
if ( instance.options[ set[ i ][ 0 ] ] ) {
set[ i ][ 1 ].apply( instance.element, args );
}
}
}
},
contains: $.contains,
// only used by resizable
hasScroll: function( el, a ) {
//If overflow is hidden, the element might have extra content, but the user wants to hide it
if ( $( el ).css( "overflow" ) === "hidden") {
return false;
}
var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
has = false;
if ( el[ scroll ] > 0 ) {
return true;
}
// TODO: determine which cases actually cause this to happen
// if the element doesn't have the scroll set, see if it's possible to
// set the scroll
el[ scroll ] = 1;
has = ( el[ scroll ] > 0 );
el[ scroll ] = 0;
return has;
},
// these are odd functions, fix the API or move into individual plugins
isOverAxis: function( x, reference, size ) {
//Determines when x coordinate is over "b" element axis
return ( x > reference ) && ( x < ( reference + size ) );
},
isOver: function( y, x, top, left, height, width ) {
//Determines when x, y coordinates is over "b" element
return $.ui.isOverAxis( y, top, height ) && $.ui.isOverAxis( x, left, width );
}
});
})( jQuery );
| agpl-3.0 |
dylanswartz/canvas-lms | lib/i18n_extraction/js_extractor.rb | 11209 | require 'lib/i18n_extraction/abstract_extractor'
module I18nExtraction
class JsExtractor
include AbstractExtractor
I18N_KEY = /['"](#?[\w.]+)['"]/
HASH_KEY = /['"]?(\w+)['"]?\s*:/
INTERPOLATION_KEY = /%\{([^\}]+)\}|\{\{([^\}]+)\}\}/
CORE_KEY = /\A(number|time|date|datetime|support)\./
STRING_LITERAL = /'((\\'|[^'])*)'|"((\\"|[^"])*)"/m
STRING_CONCATENATION = /(#{STRING_LITERAL})(\s*\+\s*(#{STRING_LITERAL})\s*)*/m
RUBY_SYMBOL = /:(\w+|#{STRING_LITERAL})/
REALLY_SIMPLE_HASH_LITERAL = /
\{\s*
#{HASH_KEY}\s*#{STRING_LITERAL}\s*
(,\s*#{HASH_KEY}\s*#{STRING_LITERAL}\s*)*
\}
/mx
SIMPLE_HASH_LITERAL = / # might have a t call as value, for example. no nested hashes, but we shouldn't need that
\{
(
#{STRING_LITERAL} |
[^}]
)+
\}
/mx
JS_BLOCK_START = /
<%\s*
js_block\s*
[^%]*?
(do|\{)\s*
%>\s*
/mx
JS_BLOCK = /
^([ \t]*) # we rely on indentation matching for the block (and we ignore any single-line js_block calls)
#{JS_BLOCK_START}\n
(.*?)\n
\1
<%\s*(end|\})\s*%>
/mx
SCOPED_BLOCK_START_COMPONENTS = ['([ \t]*)(require|define)\(', '[^\)]+?', '[\'"]', 'i18n']
SCOPED_BLOCK_START = /#{SCOPED_BLOCK_START_COMPONENTS.join}/
SCOPED_BLOCK = /^#{SCOPED_BLOCK_START}(!(#?[\w.]+)|Obj)?['"].*?function\s*\([^\)]*I18n[^\)]*\)\s*\{( *\n(\1[^ ]+\n)?.*?\n\1\}\))/m
I18N_ANY = /(I18n|i18n|jt)/
I18N_CALL_START = /I18n\.(t|translate|beforeLabel)\(/
I18N_KEY_OR_SIMPLE_EXPRESSION = /(#{I18N_KEY}|([\w\.]+|\(['"][\w.]+['"]\))+)/
I18N_CALL = /
#{I18N_CALL_START}
#{I18N_KEY_OR_SIMPLE_EXPRESSION}
(,\s*
( #{STRING_CONCATENATION} | #{REALLY_SIMPLE_HASH_LITERAL} ) # default
(,\s*
( #{SIMPLE_HASH_LITERAL} ) # options
)?
)?
\)
/mx
def process(source, options = {})
return false unless source =~ I18N_ANY
options[:offset] ||= 1
if options.delete(:erb)
process_js_blocks(source, options)
else
process_js(source, options)
end
true
end
# this is a bit more convoluted than just doing simple scans, but it lets
# us figure out exactly which ones we can't grok (and get the line numbers)
def find_matches(source, start_pattern, full_pattern=start_pattern, options = {})
expression_type = options[:expression] || "expression"
expected = []
lines = source.lines.to_a
lines.each_with_index do |line, number|
line.scan(/#{options[:start_prefix]}#{start_pattern}#{options[:start_suffix] || /.*$/}/) do
match = $&
if options[:check_expected].nil? || number = options[:check_expected].call(lines, number)
expected << [match, number + options[:offset]]
end
end
end
matches = []
source.scan(full_pattern){ |args| matches << [$&] + args }
raise "expected/actual mismatch (probably a bug)" if expected.size < matches.size
expected.each_index do |i|
expected_string = expected[i].first.strip
unless matches[i]
raise "unable to \"parse\" #{expression_type} on line #{expected[i].last} (#{expected_string}...)"
end
matched_string = matches[i].first.strip
unless matched_string.include?(expected_string)
raise "unable to \"parse\" #{expression_type} on line #{expected[i].last} (#{expected_string}...)"
end
matches[i] << expected[i].last
if block_given?
# interleave sub-results into our matches
# (e.g. an I18n.t that is interpolated into another I18n.t)
matches.insert i + 1, *yield(matches[i])
end
end
matches
end
def find_scopes(source, options)
# really really dumb multi-line regex implementation across array of
# lines... gross but necessary so we can get line numbers ... no back-
# tracking, but sorta supports +?
checker = lambda do |lines, offset|
parts = SCOPED_BLOCK_START_COMPONENTS.dup
line = lines[offset].dup
while part = parts.shift
pattern = /^#{part}/
return false unless line =~ pattern
while line.sub!(pattern, '')
if line.empty?
offset += 1
line = lines[offset]
return false if line.nil?
line = line.dup
end
break if part !~ /\+\?\z/ || parts.present? && line =~ /^#{parts.join}/
end
end
offset
end
scopes = find_matches(source, /#{SCOPED_BLOCK_START_COMPONENTS.first}/, SCOPED_BLOCK, :start_prefix => /\s*/, :start_suffix => '', :offset => options[:offset], :expression => "I18n scope", :check_expected => checker)
raise "multiple scopes are not allowed" if scopes.size > 1
scopes.each do |scope|
yield({:name => scope[4].to_s.sub(/\A#/, ''), :source => scope[5], :offset => scope.pop})
end
end
def check_scope_violations(source, options)
offset = options[:offset]
pattern = options[:pattern] || /#{I18N_CALL_START}.*$/
type = options[:expression] || 'I18n call'
# see if any other I18n calls happen outside of a scope
chunks = source.split(/(#{SCOPED_BLOCK.to_s.gsub(/\\1/, '\\\\2')})/m) # captures subpatterns too, so we need to pick and choose what we want
while chunk = chunks.shift
if chunk =~ /^([ \t]*)#{SCOPED_BLOCK_START}/
chunks.slice!(0, 5).inspect
else
find_matches chunk, pattern, pattern, :offset => offset do |match|
raise "possibly unscoped #{type} on line #{match.last} (hint: check your indentation)"
end
end
offset += chunk.count("\n")
end
end
def process_js(source, options = {})
find_scopes(source, options) do |scope|
process_block scope[:source], scope[:name], :offset => scope[:offset]
end
check_scope_violations(source, :offset => options[:offset])
end
def process_js_blocks(source, options = {})
# NOTE: we don't do any extraction from erb here since raw I18n js calls
# are no longer supported. all js i18n in views should be done w/ jt
# calls. we do sanity checks here rather than in the ruby extractor since
# it's quite a bit easier
blocks = find_matches(source, JS_BLOCK_START, JS_BLOCK, :start_prefix => /^\s*/, :start_suffix => /$/, :offset => options[:offset], :expression => "js_block")
blocks.each do |match|
block_source = match[3]
offset = match.last + 1
find_matches block_source, I18N_CALL_START, I18N_CALL, :offset => offset, :expression => "I18n call", :start_suffix => /[^\)\{$]+/ do |match|
raise "raw I18n call on line #{match.last} (hint: use the jt helper instead)"
end
find_scopes(block_source, :offset => offset) do |scope|
raise "i18n amd plugin is not supported in js_blocks (line #{scope[:offset]})" if scope[:name].present?
end
check_scope_violations(block_source, :offset => offset, :pattern => /(<%=\sjt[ \(]).*$/, :expression => 'jt call')
end
end
def process_block(source, scope, options = {})
@scope = scope
find_matches(source, I18N_CALL_START, I18N_CALL, :offset => options[:offset], :expression => "I18n call", :start_suffix => /[^\)\{$]+/) do |args|
method = args[1] # 0 = the full string
key = args[2]
default = args[6]
call_options = args[29] # :( ... so many capture groups
offset = args.last
raise "possibly unscoped I18n call on line #{offset} (hint: did you forget the scope in the require/define call?)" if @scope.empty?
process_call(scope, method, key, default, call_options, options.merge(:offset => offset))
end
end
def process_call(scope, method, key, default, call_options, options)
offset = options[:offset] || 0
sub_calls = []
return [] unless key = process_key(scope, method, key, default, options)
default = process_default(key, default, options)
if call_options
# in case we are interpolating the results of another t call
sub_calls = process_block(call_options, scope, options)
call_options = call_options.scan(HASH_KEY).map(&:last).map(&:to_sym)
end
# single word count/pluralization fu
if default.is_a?(String) && default =~ /\A[\w\-]+\z/ && call_options && call_options.include?(:count)
default = infer_pluralization_hash(default)
end
(default.is_a?(String) ? {nil => default} : default).each_pair do |k, str|
sub_key = k ? "#{key}.#{k}" : key
str.scan(INTERPOLATION_KEY) do |match|
if $& =~ /\A\{\{/
$stderr.puts "Warning: deprecated interpolation syntax used on line #{offset} of #{options[:filename]}"
end
i_key = (match[0] || match[1]).to_sym
unless call_options && call_options.include?(i_key)
raise "interpolation value not provided for #{i_key.inspect} (#{sub_key.inspect} on line #{offset})"
end
end
add_translation sub_key, str
end
sub_calls
end
def process_key(scope, method, key, default, options)
if key !~ /\A#{I18N_KEY}\z/
return nil if method == 'beforeLabel' && default.nil?
raise "invalid key (#{key.inspect} on line #{options[:offset]})"
end
key = key[1, key.length - 2]
if key.sub!(/\A#/, '')
return nil if key =~ CORE_KEY && default.nil? # nothing to extract, so we bail
else
key = scope + '.' + (method == 'beforeLabel' ? 'labels.' : '') + key
end
key
end
def process_default(key, default, options)
raise "no default provided for #{key.inspect} on line #{options[:offset]}" if default.nil?
if default =~ /\A['"]/
process_literal(default) rescue (raise "unable to \"parse\" default for #{key.inspect} on line #{options[:offset]}: #{$!}")
else
hash = JSON.parse(sanitize_json_hash(default)) rescue (raise "unable to \"parse\" default for #{key.inspect} on line #{options[:offset]}: #{$!}")
pluralization_keys = hash.keys.map(&:to_sym)
if (invalid_keys = (pluralization_keys - allowed_pluralization_keys)).size > 0
raise "invalid :count sub-key(s): #{invalid_keys.inspect} on line #{options[:offset]}"
elsif required_pluralization_keys & pluralization_keys != required_pluralization_keys
raise "not all required :count sub-key(s) provided on line #{options[:offset]} (expected #{required_pluralization_keys.join(', ')})"
end
hash
end
end
def sanitize_json_hash(string)
string.gsub(/#{HASH_KEY}\s*#{STRING_LITERAL}/) { |m1|
m1.sub(HASH_KEY) { |m2|
'"' + m2.delete("'\":") + '":'
}
}.gsub(STRING_LITERAL) { |match|
process_literal(match).inspect # double-quoted strings only
}
end
def process_literal(string)
instance_eval(string.gsub(/(^|[^\\])#/, '\1\\#'))
end
end
end
| agpl-3.0 |
bartimaeus/crm_groups | app/helpers/comments_helper.rb | 827 | # Fat Free CRM
# Copyright (C) 2008-2010 by Michael Dvorkin
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#------------------------------------------------------------------------------
module CommentsHelper
end
| agpl-3.0 |
abdullahalmasum/a2billing-2.1.0-untar | admin/Public/A2B_entity_payment_agent.php | 2279 | <?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of A2Billing (http://www.a2billing.net/)
*
* A2Billing, Commercial Open Source Telecom Billing platform,
* powered by Star2billing S.L. <http://www.star2billing.com/>
*
* @copyright Copyright (C) 2004-2015 - Star2billing S.L.
* @author Belaid Arezqui <areski@gmail.com>
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html
* @package A2Billing
*
* Software License Agreement (GNU Affero General Public License)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
**/
include '../lib/admin.defines.php';
include '../lib/admin.module.access.php';
include '../lib/Form/Class.FormHandler.inc.php';
include './form_data/FG_var_payment_agent.inc';
include '../lib/admin.smarty.php';
if (!has_rights(ACX_BILLING)) {
Header("HTTP/1.0 401 Unauthorized");
Header("Location: PP_error.php?c=accessdenied");
die();
}
$HD_Form->setDBHandler(DbConnect());
$HD_Form->init();
if ($id != "" || !is_null($id)) {
$HD_Form->FG_EDITION_CLAUSE = str_replace("%id", "$id", $HD_Form->FG_EDITION_CLAUSE);
}
if (!isset ($form_action))
$form_action = "list"; //ask-add
if (!isset ($action))
$action = $form_action;
$list = $HD_Form->perform_action($form_action);
// #### HEADER SECTION
$smarty->display('main.tpl');
// #### HELP SECTION
echo $CC_help_view_payment_agent;
if ($form_action == "list") {
$HD_Form->create_search_form();
}
// #### TOP SECTION PAGE
$HD_Form->create_toppage($form_action);
$HD_Form->create_form($form_action, $list, $id = null);
// #### FOOTER SECTION
$smarty->display('footer.tpl');
| agpl-3.0 |
Godin/checkstyle | src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NestedForDepthCheckTest.java | 3556 | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2015 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.coding;
import static com.puppycrawl.tools.checkstyle.checks.coding.NestedForDepthCheck.MSG_KEY;
import org.junit.Assert;
import org.junit.Test;
import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
/**
* The unit-test for the <code>NestedForDepthCheck</code>-checkstyle enhancement.
* @see com.puppycrawl.tools.checkstyle.checks.coding.NestedForDepthCheck
*/
public class NestedForDepthCheckTest extends BaseCheckTestSupport {
/**
* Call the check allowing 2 layers of nested for-statements. This
* means the top-level for can contain up to 2 levels of nested for
* statements. As the testinput has 4 layers of for-statements below
* the top-level for statement, this must cause 2 error-messages.
*
* @throws Exception necessary to fulfill JUnit's
* interface-requirements for test-methods
*/
@Test
public void testNestedTooDeep() throws Exception {
final DefaultConfiguration checkConfig =
createCheckConfig(NestedForDepthCheck.class);
checkConfig.addAttribute("max", "2");
final String[] expected = {
"43:11: " + getCheckMessage(MSG_KEY, 3, 2),
"44:13: " + getCheckMessage(MSG_KEY, 4, 2),
};
verify(checkConfig, getPath("coding/InputNestedForDepth.java"),
expected);
}
/**
* Call the check allowing 4 layers of nested for-statements. This
* means the top-level for can contain up to 4 levels of nested for
* statements. As the testinput has 4 layers of for-statements below
* the top-level for statement, this must not cause an
* error-message.
*
* @throws Exception necessary to fulfill JUnit's
* interface-requirements for test-methods
*/
@Test
public void testNestedOk() throws Exception {
final DefaultConfiguration checkConfig =
createCheckConfig(NestedForDepthCheck.class);
checkConfig.addAttribute("max", "4");
final String[] expected = {
};
verify(checkConfig, getPath("coding/InputNestedForDepth.java"),
expected);
}
@Test
public void testTokensNotNull() {
NestedForDepthCheck check = new NestedForDepthCheck();
Assert.assertNotNull(check.getAcceptableTokens());
Assert.assertNotNull(check.getDefaultTokens());
Assert.assertNotNull(check.getRequiredTokens());
}
}
| lgpl-2.1 |
abedeen/shopizer | sm-shop/src/main/java/com/salesmanager/shop/store/controller/product/facade/ProductFacadeImpl.java | 6730 | package com.salesmanager.shop.store.controller.product.facade;
import com.salesmanager.core.business.services.catalog.category.CategoryService;
import com.salesmanager.core.business.services.catalog.product.PricingService;
import com.salesmanager.core.business.services.catalog.product.ProductService;
import com.salesmanager.core.business.services.catalog.product.attribute.ProductOptionService;
import com.salesmanager.core.business.services.catalog.product.attribute.ProductOptionValueService;
import com.salesmanager.core.business.services.catalog.product.manufacturer.ManufacturerService;
import com.salesmanager.core.business.services.reference.language.LanguageService;
import com.salesmanager.core.business.services.tax.TaxClassService;
import com.salesmanager.core.model.catalog.product.Product;
import com.salesmanager.core.model.catalog.product.availability.ProductAvailability;
import com.salesmanager.core.model.catalog.product.price.ProductPrice;
import com.salesmanager.core.model.merchant.MerchantStore;
import com.salesmanager.core.model.reference.language.Language;
import com.salesmanager.shop.model.catalog.product.PersistableProduct;
import com.salesmanager.shop.model.catalog.product.ProductPriceEntity;
import com.salesmanager.shop.model.catalog.product.ReadableProduct;
import com.salesmanager.shop.populator.catalog.PersistableProductPopulator;
import com.salesmanager.shop.populator.catalog.ReadableProductPopulator;
import com.salesmanager.shop.utils.DateUtil;
import com.salesmanager.shop.utils.ImageFilePath;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.util.Date;
@Service("productFacade")
public class ProductFacadeImpl implements ProductFacade {
@Inject
private CategoryService categoryService;
@Inject
private ManufacturerService manufacturerService;
@Inject
private LanguageService languageService;
@Inject
private ProductOptionService productOptionService;
@Inject
private ProductOptionValueService productOptionValueService;
@Inject
private TaxClassService taxClassService;
@Inject
private ProductService productService;
@Inject
private PricingService pricingService;
@Inject
@Qualifier("img")
private ImageFilePath imageUtils;
@Override
public PersistableProduct saveProduct(MerchantStore store, PersistableProduct product, Language language)
throws Exception {
PersistableProductPopulator persistableProductPopulator = new PersistableProductPopulator();
persistableProductPopulator.setCategoryService(categoryService);
persistableProductPopulator.setManufacturerService(manufacturerService);
persistableProductPopulator.setLanguageService(languageService);
persistableProductPopulator.setProductOptionService(productOptionService);
persistableProductPopulator.setProductOptionValueService(productOptionValueService);
persistableProductPopulator.setTaxClassService(taxClassService);
Product target = new Product();
persistableProductPopulator.populate(product, target, store, language);
productService.create(target);
product.setId(target.getId());
return product;
}
@Override
public ReadableProduct getProduct(MerchantStore store, Long id, Language language)
throws Exception {
Product product = productService.getById(id);
if(product==null) {
return null;
}
ReadableProduct readableProduct = new ReadableProduct();
ReadableProductPopulator populator = new ReadableProductPopulator();
populator.setPricingService(pricingService);
populator.setimageUtils(imageUtils);
populator.populate(product, readableProduct, store, language);
return readableProduct;
}
@Override
public ReadableProduct getProduct(MerchantStore store, String sku,
Language language) throws Exception {
Product product = productService.getByCode(sku, language);
if(product==null) {
return null;
}
ReadableProduct readableProduct = new ReadableProduct();
ReadableProductPopulator populator = new ReadableProductPopulator();
populator.setPricingService(pricingService);
populator.setimageUtils(imageUtils);
populator.populate(product, readableProduct, store, language);
return readableProduct;
}
@Override
public ReadableProduct updateProductPrice(ReadableProduct product,
ProductPriceEntity price, Language language) throws Exception {
Product persistable = productService.getById(product.getId());
if(persistable==null) {
throw new Exception("product is null for id " + product.getId());
}
java.util.Set<ProductAvailability> availabilities = persistable.getAvailabilities();
for(ProductAvailability availability : availabilities) {
ProductPrice productPrice = availability.defaultPrice();
productPrice.setProductPriceAmount(price.getOriginalPrice());
if(price.isDiscounted()) {
productPrice.setProductPriceSpecialAmount(price.getDiscountedPrice());
if(!StringUtils.isBlank(price.getDiscountStartDate())) {
Date startDate = DateUtil.getDate(price.getDiscountStartDate());
productPrice.setProductPriceSpecialStartDate(startDate);
}
if(!StringUtils.isBlank(price.getDiscountEndDate())) {
Date endDate = DateUtil.getDate(price.getDiscountEndDate());
productPrice.setProductPriceSpecialEndDate(endDate);
}
}
}
productService.update(persistable);
ReadableProduct readableProduct = new ReadableProduct();
ReadableProductPopulator populator = new ReadableProductPopulator();
populator.setPricingService(pricingService);
populator.setimageUtils(imageUtils);
populator.populate(persistable, readableProduct, persistable.getMerchantStore(), language);
return readableProduct;
}
@Override
public ReadableProduct updateProductQuantity(ReadableProduct product,
int quantity, Language language) throws Exception {
Product persistable = productService.getById(product.getId());
if(persistable==null) {
throw new Exception("product is null for id " + product.getId());
}
java.util.Set<ProductAvailability> availabilities = persistable.getAvailabilities();
for(ProductAvailability availability : availabilities) {
availability.setProductQuantity(quantity);
}
productService.update(persistable);
ReadableProduct readableProduct = new ReadableProduct();
ReadableProductPopulator populator = new ReadableProductPopulator();
populator.setPricingService(pricingService);
populator.setimageUtils(imageUtils);
populator.populate(persistable, readableProduct, persistable.getMerchantStore(), language);
return readableProduct;
}
}
| lgpl-2.1 |
msipos/syntaxic | third-party/tokenizer/input/django.js | 2390 | /*
Language: Django
Requires: xml.js
Author: Ivan Sagalaev <maniac@softwaremaniacs.org>
Contributors: Ilya Baryshev <baryshev@gmail.com>
Category: template
*/
function(hljs) {
var FILTER = {
className: 'filter',
begin: /\|[A-Za-z]+:?/,
keywords:
'truncatewords removetags linebreaksbr yesno get_digit timesince random striptags ' +
'filesizeformat escape linebreaks length_is ljust rjust cut urlize fix_ampersands ' +
'title floatformat capfirst pprint divisibleby add make_list unordered_list urlencode ' +
'timeuntil urlizetrunc wordcount stringformat linenumbers slice date dictsort ' +
'dictsortreversed default_if_none pluralize lower join center default ' +
'truncatewords_html upper length phone2numeric wordwrap time addslashes slugify first ' +
'escapejs force_escape iriencode last safe safeseq truncatechars localize unlocalize ' +
'localtime utc timezone',
contains: [
{className: 'argument', begin: /"/, end: /"/},
{className: 'argument', begin: /'/, end: /'/}
]
};
return {
aliases: ['jinja'],
case_insensitive: true,
subLanguage: 'xml', subLanguageMode: 'continuous',
contains: [
{
className: 'comment',
begin: /\{%\s*comment\s*%}/, end: /\{%\s*endcomment\s*%}/
},
{
className: 'comment',
begin: /\{#/, end: /#}/
},
{
className: 'template_tag',
begin: /\{%/, end: /%}/,
keywords:
'comment endcomment load templatetag ifchanged endifchanged if endif firstof for ' +
'endfor in ifnotequal endifnotequal widthratio extends include spaceless ' +
'endspaceless regroup by as ifequal endifequal ssi now with cycle url filter ' +
'endfilter debug block endblock else autoescape endautoescape csrf_token empty elif ' +
'endwith static trans blocktrans endblocktrans get_static_prefix get_media_prefix ' +
'plural get_current_language language get_available_languages ' +
'get_current_language_bidi get_language_info get_language_info_list localize ' +
'endlocalize localtime endlocaltime timezone endtimezone get_current_timezone ' +
'verbatim',
contains: [FILTER]
},
{
className: 'variable',
begin: /\{\{/, end: /}}/,
contains: [FILTER]
}
]
};
}
| lgpl-2.1 |
MichaelMcDonnell/vrjuggler | external/swing-laf/kunststoff/sources/com/incors/plaf/kunststoff/KunststoffTabbedPaneUI.java | 3952 | package com.incors.plaf.kunststoff;
/*
* This code was developed by INCORS GmbH (www.incors.com)
* with contributions by Jamie LaScolea.
*
* It is published under the terms of the GNU Lesser General Public License.
*/
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.*;
public class KunststoffTabbedPaneUI extends BasicTabbedPaneUI {
private static final int SHADOW_WIDTH = 5;
public static ComponentUI createUI(JComponent c) {
return new KunststoffTabbedPaneUI();
}
protected void installDefaults() {
super.installDefaults();
}
/*
* Thanks to a contribution by Jamie LaScolea this method now works with
* multiple rows of tabs.
*/
protected void paintTab(Graphics g, int tabPlacement,
Rectangle[] rects, int tabIndex,
Rectangle iconRect, Rectangle textRect) {
super.paintTab(g, tabPlacement, rects, tabIndex, iconRect, textRect);
Graphics2D g2D = (Graphics2D) g;
Rectangle tabRect = rects[tabIndex];
Color colorShadow = KunststoffLookAndFeel.getComponentGradientColorShadow();
Color colorShadowFaded = KunststoffUtilities.getTranslucentColor(colorShadow, 0);
Color colorReflection = KunststoffLookAndFeel.getComponentGradientColorReflection();
Color colorReflectionFaded = KunststoffUtilities.getTranslucentColor(colorReflection, 0);
// paint shadow that the selected tab throws on the next tab
int selectedIndex = tabPane.getSelectedIndex();
// the following statement was added by Jamie LaScolea as a bug fix. Thanks Jamie!
if (this.lastTabInRun(tabPane.getTabCount(), this.selectedRun) != selectedIndex ){
if (tabPlacement == JTabbedPane.TOP || tabPlacement == JTabbedPane.BOTTOM) {
if (tabIndex == selectedIndex+1) {
Rectangle gradientRect = new Rectangle((int) tabRect.getX(), (int) tabRect.getY(), SHADOW_WIDTH, (int) tabRect.getHeight());
KunststoffUtilities.drawGradient(g, colorShadow, colorShadowFaded, gradientRect, false);
}
} else {
if (tabIndex == selectedIndex+1) {
Rectangle gradientRect = new Rectangle((int) tabRect.getX(), (int) tabRect.getY(), (int) tabRect.getWidth(), SHADOW_WIDTH);
KunststoffUtilities.drawGradient(g, colorShadow, colorShadowFaded, gradientRect, true);
}
}
}
if (tabPlacement == JTabbedPane.TOP) {
Rectangle gradientRect = new Rectangle((int) tabRect.getX(), (int) tabRect.getY(), (int) tabRect.getWidth(), (int) SHADOW_WIDTH);
KunststoffUtilities.drawGradient(g, colorReflection, colorReflectionFaded, gradientRect, true);
} else if (tabPlacement == JTabbedPane.BOTTOM) {
if (tabIndex != selectedIndex) {
Rectangle gradientRect = new Rectangle((int) tabRect.getX(), (int) tabRect.getY(), (int) tabRect.getWidth(), SHADOW_WIDTH);
KunststoffUtilities.drawGradient(g, colorShadow, colorShadowFaded, gradientRect, true);
}
} else if (tabPlacement == JTabbedPane.RIGHT) {
if (tabIndex != selectedIndex) {
Rectangle gradientRect = new Rectangle((int) tabRect.getX(), (int) tabRect.getY(), (int) SHADOW_WIDTH, (int) tabRect.getHeight());
KunststoffUtilities.drawGradient(g, colorShadow, colorShadowFaded, gradientRect, false);
}
}
}
protected void paintTabBackground(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected ) {
if ( isSelected ) {
g.setColor(UIManager.getColor("TabbedPane.selected"));
} else {
g.setColor(tabPane.getBackgroundAt(tabIndex));
}
switch(tabPlacement) {
case LEFT: g.fillRect(x+1, y+1, w-2, h-3);
break;
case RIGHT: g.fillRect(x, y+1, w-2, h-3);
break;
case BOTTOM: g.fillRect(x+1, y, w-3, h-1);
break;
case TOP: default: g.fillRect(x+1, y+1, w-3, h-1);
}
}
} | lgpl-2.1 |
KyuRicard/MagicMod | build/tmp/recompileMc/sources/net/minecraftforge/common/capabilities/CapabilityDispatcher.java | 3592 | package net.minecraftforge.common.capabilities;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.util.INBTSerializable;
/**
* A high-speed implementation of a capability delegator.
* This is used to wrap the results of the AttachCapabilitiesEvent.
* It is HIGHLY recommended that you DO NOT use this approach unless
* you MUST delegate to multiple providers instead just implement y
* our handlers using normal if statements.
*
* Internally the handlers are baked into arrays for fast iteration.
* The ResourceLocations will be used for the NBT Key when serializing.
*/
public final class CapabilityDispatcher implements INBTSerializable<NBTTagCompound>, ICapabilityProvider
{
private ICapabilityProvider[] caps;
private INBTSerializable<NBTBase>[] writers;
private String[] names;
public CapabilityDispatcher(Map<ResourceLocation, ICapabilityProvider> list)
{
this(list, null);
}
@SuppressWarnings("unchecked")
public CapabilityDispatcher(Map<ResourceLocation, ICapabilityProvider> list, ICapabilityProvider parent)
{
List<ICapabilityProvider> lstCaps = Lists.newArrayList();
List<INBTSerializable<NBTBase>> lstWriters = Lists.newArrayList();
List<String> lstNames = Lists.newArrayList();
if (parent != null) // Parents go first!
{
lstCaps.add(parent);
if (parent instanceof INBTSerializable)
{
lstWriters.add((INBTSerializable<NBTBase>)parent);
lstNames.add("Parent");
}
}
for (Map.Entry<ResourceLocation, ICapabilityProvider> entry : list.entrySet())
{
ICapabilityProvider prov = entry.getValue();
lstCaps.add(prov);
if (prov instanceof INBTSerializable)
{
lstWriters.add((INBTSerializable<NBTBase>)prov);
lstNames.add(entry.getKey().toString());
}
}
caps = lstCaps.toArray(new ICapabilityProvider[lstCaps.size()]);
writers = lstWriters.toArray(new INBTSerializable[lstWriters.size()]);
names = lstNames.toArray(new String[lstNames.size()]);
}
@Override
public boolean hasCapability(Capability<?> capability, EnumFacing facing)
{
for (ICapabilityProvider cap : caps)
{
if (cap.hasCapability(capability, facing))
{
return true;
}
}
return false;
}
@Override
public <T> T getCapability(Capability<T> capability, EnumFacing facing)
{
for (ICapabilityProvider cap : caps)
{
T ret = cap.getCapability(capability, facing);
if (ret != null)
{
return ret;
}
}
return null;
}
@Override
public NBTTagCompound serializeNBT()
{
NBTTagCompound nbt = new NBTTagCompound();
for (int x = 0; x < writers.length; x++)
{
nbt.setTag(names[x], writers[x].serializeNBT());
}
return nbt;
}
@Override
public void deserializeNBT(NBTTagCompound nbt)
{
for (int x = 0; x < writers.length; x++)
{
if (nbt.hasKey(names[x]))
{
writers[x].deserializeNBT(nbt.getTag(names[x]));
}
}
}
} | lgpl-2.1 |
Tybion/community-edition | projects/repository/source/java/org/alfresco/service/cmr/webdav/WebDavService.java | 1597 | /*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.service.cmr.webdav;
import org.alfresco.service.cmr.repository.NodeRef;
public interface WebDavService
{
/**
* Get the WebDavUrl for the specified nodeRef
* @param nodeRef the node that the webdav URL (or null)
* @return the URL of the node in webdav or "" if a URL cannot be built.
*/
public String getWebdavUrl(NodeRef nodeRef);
/**
* Determines whether activity post generation is enabled for WebDAV. When enabled,
* file creation, modification and deletion will create activities that can be viewed
* in the Share web client.
*
* @return true if activity generation is enabled.
*/
public boolean activitiesEnabled();
/**
* Is the web dav service enabled?
* @return true, is enabled
*/
public boolean getEnabled();
}
| lgpl-3.0 |
smba/oak | edu.cmu.cs.oak/src/test/resources/mediawiki/includes/filerepo/file/File.php | 59954 | <?php
/**
* @defgroup FileAbstraction File abstraction
* @ingroup FileRepo
*
* Represents files in a repository.
*/
/**
* Base code for files.
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup FileAbstraction
*/
/**
* Implements some public methods and some protected utility functions which
* are required by multiple child classes. Contains stub functionality for
* unimplemented public methods.
*
* Stub functions which should be overridden are marked with STUB. Some more
* concrete functions are also typically overridden by child classes.
*
* Note that only the repo object knows what its file class is called. You should
* never name a file class explictly outside of the repo class. Instead use the
* repo's factory functions to generate file objects, for example:
*
* RepoGroup::singleton()->getLocalRepo()->newFile( $title );
*
* The convenience functions wfLocalFile() and wfFindFile() should be sufficient
* in most cases.
*
* @ingroup FileAbstraction
*/
abstract class File implements IDBAccessObject {
// Bitfield values akin to the Revision deletion constants
const DELETED_FILE = 1;
const DELETED_COMMENT = 2;
const DELETED_USER = 4;
const DELETED_RESTRICTED = 8;
/** Force rendering in the current process */
const RENDER_NOW = 1;
/**
* Force rendering even if thumbnail already exist and using RENDER_NOW
* I.e. you have to pass both flags: File::RENDER_NOW | File::RENDER_FORCE
*/
const RENDER_FORCE = 2;
const DELETE_SOURCE = 1;
// Audience options for File::getDescription()
const FOR_PUBLIC = 1;
const FOR_THIS_USER = 2;
const RAW = 3;
// Options for File::thumbName()
const THUMB_FULL_NAME = 1;
/**
* Some member variables can be lazy-initialised using __get(). The
* initialisation function for these variables is always a function named
* like getVar(), where Var is the variable name with upper-case first
* letter.
*
* The following variables are initialised in this way in this base class:
* name, extension, handler, path, canRender, isSafeFile,
* transformScript, hashPath, pageCount, url
*
* Code within this class should generally use the accessor function
* directly, since __get() isn't re-entrant and therefore causes bugs that
* depend on initialisation order.
*/
/**
* The following member variables are not lazy-initialised
*/
/** @var FileRepo|LocalRepo|ForeignAPIRepo|bool */
public $repo;
/** @var Title|string|bool */
protected $title;
/** @var string Text of last error */
protected $lastError;
/** @var string Main part of the title, with underscores (Title::getDBkey) */
protected $redirected;
/** @var Title */
protected $redirectedTitle;
/** @var FSFile|bool False if undefined */
protected $fsFile;
/** @var MediaHandler */
protected $handler;
/** @var string The URL corresponding to one of the four basic zones */
protected $url;
/** @var string File extension */
protected $extension;
/** @var string The name of a file from its title object */
protected $name;
/** @var string The storage path corresponding to one of the zones */
protected $path;
/** @var string Relative path including trailing slash */
protected $hashPath;
/** @var string Number of pages of a multipage document, or false for
* documents which aren't multipage documents
*/
protected $pageCount;
/** @var string URL of transformscript (for example thumb.php) */
protected $transformScript;
/** @var Title */
protected $redirectTitle;
/** @var bool Whether the output of transform() for this file is likely to be valid. */
protected $canRender;
/** @var bool Whether this media file is in a format that is unlikely to
* contain viruses or malicious content
*/
protected $isSafeFile;
/** @var string Required Repository class type */
protected $repoClass = 'FileRepo';
/** @var array Cache of tmp filepaths pointing to generated bucket thumbnails, keyed by width */
protected $tmpBucketedThumbCache = [];
/**
* Call this constructor from child classes.
*
* Both $title and $repo are optional, though some functions
* may return false or throw exceptions if they are not set.
* Most subclasses will want to call assertRepoDefined() here.
*
* @param Title|string|bool $title
* @param FileRepo|bool $repo
*/
function __construct( $title, $repo ) {
// Some subclasses do not use $title, but set name/title some other way
if ( $title !== false ) {
$title = self::normalizeTitle( $title, 'exception' );
}
$this->title = $title;
$this->repo = $repo;
}
/**
* Given a string or Title object return either a
* valid Title object with namespace NS_FILE or null
*
* @param Title|string $title
* @param string|bool $exception Use 'exception' to throw an error on bad titles
* @throws MWException
* @return Title|null
*/
static function normalizeTitle( $title, $exception = false ) {
$ret = $title;
if ( $ret instanceof Title ) {
# Normalize NS_MEDIA -> NS_FILE
if ( $ret->getNamespace() == NS_MEDIA ) {
$ret = Title::makeTitleSafe( NS_FILE, $ret->getDBkey() );
# Sanity check the title namespace
} elseif ( $ret->getNamespace() !== NS_FILE ) {
$ret = null;
}
} else {
# Convert strings to Title objects
$ret = Title::makeTitleSafe( NS_FILE, (string)$ret );
}
if ( !$ret && $exception !== false ) {
throw new MWException( "`$title` is not a valid file title." );
}
return $ret;
}
function __get( $name ) {
$function = [ $this, 'get' . ucfirst( $name ) ];
if ( !is_callable( $function ) ) {
return null;
} else {
$this->$name = call_user_func( $function );
return $this->$name;
}
}
/**
* Normalize a file extension to the common form, making it lowercase and checking some synonyms,
* and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
* Keep in sync with mw.Title.normalizeExtension() in JS.
*
* @param string $extension File extension (without the leading dot)
* @return string File extension in canonical form
*/
static function normalizeExtension( $extension ) {
$lower = strtolower( $extension );
$squish = [
'htm' => 'html',
'jpeg' => 'jpg',
'mpeg' => 'mpg',
'tiff' => 'tif',
'ogv' => 'ogg' ];
if ( isset( $squish[$lower] ) ) {
return $squish[$lower];
} elseif ( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
return $lower;
} else {
return '';
}
}
/**
* Checks if file extensions are compatible
*
* @param File $old Old file
* @param string $new New name
*
* @return bool|null
*/
static function checkExtensionCompatibility( File $old, $new ) {
$oldMime = $old->getMimeType();
$n = strrpos( $new, '.' );
$newExt = self::normalizeExtension( $n ? substr( $new, $n + 1 ) : '' );
$mimeMagic = MimeMagic::singleton();
return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
}
/**
* Upgrade the database row if there is one
* Called by ImagePage
* STUB
*/
function upgradeRow() {
}
/**
* Split an internet media type into its two components; if not
* a two-part name, set the minor type to 'unknown'.
*
* @param string $mime "text/html" etc
* @return array ("text", "html") etc
*/
public static function splitMime( $mime ) {
if ( strpos( $mime, '/' ) !== false ) {
return explode( '/', $mime, 2 );
} else {
return [ $mime, 'unknown' ];
}
}
/**
* Callback for usort() to do file sorts by name
*
* @param File $a
* @param File $b
* @return int Result of name comparison
*/
public static function compare( File $a, File $b ) {
return strcmp( $a->getName(), $b->getName() );
}
/**
* Return the name of this file
*
* @return string
*/
public function getName() {
if ( !isset( $this->name ) ) {
$this->assertRepoDefined();
$this->name = $this->repo->getNameFromTitle( $this->title );
}
return $this->name;
}
/**
* Get the file extension, e.g. "svg"
*
* @return string
*/
function getExtension() {
if ( !isset( $this->extension ) ) {
$n = strrpos( $this->getName(), '.' );
$this->extension = self::normalizeExtension(
$n ? substr( $this->getName(), $n + 1 ) : '' );
}
return $this->extension;
}
/**
* Return the associated title object
*
* @return Title
*/
public function getTitle() {
return $this->title;
}
/**
* Return the title used to find this file
*
* @return Title
*/
public function getOriginalTitle() {
if ( $this->redirected ) {
return $this->getRedirectedTitle();
}
return $this->title;
}
/**
* Return the URL of the file
*
* @return string
*/
public function getUrl() {
if ( !isset( $this->url ) ) {
$this->assertRepoDefined();
$ext = $this->getExtension();
$this->url = $this->repo->getZoneUrl( 'public', $ext ) . '/' . $this->getUrlRel();
}
return $this->url;
}
/*
* Get short description URL for a files based on the page ID
*
* @return string|null
* @since 1.27
*/
public function getDescriptionShortUrl() {
return null;
}
/**
* Return a fully-qualified URL to the file.
* Upload URL paths _may or may not_ be fully qualified, so
* we check. Local paths are assumed to belong on $wgServer.
*
* @return string
*/
public function getFullUrl() {
return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE );
}
/**
* @return string
*/
public function getCanonicalUrl() {
return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL );
}
/**
* @return string
*/
function getViewURL() {
if ( $this->mustRender() ) {
if ( $this->canRender() ) {
return $this->createThumb( $this->getWidth() );
} else {
wfDebug( __METHOD__ . ': supposed to render ' . $this->getName() .
' (' . $this->getMimeType() . "), but can't!\n" );
return $this->getUrl(); # hm... return NULL?
}
} else {
return $this->getUrl();
}
}
/**
* Return the storage path to the file. Note that this does
* not mean that a file actually exists under that location.
*
* This path depends on whether directory hashing is active or not,
* i.e. whether the files are all found in the same directory,
* or in hashed paths like /images/3/3c.
*
* Most callers don't check the return value, but ForeignAPIFile::getPath
* returns false.
*
* @return string|bool ForeignAPIFile::getPath can return false
*/
public function getPath() {
if ( !isset( $this->path ) ) {
$this->assertRepoDefined();
$this->path = $this->repo->getZonePath( 'public' ) . '/' . $this->getRel();
}
return $this->path;
}
/**
* Get an FS copy or original of this file and return the path.
* Returns false on failure. Callers must not alter the file.
* Temporary files are cleared automatically.
*
* @return string|bool False on failure
*/
public function getLocalRefPath() {
$this->assertRepoDefined();
if ( !isset( $this->fsFile ) ) {
$starttime = microtime( true );
$this->fsFile = $this->repo->getLocalReference( $this->getPath() );
$statTiming = microtime( true ) - $starttime;
RequestContext::getMain()->getStats()->timing(
'media.thumbnail.generate.fetchoriginal', 1000 * $statTiming );
if ( !$this->fsFile ) {
$this->fsFile = false; // null => false; cache negative hits
}
}
return ( $this->fsFile )
? $this->fsFile->getPath()
: false;
}
/**
* Return the width of the image. Returns false if the width is unknown
* or undefined.
*
* STUB
* Overridden by LocalFile, UnregisteredLocalFile
*
* @param int $page
* @return int|bool
*/
public function getWidth( $page = 1 ) {
return false;
}
/**
* Return the height of the image. Returns false if the height is unknown
* or undefined
*
* STUB
* Overridden by LocalFile, UnregisteredLocalFile
*
* @param int $page
* @return bool|int False on failure
*/
public function getHeight( $page = 1 ) {
return false;
}
/**
* Return the smallest bucket from $wgThumbnailBuckets which is at least
* $wgThumbnailMinimumBucketDistance larger than $desiredWidth. The returned bucket, if any,
* will always be bigger than $desiredWidth.
*
* @param int $desiredWidth
* @param int $page
* @return bool|int
*/
public function getThumbnailBucket( $desiredWidth, $page = 1 ) {
global $wgThumbnailBuckets, $wgThumbnailMinimumBucketDistance;
$imageWidth = $this->getWidth( $page );
if ( $imageWidth === false ) {
return false;
}
if ( $desiredWidth > $imageWidth ) {
return false;
}
if ( !$wgThumbnailBuckets ) {
return false;
}
$sortedBuckets = $wgThumbnailBuckets;
sort( $sortedBuckets );
foreach ( $sortedBuckets as $bucket ) {
if ( $bucket >= $imageWidth ) {
return false;
}
if ( $bucket - $wgThumbnailMinimumBucketDistance > $desiredWidth ) {
return $bucket;
}
}
// Image is bigger than any available bucket
return false;
}
/**
* Returns ID or name of user who uploaded the file
* STUB
*
* @param string $type 'text' or 'id'
* @return string|int
*/
public function getUser( $type = 'text' ) {
return null;
}
/**
* Get the duration of a media file in seconds
*
* @return int
*/
public function getLength() {
$handler = $this->getHandler();
if ( $handler ) {
return $handler->getLength( $this );
} else {
return 0;
}
}
/**
* Return true if the file is vectorized
*
* @return bool
*/
public function isVectorized() {
$handler = $this->getHandler();
if ( $handler ) {
return $handler->isVectorized( $this );
} else {
return false;
}
}
/**
* Gives a (possibly empty) list of languages to render
* the file in.
*
* If the file doesn't have translations, or if the file
* format does not support that sort of thing, returns
* an empty array.
*
* @return array
* @since 1.23
*/
public function getAvailableLanguages() {
$handler = $this->getHandler();
if ( $handler ) {
return $handler->getAvailableLanguages( $this );
} else {
return [];
}
}
/**
* In files that support multiple language, what is the default language
* to use if none specified.
*
* @return string|null Lang code, or null if filetype doesn't support multiple languages.
* @since 1.23
*/
public function getDefaultRenderLanguage() {
$handler = $this->getHandler();
if ( $handler ) {
return $handler->getDefaultRenderLanguage( $this );
} else {
return null;
}
}
/**
* Will the thumbnail be animated if one would expect it to be.
*
* Currently used to add a warning to the image description page
*
* @return bool False if the main image is both animated
* and the thumbnail is not. In all other cases must return
* true. If image is not renderable whatsoever, should
* return true.
*/
public function canAnimateThumbIfAppropriate() {
$handler = $this->getHandler();
if ( !$handler ) {
// We cannot handle image whatsoever, thus
// one would not expect it to be animated
// so true.
return true;
} else {
if ( $this->allowInlineDisplay()
&& $handler->isAnimatedImage( $this )
&& !$handler->canAnimateThumbnail( $this )
) {
// Image is animated, but thumbnail isn't.
// This is unexpected to the user.
return false;
} else {
// Image is not animated, so one would
// not expect thumb to be
return true;
}
}
}
/**
* Get handler-specific metadata
* Overridden by LocalFile, UnregisteredLocalFile
* STUB
* @return bool|array
*/
public function getMetadata() {
return false;
}
/**
* Like getMetadata but returns a handler independent array of common values.
* @see MediaHandler::getCommonMetaArray()
* @return array|bool Array or false if not supported
* @since 1.23
*/
public function getCommonMetaArray() {
$handler = $this->getHandler();
if ( !$handler ) {
return false;
}
return $handler->getCommonMetaArray( $this );
}
/**
* get versioned metadata
*
* @param array|string $metadata Array or string of (serialized) metadata
* @param int $version Version number.
* @return array Array containing metadata, or what was passed to it on fail
* (unserializing if not array)
*/
public function convertMetadataVersion( $metadata, $version ) {
$handler = $this->getHandler();
if ( !is_array( $metadata ) ) {
// Just to make the return type consistent
$metadata = unserialize( $metadata );
}
if ( $handler ) {
return $handler->convertMetadataVersion( $metadata, $version );
} else {
return $metadata;
}
}
/**
* Return the bit depth of the file
* Overridden by LocalFile
* STUB
* @return int
*/
public function getBitDepth() {
return 0;
}
/**
* Return the size of the image file, in bytes
* Overridden by LocalFile, UnregisteredLocalFile
* STUB
* @return bool
*/
public function getSize() {
return false;
}
/**
* Returns the MIME type of the file.
* Overridden by LocalFile, UnregisteredLocalFile
* STUB
*
* @return string
*/
function getMimeType() {
return 'unknown/unknown';
}
/**
* Return the type of the media in the file.
* Use the value returned by this function with the MEDIATYPE_xxx constants.
* Overridden by LocalFile,
* STUB
* @return string
*/
function getMediaType() {
return MEDIATYPE_UNKNOWN;
}
/**
* Checks if the output of transform() for this file is likely
* to be valid. If this is false, various user elements will
* display a placeholder instead.
*
* Currently, this checks if the file is an image format
* that can be converted to a format
* supported by all browsers (namely GIF, PNG and JPEG),
* or if it is an SVG image and SVG conversion is enabled.
*
* @return bool
*/
function canRender() {
if ( !isset( $this->canRender ) ) {
$this->canRender = $this->getHandler() && $this->handler->canRender( $this ) && $this->exists();
}
return $this->canRender;
}
/**
* Accessor for __get()
* @return bool
*/
protected function getCanRender() {
return $this->canRender();
}
/**
* Return true if the file is of a type that can't be directly
* rendered by typical browsers and needs to be re-rasterized.
*
* This returns true for everything but the bitmap types
* supported by all browsers, i.e. JPEG; GIF and PNG. It will
* also return true for any non-image formats.
*
* @return bool
*/
function mustRender() {
return $this->getHandler() && $this->handler->mustRender( $this );
}
/**
* Alias for canRender()
*
* @return bool
*/
function allowInlineDisplay() {
return $this->canRender();
}
/**
* Determines if this media file is in a format that is unlikely to
* contain viruses or malicious content. It uses the global
* $wgTrustedMediaFormats list to determine if the file is safe.
*
* This is used to show a warning on the description page of non-safe files.
* It may also be used to disallow direct [[media:...]] links to such files.
*
* Note that this function will always return true if allowInlineDisplay()
* or isTrustedFile() is true for this file.
*
* @return bool
*/
function isSafeFile() {
if ( !isset( $this->isSafeFile ) ) {
$this->isSafeFile = $this->getIsSafeFileUncached();
}
return $this->isSafeFile;
}
/**
* Accessor for __get()
*
* @return bool
*/
protected function getIsSafeFile() {
return $this->isSafeFile();
}
/**
* Uncached accessor
*
* @return bool
*/
protected function getIsSafeFileUncached() {
global $wgTrustedMediaFormats;
if ( $this->allowInlineDisplay() ) {
return true;
}
if ( $this->isTrustedFile() ) {
return true;
}
$type = $this->getMediaType();
$mime = $this->getMimeType();
# wfDebug( "LocalFile::isSafeFile: type= $type, mime= $mime\n" );
if ( !$type || $type === MEDIATYPE_UNKNOWN ) {
return false; # unknown type, not trusted
}
if ( in_array( $type, $wgTrustedMediaFormats ) ) {
return true;
}
if ( $mime === "unknown/unknown" ) {
return false; # unknown type, not trusted
}
if ( in_array( $mime, $wgTrustedMediaFormats ) ) {
return true;
}
return false;
}
/**
* Returns true if the file is flagged as trusted. Files flagged that way
* can be linked to directly, even if that is not allowed for this type of
* file normally.
*
* This is a dummy function right now and always returns false. It could be
* implemented to extract a flag from the database. The trusted flag could be
* set on upload, if the user has sufficient privileges, to bypass script-
* and html-filters. It may even be coupled with cryptographics signatures
* or such.
*
* @return bool
*/
function isTrustedFile() {
# this could be implemented to check a flag in the database,
# look for signatures, etc
return false;
}
/**
* Load any lazy-loaded file object fields from source
*
* This is only useful when setting $flags
*
* Overridden by LocalFile to actually query the DB
*
* @param integer $flags Bitfield of File::READ_* constants
*/
public function load( $flags = 0 ) {
}
/**
* Returns true if file exists in the repository.
*
* Overridden by LocalFile to avoid unnecessary stat calls.
*
* @return bool Whether file exists in the repository.
*/
public function exists() {
return $this->getPath() && $this->repo->fileExists( $this->path );
}
/**
* Returns true if file exists in the repository and can be included in a page.
* It would be unsafe to include private images, making public thumbnails inadvertently
*
* @return bool Whether file exists in the repository and is includable.
*/
public function isVisible() {
return $this->exists();
}
/**
* @return string
*/
function getTransformScript() {
if ( !isset( $this->transformScript ) ) {
$this->transformScript = false;
if ( $this->repo ) {
$script = $this->repo->getThumbScriptUrl();
if ( $script ) {
$this->transformScript = wfAppendQuery( $script, [ 'f' => $this->getName() ] );
}
}
}
return $this->transformScript;
}
/**
* Get a ThumbnailImage which is the same size as the source
*
* @param array $handlerParams
*
* @return string
*/
function getUnscaledThumb( $handlerParams = [] ) {
$hp =& $handlerParams;
$page = isset( $hp['page'] ) ? $hp['page'] : false;
$width = $this->getWidth( $page );
if ( !$width ) {
return $this->iconThumb();
}
$hp['width'] = $width;
// be sure to ignore any height specification as well (bug 62258)
unset( $hp['height'] );
return $this->transform( $hp );
}
/**
* Return the file name of a thumbnail with the specified parameters.
* Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
* Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
*
* @param array $params Handler-specific parameters
* @param int $flags Bitfield that supports THUMB_* constants
* @return string|null
*/
public function thumbName( $params, $flags = 0 ) {
$name = ( $this->repo && !( $flags & self::THUMB_FULL_NAME ) )
? $this->repo->nameForThumb( $this->getName() )
: $this->getName();
return $this->generateThumbName( $name, $params );
}
/**
* Generate a thumbnail file name from a name and specified parameters
*
* @param string $name
* @param array $params Parameters which will be passed to MediaHandler::makeParamString
* @return string|null
*/
public function generateThumbName( $name, $params ) {
if ( !$this->getHandler() ) {
return null;
}
$extension = $this->getExtension();
list( $thumbExt, ) = $this->getHandler()->getThumbType(
$extension, $this->getMimeType(), $params );
$thumbName = $this->getHandler()->makeParamString( $params );
if ( $this->repo->supportsSha1URLs() ) {
$thumbName .= '-' . $this->getSha1() . '.' . $thumbExt;
} else {
$thumbName .= '-' . $name;
if ( $thumbExt != $extension ) {
$thumbName .= ".$thumbExt";
}
}
return $thumbName;
}
/**
* Create a thumbnail of the image having the specified width/height.
* The thumbnail will not be created if the width is larger than the
* image's width. Let the browser do the scaling in this case.
* The thumbnail is stored on disk and is only computed if the thumbnail
* file does not exist OR if it is older than the image.
* Returns the URL.
*
* Keeps aspect ratio of original image. If both width and height are
* specified, the generated image will be no bigger than width x height,
* and will also have correct aspect ratio.
*
* @param int $width Maximum width of the generated thumbnail
* @param int $height Maximum height of the image (optional)
*
* @return string
*/
public function createThumb( $width, $height = -1 ) {
$params = [ 'width' => $width ];
if ( $height != -1 ) {
$params['height'] = $height;
}
$thumb = $this->transform( $params );
if ( !$thumb || $thumb->isError() ) {
return '';
}
return $thumb->getUrl();
}
/**
* Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
*
* @param string $thumbPath Thumbnail storage path
* @param string $thumbUrl Thumbnail URL
* @param array $params
* @param int $flags
* @return MediaTransformOutput
*/
protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
global $wgIgnoreImageErrors;
$handler = $this->getHandler();
if ( $handler && $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
return $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
} else {
return new MediaTransformError( 'thumbnail_error',
$params['width'], 0, wfMessage( 'thumbnail-dest-create' )->text() );
}
}
/**
* Transform a media file
*
* @param array $params An associative array of handler-specific parameters.
* Typical keys are width, height and page.
* @param int $flags A bitfield, may contain self::RENDER_NOW to force rendering
* @return MediaTransformOutput|bool False on failure
*/
function transform( $params, $flags = 0 ) {
global $wgThumbnailEpoch;
do {
if ( !$this->canRender() ) {
$thumb = $this->iconThumb();
break; // not a bitmap or renderable image, don't try
}
// Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
$descriptionUrl = $this->getDescriptionUrl();
if ( $descriptionUrl ) {
$params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL );
}
$handler = $this->getHandler();
$script = $this->getTransformScript();
if ( $script && !( $flags & self::RENDER_NOW ) ) {
// Use a script to transform on client request, if possible
$thumb = $handler->getScriptedTransform( $this, $script, $params );
if ( $thumb ) {
break;
}
}
$normalisedParams = $params;
$handler->normaliseParams( $this, $normalisedParams );
$thumbName = $this->thumbName( $normalisedParams );
$thumbUrl = $this->getThumbUrl( $thumbName );
$thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
if ( $this->repo ) {
// Defer rendering if a 404 handler is set up...
if ( $this->repo->canTransformVia404() && !( $flags & self::RENDER_NOW ) ) {
wfDebug( __METHOD__ . " transformation deferred.\n" );
// XXX: Pass in the storage path even though we are not rendering anything
// and the path is supposed to be an FS path. This is due to getScalerType()
// getting called on the path and clobbering $thumb->getUrl() if it's false.
$thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
break;
}
// Check if an up-to-date thumbnail already exists...
wfDebug( __METHOD__ . ": Doing stat for $thumbPath\n" );
if ( !( $flags & self::RENDER_FORCE ) && $this->repo->fileExists( $thumbPath ) ) {
$timestamp = $this->repo->getFileTimestamp( $thumbPath );
if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
// XXX: Pass in the storage path even though we are not rendering anything
// and the path is supposed to be an FS path. This is due to getScalerType()
// getting called on the path and clobbering $thumb->getUrl() if it's false.
$thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
$thumb->setStoragePath( $thumbPath );
break;
}
} elseif ( $flags & self::RENDER_FORCE ) {
wfDebug( __METHOD__ . " forcing rendering per flag File::RENDER_FORCE\n" );
}
// If the backend is ready-only, don't keep generating thumbnails
// only to return transformation errors, just return the error now.
if ( $this->repo->getReadOnlyReason() !== false ) {
$thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
break;
}
}
$tmpFile = $this->makeTransformTmpFile( $thumbPath );
if ( !$tmpFile ) {
$thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
} else {
$thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
}
} while ( false );
return is_object( $thumb ) ? $thumb : false;
}
/**
* Generates a thumbnail according to the given parameters and saves it to storage
* @param TempFSFile $tmpFile Temporary file where the rendered thumbnail will be saved
* @param array $transformParams
* @param int $flags
* @return bool|MediaTransformOutput
*/
public function generateAndSaveThumb( $tmpFile, $transformParams, $flags ) {
global $wgIgnoreImageErrors;
$stats = RequestContext::getMain()->getStats();
$handler = $this->getHandler();
$normalisedParams = $transformParams;
$handler->normaliseParams( $this, $normalisedParams );
$thumbName = $this->thumbName( $normalisedParams );
$thumbUrl = $this->getThumbUrl( $thumbName );
$thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
$tmpThumbPath = $tmpFile->getPath();
if ( $handler->supportsBucketing() ) {
$this->generateBucketsIfNeeded( $normalisedParams, $flags );
}
$starttime = microtime( true );
// Actually render the thumbnail...
$thumb = $handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
$tmpFile->bind( $thumb ); // keep alive with $thumb
$statTiming = microtime( true ) - $starttime;
$stats->timing( 'media.thumbnail.generate.transform', 1000 * $statTiming );
if ( !$thumb ) { // bad params?
$thumb = false;
} elseif ( $thumb->isError() ) { // transform error
/** @var $thumb MediaTransformError */
$this->lastError = $thumb->toText();
// Ignore errors if requested
if ( $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
$thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
}
} elseif ( $this->repo && $thumb->hasFile() && !$thumb->fileIsSource() ) {
// Copy the thumbnail from the file system into storage...
$starttime = microtime( true );
$disposition = $this->getThumbDisposition( $thumbName );
$status = $this->repo->quickImport( $tmpThumbPath, $thumbPath, $disposition );
if ( $status->isOK() ) {
$thumb->setStoragePath( $thumbPath );
} else {
$thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $transformParams, $flags );
}
$statTiming = microtime( true ) - $starttime;
$stats->timing( 'media.thumbnail.generate.store', 1000 * $statTiming );
// Give extensions a chance to do something with this thumbnail...
Hooks::run( 'FileTransformed', [ $this, $thumb, $tmpThumbPath, $thumbPath ] );
}
return $thumb;
}
/**
* Generates chained bucketed thumbnails if needed
* @param array $params
* @param int $flags
* @return bool Whether at least one bucket was generated
*/
protected function generateBucketsIfNeeded( $params, $flags = 0 ) {
if ( !$this->repo
|| !isset( $params['physicalWidth'] )
|| !isset( $params['physicalHeight'] )
) {
return false;
}
$bucket = $this->getThumbnailBucket( $params['physicalWidth'] );
if ( !$bucket || $bucket == $params['physicalWidth'] ) {
return false;
}
$bucketPath = $this->getBucketThumbPath( $bucket );
if ( $this->repo->fileExists( $bucketPath ) ) {
return false;
}
$starttime = microtime( true );
$params['physicalWidth'] = $bucket;
$params['width'] = $bucket;
$params = $this->getHandler()->sanitizeParamsForBucketing( $params );
$tmpFile = $this->makeTransformTmpFile( $bucketPath );
if ( !$tmpFile ) {
return false;
}
$thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
$buckettime = microtime( true ) - $starttime;
if ( !$thumb || $thumb->isError() ) {
return false;
}
$this->tmpBucketedThumbCache[$bucket] = $tmpFile->getPath();
// For the caching to work, we need to make the tmp file survive as long as
// this object exists
$tmpFile->bind( $this );
RequestContext::getMain()->getStats()->timing(
'media.thumbnail.generate.bucket', 1000 * $buckettime );
return true;
}
/**
* Returns the most appropriate source image for the thumbnail, given a target thumbnail size
* @param array $params
* @return array Source path and width/height of the source
*/
public function getThumbnailSource( $params ) {
if ( $this->repo
&& $this->getHandler()->supportsBucketing()
&& isset( $params['physicalWidth'] )
&& $bucket = $this->getThumbnailBucket( $params['physicalWidth'] )
) {
if ( $this->getWidth() != 0 ) {
$bucketHeight = round( $this->getHeight() * ( $bucket / $this->getWidth() ) );
} else {
$bucketHeight = 0;
}
// Try to avoid reading from storage if the file was generated by this script
if ( isset( $this->tmpBucketedThumbCache[$bucket] ) ) {
$tmpPath = $this->tmpBucketedThumbCache[$bucket];
if ( file_exists( $tmpPath ) ) {
return [
'path' => $tmpPath,
'width' => $bucket,
'height' => $bucketHeight
];
}
}
$bucketPath = $this->getBucketThumbPath( $bucket );
if ( $this->repo->fileExists( $bucketPath ) ) {
$fsFile = $this->repo->getLocalReference( $bucketPath );
if ( $fsFile ) {
return [
'path' => $fsFile->getPath(),
'width' => $bucket,
'height' => $bucketHeight
];
}
}
}
// Thumbnailing a very large file could result in network saturation if
// everyone does it at once.
if ( $this->getSize() >= 1e7 ) { // 10MB
$that = $this;
$work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $this->getName() ),
[
'doWork' => function () use ( $that ) {
return $that->getLocalRefPath();
}
]
);
$srcPath = $work->execute();
} else {
$srcPath = $this->getLocalRefPath();
}
// Original file
return [
'path' => $srcPath,
'width' => $this->getWidth(),
'height' => $this->getHeight()
];
}
/**
* Returns the repo path of the thumb for a given bucket
* @param int $bucket
* @return string
*/
protected function getBucketThumbPath( $bucket ) {
$thumbName = $this->getBucketThumbName( $bucket );
return $this->getThumbPath( $thumbName );
}
/**
* Returns the name of the thumb for a given bucket
* @param int $bucket
* @return string
*/
protected function getBucketThumbName( $bucket ) {
return $this->thumbName( [ 'physicalWidth' => $bucket ] );
}
/**
* Creates a temp FS file with the same extension and the thumbnail
* @param string $thumbPath Thumbnail path
* @return TempFSFile
*/
protected function makeTransformTmpFile( $thumbPath ) {
$thumbExt = FileBackend::extensionFromPath( $thumbPath );
return TempFSFile::factory( 'transform_', $thumbExt );
}
/**
* @param string $thumbName Thumbnail name
* @param string $dispositionType Type of disposition (either "attachment" or "inline")
* @return string Content-Disposition header value
*/
function getThumbDisposition( $thumbName, $dispositionType = 'inline' ) {
$fileName = $this->name; // file name to suggest
$thumbExt = FileBackend::extensionFromPath( $thumbName );
if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
$fileName .= ".$thumbExt";
}
return FileBackend::makeContentDisposition( $dispositionType, $fileName );
}
/**
* Hook into transform() to allow migration of thumbnail files
* STUB
* Overridden by LocalFile
* @param string $thumbName
*/
function migrateThumbFile( $thumbName ) {
}
/**
* Get a MediaHandler instance for this file
*
* @return MediaHandler|bool Registered MediaHandler for file's MIME type
* or false if none found
*/
function getHandler() {
if ( !isset( $this->handler ) ) {
$this->handler = MediaHandler::getHandler( $this->getMimeType() );
}
return $this->handler;
}
/**
* Get a ThumbnailImage representing a file type icon
*
* @return ThumbnailImage
*/
function iconThumb() {
global $wgResourceBasePath, $IP;
$assetsPath = "$wgResourceBasePath/resources/assets/file-type-icons/";
$assetsDirectory = "$IP/resources/assets/file-type-icons/";
$try = [ 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' ];
foreach ( $try as $icon ) {
if ( file_exists( $assetsDirectory . $icon ) ) { // always FS
$params = [ 'width' => 120, 'height' => 120 ];
return new ThumbnailImage( $this, $assetsPath . $icon, false, $params );
}
}
return null;
}
/**
* Get last thumbnailing error.
* Largely obsolete.
* @return string
*/
function getLastError() {
return $this->lastError;
}
/**
* Get all thumbnail names previously generated for this file
* STUB
* Overridden by LocalFile
* @return array
*/
function getThumbnails() {
return [];
}
/**
* Purge shared caches such as thumbnails and DB data caching
* STUB
* Overridden by LocalFile
* @param array $options Options, which include:
* 'forThumbRefresh' : The purging is only to refresh thumbnails
*/
function purgeCache( $options = [] ) {
}
/**
* Purge the file description page, but don't go after
* pages using the file. Use when modifying file history
* but not the current data.
*/
function purgeDescription() {
$title = $this->getTitle();
if ( $title ) {
$title->invalidateCache();
$title->purgeSquid();
}
}
/**
* Purge metadata and all affected pages when the file is created,
* deleted, or majorly updated.
*/
function purgeEverything() {
// Delete thumbnails and refresh file metadata cache
$this->purgeCache();
$this->purgeDescription();
// Purge cache of all pages using this file
$title = $this->getTitle();
if ( $title ) {
DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
}
}
/**
* Return a fragment of the history of file.
*
* STUB
* @param int $limit Limit of rows to return
* @param string $start Only revisions older than $start will be returned
* @param string $end Only revisions newer than $end will be returned
* @param bool $inc Include the endpoints of the time range
*
* @return File[]
*/
function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
return [];
}
/**
* Return the history of this file, line by line. Starts with current version,
* then old versions. Should return an object similar to an image/oldimage
* database row.
*
* STUB
* Overridden in LocalFile
* @return bool
*/
public function nextHistoryLine() {
return false;
}
/**
* Reset the history pointer to the first element of the history.
* Always call this function after using nextHistoryLine() to free db resources
* STUB
* Overridden in LocalFile.
*/
public function resetHistory() {
}
/**
* Get the filename hash component of the directory including trailing slash,
* e.g. f/fa/
* If the repository is not hashed, returns an empty string.
*
* @return string
*/
function getHashPath() {
if ( !isset( $this->hashPath ) ) {
$this->assertRepoDefined();
$this->hashPath = $this->repo->getHashPath( $this->getName() );
}
return $this->hashPath;
}
/**
* Get the path of the file relative to the public zone root.
* This function is overridden in OldLocalFile to be like getArchiveRel().
*
* @return string
*/
function getRel() {
return $this->getHashPath() . $this->getName();
}
/**
* Get the path of an archived file relative to the public zone root
*
* @param bool|string $suffix If not false, the name of an archived thumbnail file
*
* @return string
*/
function getArchiveRel( $suffix = false ) {
$path = 'archive/' . $this->getHashPath();
if ( $suffix === false ) {
$path = substr( $path, 0, -1 );
} else {
$path .= $suffix;
}
return $path;
}
/**
* Get the path, relative to the thumbnail zone root, of the
* thumbnail directory or a particular file if $suffix is specified
*
* @param bool|string $suffix If not false, the name of a thumbnail file
* @return string
*/
function getThumbRel( $suffix = false ) {
$path = $this->getRel();
if ( $suffix !== false ) {
$path .= '/' . $suffix;
}
return $path;
}
/**
* Get urlencoded path of the file relative to the public zone root.
* This function is overridden in OldLocalFile to be like getArchiveUrl().
*
* @return string
*/
function getUrlRel() {
return $this->getHashPath() . rawurlencode( $this->getName() );
}
/**
* Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
* or a specific thumb if the $suffix is given.
*
* @param string $archiveName The timestamped name of an archived image
* @param bool|string $suffix If not false, the name of a thumbnail file
* @return string
*/
function getArchiveThumbRel( $archiveName, $suffix = false ) {
$path = 'archive/' . $this->getHashPath() . $archiveName . "/";
if ( $suffix === false ) {
$path = substr( $path, 0, -1 );
} else {
$path .= $suffix;
}
return $path;
}
/**
* Get the path of the archived file.
*
* @param bool|string $suffix If not false, the name of an archived file.
* @return string
*/
function getArchivePath( $suffix = false ) {
$this->assertRepoDefined();
return $this->repo->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
}
/**
* Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
*
* @param string $archiveName The timestamped name of an archived image
* @param bool|string $suffix If not false, the name of a thumbnail file
* @return string
*/
function getArchiveThumbPath( $archiveName, $suffix = false ) {
$this->assertRepoDefined();
return $this->repo->getZonePath( 'thumb' ) . '/' .
$this->getArchiveThumbRel( $archiveName, $suffix );
}
/**
* Get the path of the thumbnail directory, or a particular file if $suffix is specified
*
* @param bool|string $suffix If not false, the name of a thumbnail file
* @return string
*/
function getThumbPath( $suffix = false ) {
$this->assertRepoDefined();
return $this->repo->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
}
/**
* Get the path of the transcoded directory, or a particular file if $suffix is specified
*
* @param bool|string $suffix If not false, the name of a media file
* @return string
*/
function getTranscodedPath( $suffix = false ) {
$this->assertRepoDefined();
return $this->repo->getZonePath( 'transcoded' ) . '/' . $this->getThumbRel( $suffix );
}
/**
* Get the URL of the archive directory, or a particular file if $suffix is specified
*
* @param bool|string $suffix If not false, the name of an archived file
* @return string
*/
function getArchiveUrl( $suffix = false ) {
$this->assertRepoDefined();
$ext = $this->getExtension();
$path = $this->repo->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
if ( $suffix === false ) {
$path = substr( $path, 0, -1 );
} else {
$path .= rawurlencode( $suffix );
}
return $path;
}
/**
* Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
*
* @param string $archiveName The timestamped name of an archived image
* @param bool|string $suffix If not false, the name of a thumbnail file
* @return string
*/
function getArchiveThumbUrl( $archiveName, $suffix = false ) {
$this->assertRepoDefined();
$ext = $this->getExtension();
$path = $this->repo->getZoneUrl( 'thumb', $ext ) . '/archive/' .
$this->getHashPath() . rawurlencode( $archiveName ) . "/";
if ( $suffix === false ) {
$path = substr( $path, 0, -1 );
} else {
$path .= rawurlencode( $suffix );
}
return $path;
}
/**
* Get the URL of the zone directory, or a particular file if $suffix is specified
*
* @param string $zone Name of requested zone
* @param bool|string $suffix If not false, the name of a file in zone
* @return string Path
*/
function getZoneUrl( $zone, $suffix = false ) {
$this->assertRepoDefined();
$ext = $this->getExtension();
$path = $this->repo->getZoneUrl( $zone, $ext ) . '/' . $this->getUrlRel();
if ( $suffix !== false ) {
$path .= '/' . rawurlencode( $suffix );
}
return $path;
}
/**
* Get the URL of the thumbnail directory, or a particular file if $suffix is specified
*
* @param bool|string $suffix If not false, the name of a thumbnail file
* @return string Path
*/
function getThumbUrl( $suffix = false ) {
return $this->getZoneUrl( 'thumb', $suffix );
}
/**
* Get the URL of the transcoded directory, or a particular file if $suffix is specified
*
* @param bool|string $suffix If not false, the name of a media file
* @return string Path
*/
function getTranscodedUrl( $suffix = false ) {
return $this->getZoneUrl( 'transcoded', $suffix );
}
/**
* Get the public zone virtual URL for a current version source file
*
* @param bool|string $suffix If not false, the name of a thumbnail file
* @return string
*/
function getVirtualUrl( $suffix = false ) {
$this->assertRepoDefined();
$path = $this->repo->getVirtualUrl() . '/public/' . $this->getUrlRel();
if ( $suffix !== false ) {
$path .= '/' . rawurlencode( $suffix );
}
return $path;
}
/**
* Get the public zone virtual URL for an archived version source file
*
* @param bool|string $suffix If not false, the name of a thumbnail file
* @return string
*/
function getArchiveVirtualUrl( $suffix = false ) {
$this->assertRepoDefined();
$path = $this->repo->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
if ( $suffix === false ) {
$path = substr( $path, 0, -1 );
} else {
$path .= rawurlencode( $suffix );
}
return $path;
}
/**
* Get the virtual URL for a thumbnail file or directory
*
* @param bool|string $suffix If not false, the name of a thumbnail file
* @return string
*/
function getThumbVirtualUrl( $suffix = false ) {
$this->assertRepoDefined();
$path = $this->repo->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
if ( $suffix !== false ) {
$path .= '/' . rawurlencode( $suffix );
}
return $path;
}
/**
* @return bool
*/
function isHashed() {
$this->assertRepoDefined();
return (bool)$this->repo->getHashLevels();
}
/**
* @throws MWException
*/
function readOnlyError() {
throw new MWException( get_class( $this ) . ': write operations are not supported' );
}
/**
* Record a file upload in the upload log and the image table
* STUB
* Overridden by LocalFile
* @param string $oldver
* @param string $desc
* @param string $license
* @param string $copyStatus
* @param string $source
* @param bool $watch
* @param string|bool $timestamp
* @param null|User $user User object or null to use $wgUser
* @return bool
* @throws MWException
*/
function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
$watch = false, $timestamp = false, User $user = null
) {
$this->readOnlyError();
}
/**
* Move or copy a file to its public location. If a file exists at the
* destination, move it to an archive. Returns a FileRepoStatus object with
* the archive name in the "value" member on success.
*
* The archive name should be passed through to recordUpload for database
* registration.
*
* Options to $options include:
* - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
*
* @param string|FSFile $src Local filesystem path to the source image
* @param int $flags A bitwise combination of:
* File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
* @param array $options Optional additional parameters
* @return FileRepoStatus On success, the value member contains the
* archive name, or an empty string if it was a new file.
*
* STUB
* Overridden by LocalFile
*/
function publish( $src, $flags = 0, array $options = [] ) {
$this->readOnlyError();
}
/**
* @param bool|IContextSource $context Context to use (optional)
* @return bool
*/
function formatMetadata( $context = false ) {
if ( !$this->getHandler() ) {
return false;
}
return $this->getHandler()->formatMetadata( $this, $context );
}
/**
* Returns true if the file comes from the local file repository.
*
* @return bool
*/
function isLocal() {
return $this->repo && $this->repo->isLocal();
}
/**
* Returns the name of the repository.
*
* @return string
*/
function getRepoName() {
return $this->repo ? $this->repo->getName() : 'unknown';
}
/**
* Returns the repository
*
* @return FileRepo|LocalRepo|bool
*/
function getRepo() {
return $this->repo;
}
/**
* Returns true if the image is an old version
* STUB
*
* @return bool
*/
function isOld() {
return false;
}
/**
* Is this file a "deleted" file in a private archive?
* STUB
*
* @param int $field One of DELETED_* bitfield constants
* @return bool
*/
function isDeleted( $field ) {
return false;
}
/**
* Return the deletion bitfield
* STUB
* @return int
*/
function getVisibility() {
return 0;
}
/**
* Was this file ever deleted from the wiki?
*
* @return bool
*/
function wasDeleted() {
$title = $this->getTitle();
return $title && $title->isDeletedQuick();
}
/**
* Move file to the new title
*
* Move current, old version and all thumbnails
* to the new filename. Old file is deleted.
*
* Cache purging is done; checks for validity
* and logging are caller's responsibility
*
* @param Title $target New file name
* @return FileRepoStatus
*/
function move( $target ) {
$this->readOnlyError();
}
/**
* Delete all versions of the file.
*
* Moves the files into an archive directory (or deletes them)
* and removes the database rows.
*
* Cache purging is done; logging is caller's responsibility.
*
* @param string $reason
* @param bool $suppress Hide content from sysops?
* @param User|null $user
* @return FileRepoStatus
* STUB
* Overridden by LocalFile
*/
function delete( $reason, $suppress = false, $user = null ) {
$this->readOnlyError();
}
/**
* Restore all or specified deleted revisions to the given file.
* Permissions and logging are left to the caller.
*
* May throw database exceptions on error.
*
* @param array $versions Set of record ids of deleted items to restore,
* or empty to restore all revisions.
* @param bool $unsuppress Remove restrictions on content upon restoration?
* @return int|bool The number of file revisions restored if successful,
* or false on failure
* STUB
* Overridden by LocalFile
*/
function restore( $versions = [], $unsuppress = false ) {
$this->readOnlyError();
}
/**
* Returns 'true' if this file is a type which supports multiple pages,
* e.g. DJVU or PDF. Note that this may be true even if the file in
* question only has a single page.
*
* @return bool
*/
function isMultipage() {
return $this->getHandler() && $this->handler->isMultiPage( $this );
}
/**
* Returns the number of pages of a multipage document, or false for
* documents which aren't multipage documents
*
* @return bool|int
*/
function pageCount() {
if ( !isset( $this->pageCount ) ) {
if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
$this->pageCount = $this->handler->pageCount( $this );
} else {
$this->pageCount = false;
}
}
return $this->pageCount;
}
/**
* Calculate the height of a thumbnail using the source and destination width
*
* @param int $srcWidth
* @param int $srcHeight
* @param int $dstWidth
*
* @return int
*/
static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
// Exact integer multiply followed by division
if ( $srcWidth == 0 ) {
return 0;
} else {
return round( $srcHeight * $dstWidth / $srcWidth );
}
}
/**
* Get an image size array like that returned by getImageSize(), or false if it
* can't be determined. Loads the image size directly from the file ignoring caches.
*
* @note Use getWidth()/getHeight() instead of this method unless you have a
* a good reason. This method skips all caches.
*
* @param string $filePath The path to the file (e.g. From getLocalPathRef() )
* @return array The width, followed by height, with optionally more things after
*/
function getImageSize( $filePath ) {
if ( !$this->getHandler() ) {
return false;
}
return $this->getHandler()->getImageSize( $this, $filePath );
}
/**
* Get the URL of the image description page. May return false if it is
* unknown or not applicable.
*
* @return string
*/
function getDescriptionUrl() {
if ( $this->repo ) {
return $this->repo->getDescriptionUrl( $this->getName() );
} else {
return false;
}
}
/**
* Get the HTML text of the description page, if available
*
* @param bool|Language $lang Optional language to fetch description in
* @return string
*/
function getDescriptionText( $lang = false ) {
global $wgLang;
if ( !$this->repo || !$this->repo->fetchDescription ) {
return false;
}
$lang = $lang ?: $wgLang;
$renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName(), $lang->getCode() );
if ( $renderUrl ) {
$cache = ObjectCache::getMainWANInstance();
$key = $this->repo->getLocalCacheKey(
'RemoteFileDescription',
'url',
$lang->getCode(),
$this->getName()
);
return $cache->getWithSetCallback(
$key,
$this->repo->descriptionCacheExpiry ?: $cache::TTL_UNCACHEABLE,
function ( $oldValue, &$ttl, array &$setOpts ) use ( $renderUrl ) {
wfDebug( "Fetching shared description from $renderUrl\n" );
$res = Http::get( $renderUrl, [], __METHOD__ );
if ( !$res ) {
$ttl = WANObjectCache::TTL_UNCACHEABLE;
}
return $res;
}
);
}
return false;
}
/**
* Get description of file revision
* STUB
*
* @param int $audience One of:
* File::FOR_PUBLIC to be displayed to all users
* File::FOR_THIS_USER to be displayed to the given user
* File::RAW get the description regardless of permissions
* @param User $user User object to check for, only if FOR_THIS_USER is
* passed to the $audience parameter
* @return string
*/
function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
return null;
}
/**
* Get the 14-character timestamp of the file upload
*
* @return string|bool TS_MW timestamp or false on failure
*/
function getTimestamp() {
$this->assertRepoDefined();
return $this->repo->getFileTimestamp( $this->getPath() );
}
/**
* Returns the timestamp (in TS_MW format) of the last change of the description page.
* Returns false if the file does not have a description page, or retrieving the timestamp
* would be expensive.
* @since 1.25
* @return string|bool
*/
public function getDescriptionTouched() {
return false;
}
/**
* Get the SHA-1 base 36 hash of the file
*
* @return string
*/
function getSha1() {
$this->assertRepoDefined();
return $this->repo->getFileSha1( $this->getPath() );
}
/**
* Get the deletion archive key, "<sha1>.<ext>"
*
* @return string
*/
function getStorageKey() {
$hash = $this->getSha1();
if ( !$hash ) {
return false;
}
$ext = $this->getExtension();
$dotExt = $ext === '' ? '' : ".$ext";
return $hash . $dotExt;
}
/**
* Determine if the current user is allowed to view a particular
* field of this file, if it's marked as deleted.
* STUB
* @param int $field
* @param User $user User object to check, or null to use $wgUser
* @return bool
*/
function userCan( $field, User $user = null ) {
return true;
}
/**
* @return array HTTP header name/value map to use for HEAD/GET request responses
*/
function getStreamHeaders() {
$handler = $this->getHandler();
if ( $handler ) {
return $handler->getStreamHeaders( $this->getMetadata() );
} else {
return [];
}
}
/**
* @return string
*/
function getLongDesc() {
$handler = $this->getHandler();
if ( $handler ) {
return $handler->getLongDesc( $this );
} else {
return MediaHandler::getGeneralLongDesc( $this );
}
}
/**
* @return string
*/
function getShortDesc() {
$handler = $this->getHandler();
if ( $handler ) {
return $handler->getShortDesc( $this );
} else {
return MediaHandler::getGeneralShortDesc( $this );
}
}
/**
* @return string
*/
function getDimensionsString() {
$handler = $this->getHandler();
if ( $handler ) {
return $handler->getDimensionsString( $this );
} else {
return '';
}
}
/**
* @return string
*/
function getRedirected() {
return $this->redirected;
}
/**
* @return Title|null
*/
function getRedirectedTitle() {
if ( $this->redirected ) {
if ( !$this->redirectTitle ) {
$this->redirectTitle = Title::makeTitle( NS_FILE, $this->redirected );
}
return $this->redirectTitle;
}
return null;
}
/**
* @param string $from
* @return void
*/
function redirectedFrom( $from ) {
$this->redirected = $from;
}
/**
* @return bool
*/
function isMissing() {
return false;
}
/**
* Check if this file object is small and can be cached
* @return bool
*/
public function isCacheable() {
return true;
}
/**
* Assert that $this->repo is set to a valid FileRepo instance
* @throws MWException
*/
protected function assertRepoDefined() {
if ( !( $this->repo instanceof $this->repoClass ) ) {
throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
}
}
/**
* Assert that $this->title is set to a Title
* @throws MWException
*/
protected function assertTitleDefined() {
if ( !( $this->title instanceof Title ) ) {
throw new MWException( "A Title object is not set for this File.\n" );
}
}
/**
* True if creating thumbnails from the file is large or otherwise resource-intensive.
* @return bool
*/
public function isExpensiveToThumbnail() {
$handler = $this->getHandler();
return $handler ? $handler->isExpensiveToThumbnail( $this ) : false;
}
/**
* Whether the thumbnails created on the same server as this code is running.
* @since 1.25
* @return bool
*/
public function isTransformedLocally() {
return true;
}
}
| lgpl-3.0 |
nttuyen/task | task-management/src/main/java/org/exoplatform/task/management/assets/ckeditorCustom/plugins/a11yhelp/dialogs/lang/pt.js | 5505 | /**
* @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'a11yhelp', 'pt', {
title: 'Instruções de acessibilidade',
contents: 'Conteúdo de ajuda. Use a tecla ESC para fechar esta janela.',
legend: [
{
name: 'Geral',
items: [
{
name: 'Barra de ferramentas do editor',
legend: 'Clique em ${toolbarFocus} para navegar para a barra de ferramentas. Vá para o grupo da barra de ferramentas anterior e seguinte com TAB e SHIFT+TAB. Vá para o botão da barra de ferramentas anterior com a SETA DIREITA ou ESQUERDA. Pressione ESPAÇO ou ENTER para ativar o botão da barra de ferramentas.'
},
{
name: 'Janela do Editor',
legend:
'Inside a dialog, press TAB to navigate to the next dialog element, press SHIFT+TAB to move to the previous dialog element, press ENTER to submit the dialog, press ESC to cancel the dialog. When a dialog has multiple tabs, the tab list can be reached either with ALT+F10 or with TAB as part of the dialog tabbing order. With tab list focused, move to the next and previous tab with RIGHT and LEFT ARROW, respectively.' // MISSING
},
{
name: 'Menu de Contexto do Editor',
legend: 'Clique em ${contextMenu} ou TECLA APLICAÇÃO para abrir o menu de contexto. Depois vá para a opção do menu seguinte com TAB ou SETA PARA BAIXO. Vá para a opção anterior com SHIFT+TAB ou SETA PARA CIMA. Pressione ESPAÇO ou ENTER para selecionar a opção do menu. Abra o submenu da opção atual com ESPAÇO, ENTER ou SETA DIREITA. GVá para o item do menu parente com ESC ou SETA ESQUERDA. Feche o menu de contexto com ESC.'
},
{
name: 'Editor de caixa em lista',
legend: 'Dentro da caixa da lista, vá para o itemda lista seguinte com TAB ou SETA PARA BAIXO. Move Vá parao item da lista anterior com SHIFT+TAB ou SETA PARA BAIXO. Pressione ESPAÇO ou ENTER para selecionar a opção da lista. Pressione ESC para fechar a caisa da lista.'
},
{
name: 'Caminho Barra Elemento Editor',
legend: 'Clique em ${elementsPathFocus} para navegar para a barra do caminho dos elementos. Vá para o botão do elemento seguinte com TAB ou SETA DIREITA. Vá para o botão anterior com SHIFT+TAB ou SETA ESQUERDA. Pressione ESPAÇO ou ENTER para selecionar o elemento no editor.'
}
]
},
{
name: 'Comandos',
items: [
{
name: 'Comando de Anular',
legend: 'Carregar ${undo}'
},
{
name: 'Comando de Refazer',
legend: 'Pressione ${redo}'
},
{
name: 'Comando de Negrito',
legend: 'Pressione ${bold}'
},
{
name: 'Comando de Itálico',
legend: 'Pressione ${italic}'
},
{
name: 'Comando de Sublinhado',
legend: 'Pressione ${underline}'
},
{
name: 'Comando de Hiperligação',
legend: 'Pressione ${link}'
},
{
name: 'Comando de Ocultar Barra de Ferramentas',
legend: 'Pressione ${toolbarCollapse}'
},
{
name: 'Acesso comando do espaço focus anterior',
legend: 'Clique em ${accessPreviousSpace} para aceder ao espaço do focos inalcançável mais perto antes do sinal de omissão, por exemplo: dois elementos HR adjacentes. Repetir a combinação da chave para alcançar os espaços dos focos distantes.'
},
{
name: 'Acesso comando do espaço focus seguinte',
legend: 'Pressione ${accessNextSpace} para aceder ao espaço do focos inalcançável mais perto depois do sinal de omissão, por exemplo: dois elementos HR adjacentes. Repetir a combinação da chave para alcançar os espaços dos focos distantes.'
},
{
name: 'Ajuda a acessibilidade',
legend: 'Pressione ${a11yHelp}'
}
]
}
],
backspace: 'Backspace', // MISSING
tab: 'Tab', // MISSING
enter: 'Enter', // MISSING
shift: 'Shift',
ctrl: 'Ctrl',
alt: 'Alt',
pause: 'Pausa',
capslock: 'Maiúsculas',
escape: 'Esc',
pageUp: 'Page Up', // MISSING
pageDown: 'Page Down', // MISSING
end: 'Fim',
home: 'Entrada',
leftArrow: 'Seta esquerda',
upArrow: 'Seta para cima',
rightArrow: 'Seta direita',
downArrow: 'Seta para baixo',
insert: 'Inserir',
'delete': 'Eliminar',
leftWindowKey: 'Left Windows key', // MISSING
rightWindowKey: 'Right Windows key', // MISSING
selectKey: 'Select key', // MISSING
numpad0: 'Numpad 0', // MISSING
numpad1: 'Numpad 1', // MISSING
numpad2: 'Numpad 2', // MISSING
numpad3: 'Numpad 3', // MISSING
numpad4: 'Numpad 4', // MISSING
numpad5: 'Numpad 5', // MISSING
numpad6: 'Numpad 6', // MISSING
numpad7: 'Numpad 7', // MISSING
numpad8: 'Numpad 8', // MISSING
numpad9: 'Numpad 9', // MISSING
multiply: 'Multiplicar',
add: 'Adicionar',
subtract: 'Subtrair',
decimalPoint: 'Decimal Point', // MISSING
divide: 'Divide', // MISSING
f1: 'F1',
f2: 'F2',
f3: 'F3',
f4: 'F4',
f5: 'F5',
f6: 'F6',
f7: 'F7',
f8: 'F8',
f9: 'F9',
f10: 'F10',
f11: 'F11',
f12: 'F12',
numLock: 'Num Lock', // MISSING
scrollLock: 'Scroll Lock', // MISSING
semiColon: 'Semicolon', // MISSING
equalSign: 'Equal Sign', // MISSING
comma: 'Vírgula',
dash: 'Dash', // MISSING
period: 'Period', // MISSING
forwardSlash: 'Forward Slash', // MISSING
graveAccent: 'Acento grave',
openBracket: 'Open Bracket', // MISSING
backSlash: 'Backslash', // MISSING
closeBracket: 'Close Bracket', // MISSING
singleQuote: 'Single Quote' // MISSING
} );
| lgpl-3.0 |
bobslaede/sund2 | node_modules/buckets/node_modules/newrelic/lib/util/sum-children.js | 2476 | 'use strict';
/**
* Given an ordered list of disjoint intervals and a new interval to fold into
* it, determine if the new interval is a sub-interval (in which case it's
* redundant), an overlapping interval (in which case, replace the most recent
* interval on the list with an interval representing the union of the new and
* last intervals), or otherwise (it's disjoint to what we already
* have, in which case add it to the list). Meant to be used with
* Array.reduce().
*
* Assumes the list being reduced is sorted by interval start time.
*
* @param {Array} accum The accumulated list of reduced intervals.
* @param {Array} newest A new pair of range start and end to compare to the
* existing intervals.
*
* @return {Array} A list of intervals updated to include the new interval.
*/
function reduceIntervals(accum, newest) {
if (accum && accum.length > 0) {
// the last interval on the list will always be the latest
var last = accum.slice(-1)[0];
// case 1: the new interval is a strict subset of the last interval
if (newest[0] >= last[0] && newest[1] <= last[1]) {
return accum;
}
// case 2: the start of the new interval is inside the last interval
else if (newest[0] >= last[0] && newest[0] <= last[1]) {
var heads = accum.slice(0, -1);
// gotta double-wrap the array I'm appending onto the end
return heads.concat([[last[0], newest[1]]]);
}
// case 3: the interval is disjoint
else {
return accum.concat([newest]);
}
}
// base case: wrap up the newest element to create the accumulator
return [newest];
}
/**
* Reduce a list of intervals to the magnitude of the range, eliminating any
* overlaps.
*
* @param {Array} pairs The list of startRange, endRange pairs to reduce.
* @return {integer} The magnitude of the range, after all the overlaps have
* been smoothed and the holes eliminated.
*/
function sumChildren(pairs) {
// 1. sort the list of [begin, end] pairs by start time
var sortedPairs = pairs.sort(function cb_sort(a, b) { return a[0] - b[0]; });
// 2. reduce the list to a set of disjoint intervals
// I love ECMAscript 5!
var disjointIntervals = sortedPairs.reduce(reduceIntervals, []);
// 3. sum the durations of the intervals
return disjointIntervals.reduce(function cb_reduce(accum, current) {
return accum + (current[1] - current[0]);
}, 0);
}
module.exports = sumChildren;
| unlicense |
somenxavier/powered-by-somenergia | js/leaflet.geocsv-src.js | 4150 | /*
* Copyright 2013 - GPL
* Iván Eixarch <ivan@sinanimodelucro.org>
* https://github.com/joker-x/Leaflet.geoCSV
*
* 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., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
L.GeoCSV = L.GeoJSON.extend({
//opciones por defecto
options: {
titles: ['lat', 'lng', 'popup'],
fieldSeparator: ';',
lineSeparator: '\n',
deleteDobleQuotes: true,
firstLineTitles: false
},
_propertiesNames: [],
initialize: function (csv, options) {
L.Util.setOptions (this, options);
L.GeoJSON.prototype.initialize.call (this, csv, options);
},
addData: function (data) {
if (typeof data === 'string') {
//leemos titulos
var titulos = this.options.titles;
if (this.options.firstLineTitles) {
data = data.split(this.options.lineSeparator);
if (data.length < 2) return;
titulos = data[0];
data.splice(0,1);
data = data.join(this.options.lineSeparator);
titulos = titulos.trim().split(this.options.fieldSeparator);
for (var i=0; i<titulos.length; i++) {
titulos[i] = this._deleteDobleQuotes(titulos[i]);
}
this.options.titles = titulos;
}
//generamos _propertiesNames
for (var i=0; i<titulos.length; i++) {
var prop = titulos[i].toLowerCase().replace(/[^\w ]+/g,'').replace(/ +/g,'_');
if (prop == '' || prop == '_' || this._propertiesNames.indexOf(prop) >= 0) prop = 'prop-'+i;
this._propertiesNames[i] = prop;
}
//convertimos los datos a geoJSON
data = this._csv2json(data);
}
L.GeoJSON.prototype.addData.call (this, data);
},
getPropertyName: function (title) {
var pos = this.options.titles.indexOf(title)
, prop = '';
if (pos >= 0) prop = this._propertiesNames[pos];
return prop;
},
getPropertyTitle: function (prop) {
var pos = this._propertiesNames.indexOf(prop)
, title = '';
if (pos >= 0) title = this.options.titles[pos];
return title;
},
_deleteDobleQuotes: function (cadena) {
if (this.options.deleteDobleQuotes) cadena = cadena.trim().replace(/^"/,"").replace(/"$/,"");
return cadena;
},
_csv2json: function (csv) {
var json = {};
json["type"]="FeatureCollection";
json["features"]=[];
var titulos = this.options.titles;
csv = csv.split(this.options.lineSeparator);
for (var num_linea = 0; num_linea < csv.length; num_linea++) {
var campos = csv[num_linea].trim().split(this.options.fieldSeparator)
, lng = parseFloat(campos[titulos.indexOf('lng')])
, lat = parseFloat(campos[titulos.indexOf('lat')]);
if (campos.length==titulos.length && lng<180 && lng>-180 && lat<90 && lat>-90) {
var feature = {};
feature["type"]="Feature";
feature["geometry"]={};
feature["properties"]={};
feature["geometry"]["type"]="Point";
feature["geometry"]["coordinates"]=[lng,lat];
//propiedades
for (var i=0; i<titulos.length; i++) {
if (titulos[i] != 'lat' && titulos[i] != 'lng') {
feature["properties"][this._propertiesNames[i]] = this._deleteDobleQuotes(campos[i]);
}
}
json["features"].push(feature);
} else {
console.log(campos.length, titulos.length, campos, campos.length==titulos.length , lng<180 , lng>-180, lat<90, lat>-90);
}
}
return json;
}
});
L.geoCsv = function (csv_string, options) {
return new L.GeoCSV (csv_string, options);
};
| unlicense |
hmcl/storm-apache | examples/storm-elasticsearch-examples/src/main/java/org/apache/storm/elasticsearch/common/EsConstants.java | 1232 | /**
* 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.storm.elasticsearch.common;
/**
* Constants used in ElasticSearch examples.
*/
public final class EsConstants {
/**
* The cluster name.
*/
public static final String CLUSTER_NAME = "test-cluster";
/**
* The default wait value in seconds.
*/
public static final int WAIT_DEFAULT_SECS = 5;
/**
* Utility constructor.
*/
private EsConstants() {
}
}
| apache-2.0 |
tellapart/elasticsearch-zookeeper | src/test/java/com/sonian/elasticsearch/zookeeper/discovery/embedded/EmbeddedZooKeeperService.java | 3724 | /*
* Copyright 2011 Sonian Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sonian.elasticsearch.zookeeper.discovery.embedded;
import org.apache.zookeeper.server.NIOServerCnxnFactory;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.ZooKeeperServer;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.PortsRange;
import org.elasticsearch.env.Environment;
import java.io.File;
import java.io.IOException;
import java.net.BindException;
import java.net.InetSocketAddress;
/**
* @author imotov
*/
public class EmbeddedZooKeeperService extends AbstractLifecycleComponent<EmbeddedZooKeeper> implements EmbeddedZooKeeper {
private ZooKeeperServer zooKeeperServer;
private ServerCnxnFactory cnxnFactory;
public EmbeddedZooKeeperService(Settings settings, Environment environment) {
super(settings);
try {
zooKeeperServer = new ZooKeeperServer();
File zooKeeperDir = new File(environment.dataFiles()[0], "zookeeper");
FileTxnSnapLog fileTxnSnapLog = new FileTxnSnapLog(zooKeeperDir, zooKeeperDir);
zooKeeperServer.setTxnLogFactory(fileTxnSnapLog);
zooKeeperServer.setTickTime(ZooKeeperServer.DEFAULT_TICK_TIME);
// Large session timeout so it doesn't time out during debugging
zooKeeperServer.setMinSessionTimeout(100000);
zooKeeperServer.setMaxSessionTimeout(100000);
String zooKeeperPort = settings.get("zookeeper.port", "2800-2900");
PortsRange portsRange = new PortsRange(zooKeeperPort);
for (int port : portsRange.ports()) {
InetSocketAddress address = new InetSocketAddress(port);
try {
cnxnFactory = NIOServerCnxnFactory.createFactory(address, -1);
zooKeeperServer.setServerCnxnFactory(cnxnFactory);
break;
} catch (BindException bindException) {
// Ignore
}
}
} catch (Exception ex) {
logger.error("ZooKeeper initialization failed ", ex);
}
}
@Override protected void doStart() throws ElasticsearchException {
try {
cnxnFactory.startup(zooKeeperServer);
} catch (IOException e) {
throw new ElasticsearchException("Cannot start ZooKeeper", e);
} catch (InterruptedException e) {
throw new ElasticsearchException("ZooKeeper startup interrupted", e);
}
}
@Override protected void doStop() throws ElasticsearchException {
cnxnFactory.shutdown();
}
@Override protected void doClose() throws ElasticsearchException {
}
@Override public int port() {
return zooKeeperServer.getClientPort();
}
@Override public void expireSession(long sessionId) {
logger.info("Expiring session {}", sessionId);
zooKeeperServer.closeSession(sessionId);
}
}
| apache-2.0 |
0x73/rust | src/test/compile-fail/liveness-move-in-loop.rs | 766 | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn main() {
let y: Box<int> = box 42;
let mut x: Box<int>;
loop {
println!("{}", y);
loop {
loop {
loop {
x = y; //~ ERROR use of moved value
x.clone();
}
}
}
}
}
| apache-2.0 |
ernestp/consulo | platform/lang-impl/src/com/intellij/ide/util/treeView/smartTree/TreeElementWrapper.java | 2254 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.util.treeView.smartTree;
import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.structureView.StructureViewTreeElement;
import com.intellij.openapi.project.Project;
import java.util.Collection;
public class TreeElementWrapper extends CachingChildrenTreeNode<TreeElement> {
public TreeElementWrapper(Project project, TreeElement value, TreeModel treeModel) {
super(project, value, treeModel);
}
@Override
public void copyFromNewInstance(final CachingChildrenTreeNode oldInstance) {
}
@Override
public void update(PresentationData presentation) {
if (((StructureViewTreeElement)getValue()).getValue() != null) {
presentation.updateFrom(getValue().getPresentation());
}
}
@Override
public void initChildren() {
clearChildren();
TreeElement[] children = getValue().getChildren();
for (TreeElement child : children) {
addSubElement(createChildNode(child));
}
if (myTreeModel instanceof ProvidingTreeModel) {
final Collection<NodeProvider> providers = ((ProvidingTreeModel)myTreeModel).getNodeProviders();
for (NodeProvider provider : providers) {
if (((ProvidingTreeModel)myTreeModel).isEnabled(provider)) {
final Collection<TreeElement> nodes = provider.provideNodes(getValue());
for (TreeElement node : nodes) {
addSubElement(createChildNode(node));
}
}
}
}
}
@Override
protected void performTreeActions() {
filterChildren(myTreeModel.getFilters());
groupChildren(myTreeModel.getGroupers());
sortChildren(myTreeModel.getSorters());
}
}
| apache-2.0 |
treejames/SlidingCard | slidingcard-core/src/main/java/com/mxn/soul/slidingcard_core/SlidingCard.java | 23488 | package com.mxn.soul.slidingcard_core;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.support.annotation.NonNull;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.VelocityTrackerCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewConfigurationCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.Interpolator;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Scroller;
/**
* 每一个卡片布局
*/
public class SlidingCard extends LinearLayout {
private static final boolean USE_CACHE = true;
public static final int MAX_SETTLE_DURATION = 600; // ms
//最小快速滑动距离
private static final int MIN_DISTANCE_FOR_FLING = 25; // dips
public static final Interpolator sInterpolator = new Interpolator() {
public float getInterpolation(float t) {
t -= 1.0f;
return t * t * t * t * t + 1.0f;
}
};
private View mContent;
private int mPrevItem = DEFAULT_ITEM;
private int mCurItem = DEFAULT_ITEM;
private static final int DEFAULT_ITEM = 0;
private boolean mFirstLayout = true;
private Scroller mScroller;
private boolean mScrollingCacheEnabled;
private boolean mScrolling;
public static boolean sScrolling = false ;
private boolean mIsBeingDragged;
private boolean mIsUnableToDrag;
private int mTouchSlop;
//手指刚按下的初始点
private float mInitialMotionX;
/**
* 最后一次motion event的位置.
*/
private float mLastMotionX;
private float mLastMotionY;
/**
* 活动的触摸pointer的ID. 用于当多点拖动的时候保持一致性
*/
protected int mActivePointerId = INVALID_POINTER;
/**
* 表示当前没有活动的点
* {@link #mActivePointerId}.
*/
private static final int INVALID_POINTER = -1;
/**
* 确定滚动的速度
*/
protected VelocityTracker mVelocityTracker;
private int mMinimumVelocity;
protected int mMaximumVelocity;
private int mFlingDistance;
private OnPageChangeListener mOnPageChangeListener;
public void setOnPageChangeListener(OnPageChangeListener listener) {
mOnPageChangeListener = listener;
}
/**
* 空闲状态,view完整显示,动画处于执行完毕状态
*/
public static final int SCROLL_STATE_IDLE = 0;
/**
* 表示正在被拖动
*/
public static final int SCROLL_STATE_DRAGGING = 1;
/**
* 表示view正在自动移动到最终的位置
*/
public static final int SCROLL_STATE_SETTLING = 2;
private int mScrollState = SCROLL_STATE_IDLE;
private int cardHeight ;
/**
* 滑动的回调接口
*/
public interface OnPageChangeListener {
/**
* 当前page滚动的时候调用,只要位置有移动就会调用
* @param position 当前Position等于0, 左滑position等于1,右滑position等于-1
* @param positionOffset 范围是[0, 1) 表示从position的偏移
* @param positionOffsetPixels 从position的偏移的像素
*/
void onPageScrolled(SlidingCard v, int position,
float positionOffset, int positionOffsetPixels);
/**
* 当新page被选中的时候调用
* 动画并不一定完成
*/
void onPageSelected(SlidingCard v, int prevPosition,
int curPosition);
/**
* 当动画结束后,新页面被选中时调用
*/
void onPageSelectedAfterAnimation(SlidingCard v,
int prevPosition, int curPosition);
/**
* 当滑动状态改变时调用,用来观察:拖动状态,自动移动状态,和停止状态。
*
* @param state 滑动状态.
* @see SlidingCard#SCROLL_STATE_IDLE
* @see SlidingCard#SCROLL_STATE_DRAGGING
* @see SlidingCard#SCROLL_STATE_SETTLING
*/
void onPageScrollStateChanged(SlidingCard v, int state);
}
public SlidingCard(Context context) {
this(context, null);
}
public SlidingCard(Context context, AttributeSet attrs) {
super(context, attrs);
initSlidingCard();
}
void initSlidingCard() {
setWillNotDraw(false);
setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
setFocusable(true);
final Context context = getContext();
mScroller = new Scroller(context, sInterpolator);
final ViewConfiguration configuration = ViewConfiguration.get(context);
mTouchSlop = ViewConfigurationCompat
.getScaledPagingTouchSlop(configuration);
mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
final float density = context.getResources().getDisplayMetrics().density;
mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mFirstLayout = true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = getDefaultSize(0, widthMeasureSpec);
setMeasuredDimension(width, cardHeight);
final int contentWidth = getChildMeasureSpec(widthMeasureSpec, 0, width);
mContent.measure(contentWidth, cardHeight);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (w != oldw) {
completeScroll();
scrollTo(getDestScrollX(mCurItem), getScrollY());
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int width = r - l;
final int height = b - t;
mContent.layout(0, 0, width, height);
if (mFirstLayout) {
scrollTo(getDestScrollX(mCurItem), getScrollY());
}
mFirstLayout = false;
}
@Override
public void computeScroll() {
if (!mScroller.isFinished()) {
if (mScroller.computeScrollOffset()) {
int oldX = getScrollX();
int oldY = getScrollY();
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
if (oldX != x || oldY != y) {
scrollTo(x, y);
pageScrolled(x);
} else {
setScrollState(SCROLL_STATE_IDLE);
}
// 继续绘图直到动画结束
ViewCompat.postInvalidateOnAnimation(this);
return;
}
}
// scroll完成, 清除状态
completeScroll();
}
@Override
public void scrollTo(int x, int y) {
super.scrollTo(x, y);
}
private void pageScrolled(int xpos) {
final int widthWithMargin = getWidth();
final int position = xpos / widthWithMargin;
final int offsetPixels = xpos % widthWithMargin;
final float offset = (float) offsetPixels / widthWithMargin;
if (mOnPageChangeListener != null) {
mOnPageChangeListener.onPageScrolled(this, position, offset,
offsetPixels);
}
}
private void setScrollState(int newState) {
if (mScrollState == newState) {
return;
}
mScrollState = newState;
disableLayers();
if (mOnPageChangeListener != null) {
mOnPageChangeListener.onPageScrollStateChanged(this, newState);
}
}
private void completeScroll() {
boolean needPopulate = mScrolling;
if (needPopulate) {
//滚动完成, 不再需要Cache
setScrollingCacheEnabled(false);
mScroller.abortAnimation();
int oldX = getScrollX();
int oldY = getScrollY();
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
if (oldX != x || oldY != y) {
scrollTo(x, y);
} else {
setScrollState(SCROLL_STATE_IDLE);
}
if (mOnPageChangeListener != null && mPrevItem != mCurItem) {
mOnPageChangeListener.onPageSelectedAfterAnimation(this,
mPrevItem, mCurItem);
}
}
mScrolling = false;
}
private void setScrollingCacheEnabled(boolean enabled) {
if (mScrollingCacheEnabled != enabled) {
mScrollingCacheEnabled = enabled;
if (USE_CACHE) {
final int size = getChildCount();
for (int i = 0; i < size; ++i) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
child.setDrawingCacheEnabled(enabled);
}
}
}
}
}
//为了改变线性关系,而采用这样的中度的影响
float distanceInfluenceForSnapDuration(float f) {
f -= 0.5f;
f *= 0.3f * Math.PI / 2.0f;
return (float) Math.sin(f);
}
/**
* Like {@link View#scrollBy}, 用平滑的滚动代替瞬间到达
*
* @param x X轴上移动的像素
* @param y Y轴上移动的像素
* @param velocity 快速滑动时的速度(可以为0)
*/
void smoothScrollTo(int x, int y, int velocity) {
if (getChildCount() == 0) {
setScrollingCacheEnabled(false);
return;
}
int sx = getScrollX();
int sy = getScrollY();
int dx = x - sx;
int dy = y - sy;
if (dx == 0 && dy == 0) {
completeScroll();
setScrollState(SCROLL_STATE_IDLE);
return;
}
setScrollingCacheEnabled(true);
setScrollState(SCROLL_STATE_SETTLING);
mScrolling = true;
sScrolling = true;
final int width = getWidth();
final int halfWidth = width / 2;
final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width);
final float distance = halfWidth + halfWidth
* distanceInfluenceForSnapDuration(distanceRatio);
int duration ;
velocity = Math.abs(velocity);
if (velocity > 0) {
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
} else {
duration = MAX_SETTLE_DURATION;
}
duration = Math.min(duration, MAX_SETTLE_DURATION);
mScroller.startScroll(sx, sy, dx, dy, duration);
invalidate();
}
void setCurrentItemInternal(int item, boolean smoothScroll, boolean always) {
setCurrentItemInternal(item, smoothScroll, always, 0);
}
void setCurrentItemInternal(int item, boolean smoothScroll, boolean always,
int velocity) {
if (!always && mCurItem == item) {
setScrollingCacheEnabled(false);
return;
}
item = getTargetPage(item);
final boolean dispatchSelected = mCurItem != item;
mPrevItem = mCurItem;
mCurItem = item;
final int destX = getDestScrollX(mCurItem);
if (dispatchSelected && mOnPageChangeListener != null) {
mOnPageChangeListener.onPageSelected(this, mPrevItem, mCurItem);
}
if (smoothScroll) {
smoothScrollTo(destX, 0, velocity);
} else {
completeScroll();
scrollTo(destX, 0);
if (mOnPageChangeListener != null && mPrevItem != mCurItem) {
mOnPageChangeListener.onPageSelectedAfterAnimation(this,
mPrevItem, mCurItem);
}
}
}
int getTargetPage(int page) {
page = (page > 1) ? 2 : ((page < 1) ? 0 : page);
return page;
}
int getDestScrollX(int page) {
switch (page) {
case 0:
return mContent.getLeft() - getCardWidth();
case 1:
return mContent.getLeft();
case 2:
return mContent.getLeft() + getCardWidth();
}
return 0;
}
public void setCurrentItem(int item, boolean smoothScroll) {
setCurrentItemInternal(item, smoothScroll, false);
}
@Override
public void addView(@NonNull View child) {
try {
super.removeAllViews();
} catch (Exception e) {
Log.e("ERROR", String.valueOf(e.getMessage()));
}
mContent = child;
super.addView(child);
disableLayers();
}
@Override
public void removeView(@NonNull View view) {
try {
super.removeView(view);
} catch (Exception e) {
Log.e("ERROR", String.valueOf(e.getMessage()));
}
disableLayers();
}
public void setContent(int res) {
RelativeLayout root = (RelativeLayout) View.inflate(getContext(),R.layout.sliding_card_root, null);
root.addView(LayoutInflater.from(getContext()).inflate(res, null));
setContent(root);
}
public void setCardHeight(int cardHeight) {
this.cardHeight = cardHeight ;
}
public void setContent(View v) {
addView(v);
}
public boolean isCardClose() {
return mCurItem == 0 || mCurItem == 2;
}
public int getCardWidth() {
return mContent.getWidth();
}
private boolean thisSlideAllowed() {
return !isCardClose();
}
private int getLeftBound() {
return mContent.getLeft() - getCardWidth();
}
private int getRightBound() {
return mContent.getLeft() + getCardWidth();
}
private void startDrag() {
mIsBeingDragged = true;
setScrollState(SCROLL_STATE_DRAGGING);
}
private void endDrag() {
mIsBeingDragged = false;
mIsUnableToDrag = false;
mActivePointerId = INVALID_POINTER;
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
private void determineDrag(MotionEvent ev) {
final int activePointerId = mActivePointerId;
if (activePointerId == INVALID_POINTER)
return;
final int pointerIndex = findPointerIndex(ev, activePointerId);
final float x = MotionEventCompat.getX(ev, pointerIndex);
final float dx = x - mLastMotionX;
final float xDiff = Math.abs(dx);
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float dy = y - mLastMotionY;
final float yDiff = Math.abs(dy);
if (xDiff > mTouchSlop && xDiff > yDiff && thisSlideAllowed()) {
startDrag();
mLastMotionX = x;
mLastMotionY = y;
setScrollingCacheEnabled(true);
} else if (xDiff > mTouchSlop) {
mIsUnableToDrag = true;
}
}
private int determineTargetPage(float pageOffset, int velocity, int deltaX) {
int targetPage = mCurItem;
if (Math.abs(deltaX) > mFlingDistance
&& Math.abs(velocity) > mMinimumVelocity) {
if (velocity > 0 && deltaX > 0) {
targetPage -= 1;
} else if (velocity < 0 && deltaX < 0) {
targetPage += 1;
}
} else {
targetPage = Math.round(mCurItem + pageOffset);
}
return targetPage;
}
@Override
public boolean dispatchKeyEvent(@NonNull KeyEvent event) {
return super.dispatchKeyEvent(event) ;
}
private void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
// 这是我们要抬起的点. 选取另外一个点代替抬起的点
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastMotionX = MotionEventCompat.getX(ev, newPointerIndex);
mActivePointerId = MotionEventCompat.getPointerId(ev,
newPointerIndex);
if (mVelocityTracker != null) {
mVelocityTracker.clear();
}
}
}
private int findPointerIndex(MotionEvent event, int pointerId) {
int index = MotionEventCompat.findPointerIndex(event, pointerId);
if (index == INVALID_POINTER) {
index = 0;
}
return index;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if(sScrolling)
return false;
if (isCardClose())
return false;
final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
if (action == MotionEvent.ACTION_CANCEL
|| action == MotionEvent.ACTION_UP
|| (action != MotionEvent.ACTION_DOWN && mIsUnableToDrag)) {
endDrag();
return false;
}
switch (action) {
case MotionEvent.ACTION_MOVE:
determineDrag(ev);
break;
case MotionEvent.ACTION_DOWN:
mLastMotionX = mInitialMotionX = ev.getX();
mLastMotionY = ev.getY();
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
completeScroll();
mIsBeingDragged = false;
mIsUnableToDrag = false;
break;
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
}
if (!mIsBeingDragged) {
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
}
return mIsBeingDragged;
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent ev) {
if(sScrolling)
return false;
if (isCardClose())
return false;
final int action = ev.getAction();
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
switch (action & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
//记录event的开始点
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mLastMotionX = mInitialMotionX = ev.getX();
mLastMotionY = ev.getY();
break;
case MotionEvent.ACTION_MOVE:
if (!mIsBeingDragged) {
determineDrag(ev);
if (mIsUnableToDrag)
return false;
}
if (mIsBeingDragged) {
// 跟随motion event滑动
final int activePointerIndex = findPointerIndex(ev,
mActivePointerId);
final float x = MotionEventCompat.getX(ev, activePointerIndex);
float deltaX = mLastMotionX - x;
mLastMotionX = x;
float oldScrollX = getScrollX();
float scrollX = oldScrollX + deltaX;
final float leftBound = getLeftBound();
final float rightBound = getRightBound();
if (scrollX < leftBound) {
scrollX = leftBound;
} else if (scrollX > rightBound) {
scrollX = rightBound;
}
mLastMotionX += scrollX - (int) scrollX;
scrollTo((int) scrollX, getScrollY());
pageScrolled((int) scrollX);
}
break;
case MotionEvent.ACTION_UP:
if (mIsBeingDragged) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(
velocityTracker, mActivePointerId);
final int scrollX = getScrollX();
final float pageOffset = (float) (scrollX - getDestScrollX(mCurItem))
/ getCardWidth();
final int activePointerIndex = findPointerIndex(ev,
mActivePointerId);
final float x = MotionEventCompat.getX(ev, activePointerIndex);
final int totalDelta = (int) (x - mInitialMotionX);
int nextPage = determineTargetPage(pageOffset, initialVelocity,
totalDelta);
setCurrentItemInternal(nextPage, true, true, initialVelocity);
mActivePointerId = INVALID_POINTER;
endDrag();
}
break;
case MotionEvent.ACTION_CANCEL:
if (mIsBeingDragged) {
setCurrentItemInternal(mCurItem, true, true);
mActivePointerId = INVALID_POINTER;
endDrag();
}
break;
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int indexx = MotionEventCompat.getActionIndex(ev);
mLastMotionX = MotionEventCompat.getX(ev, indexx);
mActivePointerId = MotionEventCompat.getPointerId(ev, indexx);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
try {
mLastMotionX = MotionEventCompat.getX(ev,
findPointerIndex(ev, mActivePointerId));
} catch (Exception e) {
e.printStackTrace();
}
break;
}
return true;
}
@Override
protected void dispatchDraw(@NonNull Canvas canvas) {
PaintFlagsDrawFilter pfd = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint
.FILTER_BITMAP_FLAG);
canvas.setDrawFilter(pfd);
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child == null)
return;
}
super.dispatchDraw(canvas);
}
private void disableLayers() {
//view按一般方式绘制,不使用离屏缓冲.这是默认的行为
ViewCompat.setLayerType(this, ViewCompat.LAYER_TYPE_NONE, null);
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
ViewCompat.setLayerType(getChildAt(i), ViewCompat.LAYER_TYPE_NONE,
null);
}
}
}
| apache-2.0 |
ricepanda/rice-git3 | development-tools/src/main/java/org/kuali/rice/devtools/jpa/eclipselink/conv/parser/helper/resolver/EntityResolver.java | 3290 | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.devtools.jpa.eclipselink.conv.parser.helper.resolver;
import japa.parser.ast.CompilationUnit;
import japa.parser.ast.ImportDeclaration;
import japa.parser.ast.Node;
import japa.parser.ast.body.ClassOrInterfaceDeclaration;
import japa.parser.ast.body.TypeDeclaration;
import japa.parser.ast.expr.MarkerAnnotationExpr;
import japa.parser.ast.expr.NameExpr;
import japa.parser.ast.expr.QualifiedNameExpr;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ojb.broker.metadata.ClassDescriptor;
import org.apache.ojb.broker.metadata.DescriptorRepository;
import org.kuali.rice.devtools.jpa.eclipselink.conv.ojb.OjbUtil;
import org.kuali.rice.devtools.jpa.eclipselink.conv.parser.helper.AnnotationResolver;
import org.kuali.rice.devtools.jpa.eclipselink.conv.parser.helper.Level;
import org.kuali.rice.devtools.jpa.eclipselink.conv.parser.helper.NodeData;
import java.util.Collection;
public class EntityResolver implements AnnotationResolver {
private static final Log LOG = LogFactory.getLog(EntityResolver.class);
public static final String PACKAGE = "javax.persistence";
public static final String SIMPLE_NAME = "Entity";
private final Collection<DescriptorRepository> descriptorRepositories;
public EntityResolver(Collection<DescriptorRepository> descriptorRepositories) {
this.descriptorRepositories = descriptorRepositories;
}
@Override
public String getFullyQualifiedName() {
return PACKAGE + "." + SIMPLE_NAME;
}
@Override
public Level getLevel() {
return Level.CLASS;
}
@Override
public NodeData resolve(Node node, String mappedClass) {
if (!(node instanceof ClassOrInterfaceDeclaration)) {
throw new IllegalArgumentException("this annotation belongs only on ClassOrInterfaceDeclaration");
}
final TypeDeclaration dclr = (TypeDeclaration) node;
if (!(dclr.getParentNode() instanceof CompilationUnit)) {
//handling nested classes
return null;
}
final String name = dclr.getName();
final String pckg = ((CompilationUnit) dclr.getParentNode()).getPackage().getName().toString();
final String enclosingClass = pckg + "." + name;
final ClassDescriptor cd = OjbUtil.findClassDescriptor(enclosingClass, descriptorRepositories);
if (cd != null) {
return new NodeData(new MarkerAnnotationExpr(new NameExpr(SIMPLE_NAME)),
new ImportDeclaration(new QualifiedNameExpr(new NameExpr(PACKAGE), SIMPLE_NAME), false, false));
}
return null;
}
}
| apache-2.0 |
emre-aydin/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/ClusterHeartbeatManager.java | 35695 | /*
* Copyright (c) 2008-2021, Hazelcast, 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.
*/
package com.hazelcast.internal.cluster.impl;
import com.hazelcast.cluster.Address;
import com.hazelcast.cluster.Member;
import com.hazelcast.cluster.impl.MemberImpl;
import com.hazelcast.config.IcmpFailureDetectorConfig;
import com.hazelcast.instance.impl.Node;
import com.hazelcast.internal.cluster.MemberInfo;
import com.hazelcast.internal.cluster.fd.ClusterFailureDetector;
import com.hazelcast.internal.cluster.fd.ClusterFailureDetectorType;
import com.hazelcast.internal.cluster.fd.DeadlineClusterFailureDetector;
import com.hazelcast.internal.cluster.fd.PhiAccrualClusterFailureDetector;
import com.hazelcast.internal.cluster.fd.PingFailureDetector;
import com.hazelcast.internal.cluster.impl.operations.ExplicitSuspicionOp;
import com.hazelcast.internal.cluster.impl.operations.HeartbeatComplaintOp;
import com.hazelcast.internal.cluster.impl.operations.HeartbeatOp;
import com.hazelcast.internal.metrics.Probe;
import com.hazelcast.internal.nio.Connection;
import com.hazelcast.internal.util.Clock;
import com.hazelcast.internal.util.ICMPHelper;
import com.hazelcast.logging.ILogger;
import com.hazelcast.spi.impl.NodeEngineImpl;
import com.hazelcast.spi.impl.executionservice.ExecutionService;
import com.hazelcast.spi.impl.operationservice.Operation;
import com.hazelcast.spi.impl.operationservice.OperationService;
import com.hazelcast.spi.properties.ClusterProperty;
import com.hazelcast.spi.properties.HazelcastProperties;
import com.hazelcast.splitbrainprotection.impl.SplitBrainProtectionServiceImpl;
import java.io.IOException;
import java.net.ConnectException;
import java.util.Collection;
import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.logging.Level;
import static com.hazelcast.cluster.memberselector.MemberSelectors.NON_LOCAL_MEMBER_SELECTOR;
import static com.hazelcast.config.ConfigAccessor.getActiveMemberNetworkConfig;
import static com.hazelcast.instance.EndpointQualifier.MEMBER;
import static com.hazelcast.internal.cluster.impl.ClusterServiceImpl.CLUSTER_EXECUTOR_NAME;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.CLUSTER_METRIC_HEARTBEAT_MANAGER_LAST_HEARTBEAT;
import static com.hazelcast.internal.metrics.ProbeUnit.MS;
import static com.hazelcast.internal.util.EmptyStatement.ignore;
import static com.hazelcast.internal.util.StringUtil.timeToString;
import static java.lang.String.format;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
import static java.util.stream.Collectors.toSet;
/**
* ClusterHeartbeatManager manages the heartbeat sending and receiving
* process of a node.
* <p>
* It periodically sends heartbeat to the other nodes and stores heartbeat timestamps
* per node when a heartbeat is received from other nodes. If enabled and required, it can send
* ping packets (an ICMP ping or an echo packet depending on the environment and settings).
* <p>
* If it detects a member is not live anymore, that member is kicked out of cluster.
*/
public class ClusterHeartbeatManager {
private static final long CLOCK_JUMP_THRESHOLD = MINUTES.toMillis(2);
private static final int HEART_BEAT_INTERVAL_FACTOR = 10;
private static final int MAX_PING_RETRY_COUNT = 5;
private static final long MIN_ICMP_INTERVAL_MILLIS = SECONDS.toMillis(1);
private static final int DEFAULT_ICMP_TIMEOUT_MILLIS = 1000;
private static final int DEFAULT_ICMP_INTERVAL_MILLIS = 1000;
private final ILogger logger;
private final Lock clusterServiceLock;
private final Node node;
private final NodeEngineImpl nodeEngine;
private final ClusterServiceImpl clusterService;
private final ClusterClockImpl clusterClock;
private final ClusterFailureDetector heartbeatFailureDetector;
private final PingFailureDetector<Member> icmpFailureDetector;
private final long maxNoHeartbeatMillis;
private final long heartbeatIntervalMillis;
private final long legacyIcmpCheckThresholdMillis;
private final boolean icmpEnabled;
private final boolean icmpParallelMode;
private final int icmpTtl;
private final int icmpTimeoutMillis;
private final int icmpIntervalMillis;
private final int icmpMaxAttempts;
@Probe(name = CLUSTER_METRIC_HEARTBEAT_MANAGER_LAST_HEARTBEAT, unit = MS)
private volatile long lastHeartbeat;
private volatile long lastClusterTimeDiff;
@SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity", "checkstyle:executablestatementcount"})
ClusterHeartbeatManager(Node node, ClusterServiceImpl clusterService, Lock lock) {
this.node = node;
this.clusterService = clusterService;
this.nodeEngine = node.getNodeEngine();
clusterClock = clusterService.getClusterClock();
logger = node.getLogger(getClass());
clusterServiceLock = lock;
HazelcastProperties hazelcastProperties = node.getProperties();
maxNoHeartbeatMillis = hazelcastProperties.getMillis(ClusterProperty.MAX_NO_HEARTBEAT_SECONDS);
heartbeatIntervalMillis = getHeartbeatInterval(hazelcastProperties);
legacyIcmpCheckThresholdMillis = heartbeatIntervalMillis * HEART_BEAT_INTERVAL_FACTOR;
IcmpFailureDetectorConfig icmpConfig
= getActiveMemberNetworkConfig(node.config).getIcmpFailureDetectorConfig();
this.icmpTtl = icmpConfig != null ? icmpConfig.getTtl() : 0;
this.icmpTimeoutMillis = icmpConfig != null ? icmpConfig.getTimeoutMilliseconds() : DEFAULT_ICMP_TIMEOUT_MILLIS;
this.icmpIntervalMillis = icmpConfig != null ? icmpConfig.getIntervalMilliseconds() : DEFAULT_ICMP_INTERVAL_MILLIS;
this.icmpMaxAttempts = icmpConfig != null ? icmpConfig.getMaxAttempts() : 3;
this.icmpEnabled = icmpConfig != null && icmpConfig.isEnabled();
this.icmpParallelMode = icmpEnabled && icmpConfig.isParallelMode();
if (icmpTimeoutMillis > icmpIntervalMillis) {
throw new IllegalStateException("ICMP timeout is set to a value greater than the ICMP interval, "
+ "this is not allowed.");
}
if (icmpIntervalMillis < MIN_ICMP_INTERVAL_MILLIS) {
throw new IllegalStateException("ICMP interval is set to a value less than the min allowed, "
+ MIN_ICMP_INTERVAL_MILLIS + "ms");
}
this.icmpFailureDetector = createIcmpFailureDetectorIfNeeded();
heartbeatFailureDetector = createHeartbeatFailureDetector(hazelcastProperties);
}
private PingFailureDetector createIcmpFailureDetectorIfNeeded() {
IcmpFailureDetectorConfig icmpFailureDetectorConfig
= getActiveMemberNetworkConfig(node.config).getIcmpFailureDetectorConfig();
boolean icmpEchoFailFast = icmpFailureDetectorConfig == null || icmpFailureDetectorConfig.isFailFastOnStartup();
if (icmpParallelMode) {
if (icmpEchoFailFast) {
logger.info("Checking that ICMP failure-detector is permitted. Attempting to create a raw-socket using JNI.");
if (!ICMPHelper.isRawSocketPermitted()) {
throw new IllegalStateException("ICMP failure-detector can't be used in this environment. "
+ "Check Hazelcast Documentation Chapter on the Ping Failure Detector for supported platforms "
+ "and how to enable this capability for your operating system");
}
logger.info("ICMP failure-detector is supported, enabling.");
}
return new PingFailureDetector(icmpMaxAttempts);
}
return null;
}
private ClusterFailureDetector createHeartbeatFailureDetector(HazelcastProperties properties) {
String type = properties.getString(ClusterProperty.HEARTBEAT_FAILURE_DETECTOR_TYPE);
ClusterFailureDetectorType fdType = ClusterFailureDetectorType.of(type);
switch (fdType) {
case DEADLINE:
return new DeadlineClusterFailureDetector(maxNoHeartbeatMillis);
case PHI_ACCRUAL:
int defaultValue = Integer.parseInt(ClusterProperty.MAX_NO_HEARTBEAT_SECONDS.getDefaultValue());
if (maxNoHeartbeatMillis == TimeUnit.SECONDS.toMillis(defaultValue)) {
logger.warning("When using Phi-Accrual Failure Detector, please consider using a lower '"
+ ClusterProperty.MAX_NO_HEARTBEAT_SECONDS.getName() + "' value. Current is: "
+ defaultValue + " seconds.");
}
return new PhiAccrualClusterFailureDetector(maxNoHeartbeatMillis, heartbeatIntervalMillis, properties);
default:
throw new IllegalArgumentException("Unknown failure detector type: " + type);
}
}
public long getHeartbeatIntervalMillis() {
return heartbeatIntervalMillis;
}
public long getLastHeartbeatTime(Member member) {
return heartbeatFailureDetector.lastHeartbeat(member);
}
private static long getHeartbeatInterval(HazelcastProperties hazelcastProperties) {
long heartbeatInterval = hazelcastProperties.getMillis(ClusterProperty.HEARTBEAT_INTERVAL_SECONDS);
return heartbeatInterval > 0 ? heartbeatInterval : TimeUnit.SECONDS.toMillis(1);
}
/**
* Initializes the {@link ClusterHeartbeatManager}. It will schedule the
* heartbeat operation to the {@link #getHeartbeatInterval(HazelcastProperties)} interval.
*/
void init() {
ExecutionService executionService = nodeEngine.getExecutionService();
executionService.scheduleWithRepetition(CLUSTER_EXECUTOR_NAME, this::heartbeat,
heartbeatIntervalMillis, heartbeatIntervalMillis, TimeUnit.MILLISECONDS);
if (icmpParallelMode) {
startPeriodicPinger();
}
}
public void handleHeartbeat(MembersViewMetadata senderMembersViewMetadata, UUID receiverUuid, long timestamp,
Collection<MemberInfo> suspectedMembers) {
Address senderAddress = senderMembersViewMetadata.getMemberAddress();
try {
long timeout = Math.min(TimeUnit.SECONDS.toMillis(1), heartbeatIntervalMillis / 2);
if (!clusterServiceLock.tryLock(timeout, MILLISECONDS)) {
logger.warning("Cannot handle heartbeat from " + senderAddress + ", could not acquire lock in time.");
return;
}
} catch (InterruptedException e) {
logger.warning("Cannot handle heartbeat from " + senderAddress + ", thread interrupted.");
Thread.currentThread().interrupt();
return;
}
try {
if (!clusterService.isJoined()) {
if (clusterService.getThisUuid().equals(receiverUuid)) {
logger.fine("Ignoring heartbeat of sender: " + senderMembersViewMetadata + ", because node is not joined!");
} else {
// we know that sender version is 3.9 so we send explicit suspicion back even if we are not joined...
logger.fine("Sending explicit suspicion to " + senderAddress + " for heartbeat " + senderMembersViewMetadata
+ ", because this node has received an invalid heartbeat before it joins to the cluster");
OperationService operationService = nodeEngine.getOperationService();
Operation op = new ExplicitSuspicionOp(senderMembersViewMetadata);
operationService.send(op, senderAddress);
}
return;
}
MembershipManager membershipManager = clusterService.getMembershipManager();
MemberImpl member = membershipManager.getMember(senderAddress, senderMembersViewMetadata.getMemberUuid());
if (member != null) {
if (clusterService.getThisUuid().equals(receiverUuid)) {
if (onHeartbeat(member, timestamp)) {
// local timestamp is used on purpose here
membershipManager.handleReceivedSuspectedMembers(member, clusterClock.getClusterTime(), suspectedMembers);
}
return;
}
logger.warning("Local UUID mismatch on received heartbeat. local UUID: " + clusterService.getThisUuid()
+ " received UUID: " + receiverUuid + " with " + senderMembersViewMetadata);
}
onInvalidHeartbeat(senderMembersViewMetadata);
} finally {
clusterServiceLock.unlock();
}
}
private void onInvalidHeartbeat(MembersViewMetadata senderMembersViewMetadata) {
Address senderAddress = senderMembersViewMetadata.getMemberAddress();
if (clusterService.isMaster()) {
if (!clusterService.getClusterJoinManager().isMastershipClaimInProgress()) {
logger.fine("Sending explicit suspicion to " + senderAddress + " for heartbeat "
+ senderMembersViewMetadata + ", because it is not a member of this cluster"
+ " or its heartbeat cannot be validated!");
clusterService.sendExplicitSuspicion(senderMembersViewMetadata);
}
} else {
MemberImpl master = clusterService.getMember(clusterService.getMasterAddress());
if (clusterService.getMembershipManager().isMemberSuspected(master)) {
logger.fine("Not sending heartbeat complaint for " + senderMembersViewMetadata
+ " to suspected master: " + master.getAddress());
return;
}
logger.fine("Sending heartbeat complaint to master " + master.getAddress() + " for heartbeat "
+ senderMembersViewMetadata + ", because it is not a member of this cluster"
+ " or its heartbeat cannot be validated!");
sendHeartbeatComplaintToMaster(senderMembersViewMetadata);
}
}
private void sendHeartbeatComplaintToMaster(MembersViewMetadata senderMembersViewMetadata) {
if (clusterService.isMaster()) {
logger.warning("Cannot send heartbeat complaint for " + senderMembersViewMetadata + " to itself.");
return;
}
Address masterAddress = clusterService.getMasterAddress();
if (masterAddress == null) {
logger.fine("Cannot send heartbeat complaint for " + senderMembersViewMetadata.getMemberAddress()
+ ", master address is not set.");
return;
}
MembersViewMetadata localMembersViewMetadata = clusterService.getMembershipManager().createLocalMembersViewMetadata();
Operation op = new HeartbeatComplaintOp(localMembersViewMetadata, senderMembersViewMetadata);
OperationService operationService = nodeEngine.getOperationService();
operationService.send(op, masterAddress);
}
public void handleHeartbeatComplaint(MembersViewMetadata receiverMVMetadata, MembersViewMetadata senderMVMetadata) {
clusterServiceLock.lock();
try {
if (!clusterService.isJoined()) {
logger.warning("Ignoring heartbeat complaint of receiver: " + receiverMVMetadata
+ " and sender: " + senderMVMetadata + " because not joined!");
return;
}
MembershipManager membershipManager = clusterService.getMembershipManager();
ClusterJoinManager clusterJoinManager = clusterService.getClusterJoinManager();
if (!clusterService.isMaster()) {
logger.warning("Ignoring heartbeat complaint of receiver: " + receiverMVMetadata
+ " for sender: " + senderMVMetadata + " because this node is not master");
return;
} else if (clusterJoinManager.isMastershipClaimInProgress()) {
logger.fine("Ignoring heartbeat complaint of receiver: " + receiverMVMetadata
+ " for sender: " + senderMVMetadata + " because mastership claim process is ongoing");
return;
} else if (senderMVMetadata.getMemberAddress().equals(receiverMVMetadata.getMemberAddress())) {
logger.warning("Ignoring heartbeat complaint of receiver: " + receiverMVMetadata
+ " for sender: " + senderMVMetadata + " because they are same member");
return;
}
if (membershipManager.validateMembersViewMetadata(senderMVMetadata)) {
if (membershipManager.validateMembersViewMetadata(receiverMVMetadata)) {
logger.fine("Sending latest member list to " + senderMVMetadata.getMemberAddress()
+ " and " + receiverMVMetadata.getMemberAddress() + " after heartbeat complaint.");
membershipManager.sendMemberListToMember(senderMVMetadata.getMemberAddress());
membershipManager.sendMemberListToMember(receiverMVMetadata.getMemberAddress());
} else {
logger.fine("Complainer " + receiverMVMetadata.getMemberAddress() + " will explicitly suspect from "
+ node.getThisAddress() + " and " + senderMVMetadata.getMemberAddress());
clusterService.sendExplicitSuspicion(receiverMVMetadata);
clusterService.sendExplicitSuspicionTrigger(senderMVMetadata.getMemberAddress(), receiverMVMetadata);
}
} else if (membershipManager.validateMembersViewMetadata(receiverMVMetadata)) {
logger.fine("Complainee " + senderMVMetadata.getMemberAddress() + " will explicitly suspect from "
+ node.getThisAddress() + " and " + receiverMVMetadata.getMemberAddress());
clusterService.sendExplicitSuspicion(senderMVMetadata);
clusterService.sendExplicitSuspicionTrigger(receiverMVMetadata.getMemberAddress(), senderMVMetadata);
} else {
logger.fine("Both complainer " + receiverMVMetadata.getMemberAddress()
+ " and complainee " + senderMVMetadata.getMemberAddress()
+ " will explicitly suspect from " + node.getThisAddress());
clusterService.sendExplicitSuspicion(senderMVMetadata);
clusterService.sendExplicitSuspicion(receiverMVMetadata);
}
} finally {
clusterServiceLock.unlock();
}
}
/**
* Accepts the heartbeat message from {@code member} created at {@code timestamp}. The timestamp must be
* related to the cluster clock, not the local clock. The heartbeat is ignored if the duration between
* {@code timestamp} and the current cluster time is more than {@link ClusterProperty#MAX_NO_HEARTBEAT_SECONDS}/2.
* If the sending node is the master, this node will also calculate and set the cluster clock diff.
*
* @param member the member sending the heartbeat
* @param timestamp the timestamp when the heartbeat was created
* @return true if the heartbeat is processed, false if it is ignored.
*/
public boolean onHeartbeat(MemberImpl member, long timestamp) {
if (member == null) {
return false;
}
long clusterTime = clusterClock.getClusterTime();
if (logger.isFineEnabled()) {
logger.fine(format("Received heartbeat from %s (now: %s, timestamp: %s)",
member, timeToString(clusterTime), timeToString(timestamp)));
}
if (clusterTime - timestamp > maxNoHeartbeatMillis / 2) {
logger.warning(format("Ignoring heartbeat from %s since it is expired (now: %s, timestamp: %s)", member,
timeToString(clusterTime), timeToString(timestamp)));
return false;
}
if (isMaster(member)) {
clusterClock.setMasterTime(timestamp);
}
heartbeatFailureDetector.heartbeat(member, clusterClock.getClusterTime());
MembershipManager membershipManager = clusterService.getMembershipManager();
membershipManager.clearMemberSuspicion(member, "Valid heartbeat");
nodeEngine.getSplitBrainProtectionService().onHeartbeat(member, timestamp);
return true;
}
/**
* Send heartbeats and calculate clock drift. This method is expected to be called periodically because it calculates
* the clock drift based on the expected and actual invocation period.
*/
void heartbeat() {
if (!clusterService.isJoined()) {
return;
}
checkClockDrift(heartbeatIntervalMillis);
final long clusterTime = clusterClock.getClusterTime();
if (clusterService.isMaster()) {
heartbeatWhenMaster(clusterTime);
} else {
heartbeatWhenSlave(clusterTime);
}
}
/**
* Checks the elapsed time from the last local heartbeat and compares it to the expected {@code intervalMillis}.
* The method will correct a number of clocks and timestamps based on this difference:
* <ul>
* <li>
* set the local cluster time diff if the absolute diff is larger than {@link #CLOCK_JUMP_THRESHOLD} and
* the change in diff from the previous and current value is less than {@link #CLOCK_JUMP_THRESHOLD}.
* In the case that the diff change is larger than the threshold, we assume that the current clock diff is not
* from any local cause but that this node received a heartbeat message from the master, setting the cluster clock diff.
* </li>
* <li>
* Reset the heartbeat timestamps if the absolute diff is greater or equal to
* {@link ClusterProperty#MAX_NO_HEARTBEAT_SECONDS}/2
* </li>
* </ul>
*
* @param intervalMillis the expected elapsed interval of the cluster clock
*/
private void checkClockDrift(long intervalMillis) {
long now = Clock.currentTimeMillis();
// compensate for any abrupt jumps forward in the system clock
if (lastHeartbeat != 0L) {
long clockJump = now - lastHeartbeat - intervalMillis;
long absoluteClockJump = Math.abs(clockJump);
if (absoluteClockJump > CLOCK_JUMP_THRESHOLD) {
logger.info(format("System clock apparently jumped from %s to %s since last heartbeat (%+d ms)",
timeToString(lastHeartbeat), timeToString(now), clockJump));
// We only set cluster clock, if clock jumps more than threshold.
// If the last cluster-time diff we've seen is significantly different than what we read now,
// that means, it's already adjusted by master heartbeat. Then don't update the cluster time again.
long currentClusterTimeDiff = clusterClock.getClusterTimeDiff();
if (Math.abs(lastClusterTimeDiff - currentClusterTimeDiff) < CLOCK_JUMP_THRESHOLD) {
// adjust cluster clock due to clock drift
clusterClock.setClusterTimeDiff(currentClusterTimeDiff - clockJump);
}
}
if (absoluteClockJump >= maxNoHeartbeatMillis / 2) {
logger.warning(format("Resetting heartbeat timestamps because of huge system clock jump!"
+ " Clock-Jump: %d ms, Heartbeat-Timeout: %d ms", clockJump, maxNoHeartbeatMillis));
resetHeartbeats();
}
}
lastClusterTimeDiff = clusterClock.getClusterTimeDiff();
lastHeartbeat = now;
}
/**
* Sends heartbeat to each of the cluster members.
* Checks whether a member has failed to send a heartbeat in time
* (see {@link #maxNoHeartbeatMillis})
* and removes that member from the cluster.
* <p></p>
* This method is only called on the master member.
*
* @param now the current cluster clock time
*/
private void heartbeatWhenMaster(long now) {
for (Member member : clusterService.getMembers(NON_LOCAL_MEMBER_SELECTOR)) {
try {
logIfConnectionToEndpointIsMissing(now, member);
if (suspectMemberIfNotHeartBeating(now, member)) {
continue;
}
pingMemberIfRequired(now, member);
sendHeartbeat(member);
} catch (Throwable t) {
logger.severe(t);
}
}
clusterService.getMembershipManager().checkPartialDisconnectivity(now);
}
/**
* Removes the {@code member} if it has not sent any heartbeats in {@link ClusterProperty#MAX_NO_HEARTBEAT_SECONDS}.
* If it has not sent any heartbeats in {@link #HEART_BEAT_INTERVAL_FACTOR} heartbeat intervals, it will log a warning.
*
* @param now the current cluster clock time
* @param member the member which needs to be checked
* @return if the member has been removed
*/
private boolean suspectMemberIfNotHeartBeating(long now, Member member) {
if (clusterService.getMembershipManager().isMemberSuspected((MemberImpl) member)) {
return true;
}
long lastHeartbeat = heartbeatFailureDetector.lastHeartbeat(member);
if (!heartbeatFailureDetector.isAlive(member, now)) {
double suspicionLevel = heartbeatFailureDetector.suspicionLevel(member, now);
String reason = format("Suspecting %s because it has not sent any heartbeats since %s."
+ " Now: %s, heartbeat timeout: %d ms, suspicion level: %.2f",
member, timeToString(lastHeartbeat), timeToString(now), maxNoHeartbeatMillis, suspicionLevel);
logger.warning(reason);
clusterService.suspectMember(member, reason, true);
return true;
}
if (logger.isFineEnabled() && (now - lastHeartbeat) > heartbeatIntervalMillis * HEART_BEAT_INTERVAL_FACTOR) {
double suspicionLevel = heartbeatFailureDetector.suspicionLevel(member, now);
logger.fine(format("Not receiving any heartbeats from %s since %s, suspicion level: %.2f",
member, timeToString(lastHeartbeat), suspicionLevel));
}
return false;
}
/**
* Sends heartbeat to each of the cluster members.
* Checks whether the master member has failed to send a heartbeat (see {@link #maxNoHeartbeatMillis})
* and removes that master member from cluster, if it fails on heartbeat.
* <p></p>
* This method is called on NON-master members.
*/
private void heartbeatWhenSlave(long now) {
MembershipManager membershipManager = clusterService.getMembershipManager();
for (Member member : clusterService.getMembers(NON_LOCAL_MEMBER_SELECTOR)) {
try {
logIfConnectionToEndpointIsMissing(now, member);
if (suspectMemberIfNotHeartBeating(now, member)) {
continue;
}
if (membershipManager.isMemberSuspected((MemberImpl) member)) {
continue;
}
pingMemberIfRequired(now, member);
sendHeartbeat(member);
} catch (Throwable e) {
logger.severe(e);
}
}
}
private boolean isMaster(MemberImpl member) {
return member.getAddress().equals(clusterService.getMasterAddress());
}
/**
* Pings the {@code member} if ICMP is enabled and more than {@link #HEART_BEAT_INTERVAL_FACTOR}
* heartbeats have passed.
*/
private void pingMemberIfRequired(long now, Member member) {
if (!icmpEnabled || icmpParallelMode) {
return;
}
long lastHeartbeat = heartbeatFailureDetector.lastHeartbeat(member);
if ((now - lastHeartbeat) >= legacyIcmpCheckThresholdMillis) {
runPingTask(member);
}
}
private void startPeriodicPinger() {
nodeEngine.getExecutionService().scheduleWithRepetition(CLUSTER_EXECUTOR_NAME, () -> {
Collection<Member> members = clusterService.getMembers(NON_LOCAL_MEMBER_SELECTOR);
for (Member member : members) {
try {
runPingTask(member);
} catch (Throwable e) {
logger.severe(e);
}
}
}, icmpIntervalMillis, icmpIntervalMillis, TimeUnit.MILLISECONDS);
}
/**
* Tries to ping the {@code member} and removes the member if it is unreachable.
*
* @param member the member for which we need to determine reachability
*/
private void runPingTask(final Member member) {
nodeEngine.getExecutionService().execute(ExecutionService.SYSTEM_EXECUTOR,
icmpParallelMode ? new PeriodicPingTask(member) : new PingTask(member));
}
/**
* Send a {@link HeartbeatOp} to the {@code target}
*
* @param target target Member
*/
private void sendHeartbeat(Member target) {
if (target == null) {
return;
}
try {
MembersViewMetadata membersViewMetadata = clusterService.getMembershipManager().createLocalMembersViewMetadata();
Collection<MemberInfo> suspectedMembers = Collections.emptySet();
if (clusterService.getMembershipManager().isPartialDisconnectionDetectionEnabled()
&& !clusterService.isMaster() && target.getAddress().equals(clusterService.getMasterAddress())) {
suspectedMembers = clusterService.getMembershipManager()
.getSuspectedMembers()
.stream()
.map(MemberInfo::new)
.collect(toSet());
}
long clusterTime = clusterClock.getClusterTime();
Operation op = new HeartbeatOp(membersViewMetadata, target.getUuid(), clusterTime, suspectedMembers);
op.setCallerUuid(clusterService.getThisUuid());
node.nodeEngine.getOperationService().send(op, target.getAddress());
} catch (Exception e) {
if (logger.isFineEnabled()) {
logger.fine(format("Error while sending heartbeat -> %s[%s]", e.getClass().getName(), e.getMessage()));
}
}
}
/**
* Logs a warning if the {@code member} hasn't sent a heartbeat in {@link #HEART_BEAT_INTERVAL_FACTOR} heartbeat
* intervals and there is no live connection to the member
*/
private void logIfConnectionToEndpointIsMissing(long now, Member member) {
long heartbeatTime = heartbeatFailureDetector.lastHeartbeat(member);
if ((now - heartbeatTime) >= heartbeatIntervalMillis * HEART_BEAT_INTERVAL_FACTOR) {
Connection conn = node.getServer().getConnectionManager(MEMBER).getOrConnect(member.getAddress());
if (conn == null || !conn.isAlive()) {
logger.warning("This node does not have a connection to " + member);
}
}
}
/** Reset all heartbeats to the current cluster time. Called when system clock jump is detected. */
private void resetHeartbeats() {
SplitBrainProtectionServiceImpl splitBrainProtectionService = nodeEngine.getSplitBrainProtectionService();
long now = clusterClock.getClusterTime();
for (MemberImpl member : clusterService.getMemberImpls()) {
heartbeatFailureDetector.heartbeat(member, now);
splitBrainProtectionService.onHeartbeat(member, now);
}
}
/** Remove the {@code member}'s heartbeat timestamps */
void removeMember(MemberImpl member) {
heartbeatFailureDetector.remove(member);
if (icmpParallelMode) {
icmpFailureDetector.remove(member);
}
}
void reset() {
heartbeatFailureDetector.reset();
if (icmpParallelMode) {
icmpFailureDetector.reset();
}
}
private class PingTask
implements Runnable {
final Member member;
PingTask(Member member) {
this.member = member;
}
public void run() {
Address address = member.getAddress();
logger.warning(format("%s will ping %s", node.getThisAddress(), address));
for (int i = 0; i < MAX_PING_RETRY_COUNT; i++) {
if (doPing(address, Level.INFO)) {
return;
}
}
// host not reachable
String reason = format("%s could not ping %s", node.getThisAddress(), address);
logger.warning(reason);
clusterService.suspectMember(member, reason, true);
}
boolean doPing(Address address, Level level) {
try {
if (address.getInetAddress().isReachable(null, icmpTtl, icmpTimeoutMillis)) {
String msg = format("%s pinged %s successfully", node.getThisAddress(), address);
logger.log(level, msg);
return true;
}
} catch (ConnectException ignored) {
// no route to host, means we cannot connect anymore
ignore(ignored);
} catch (IOException e) {
if (logger.isFinestEnabled()) {
logger.finest("Failed while pinging " + address, e);
}
}
return false;
}
}
private class PeriodicPingTask
extends PingTask {
final SplitBrainProtectionServiceImpl splitBrainProtectionService = nodeEngine.getSplitBrainProtectionService();
PeriodicPingTask(Member member) {
super(member);
}
public void run() {
Address address = member.getAddress();
logger.fine(format("%s will ping %s", node.getThisAddress(), address));
if (doPing(address, Level.FINE)) {
boolean pingRestored = (icmpFailureDetector.heartbeat(member) > 0);
if (pingRestored) {
splitBrainProtectionService.onPingRestored(member);
}
return;
}
icmpFailureDetector.logAttempt(member);
splitBrainProtectionService.onPingLost(member);
// host not reachable
String reason = format("%s could not ping %s", node.getThisAddress(), address);
logger.warning(reason);
if (!icmpFailureDetector.isAlive(member)) {
clusterService.suspectMember(member, reason, true);
}
}
}
}
| apache-2.0 |
emre-aydin/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/operations/WanOperation.java | 777 | /*
* Copyright (c) 2008-2021, Hazelcast, 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.
*/
package com.hazelcast.internal.cluster.impl.operations;
/**
* Marker interface for WAN Replication Operations
*/
public interface WanOperation {
}
| apache-2.0 |
wilkinsona/spring-boot | spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleBuildFieldSetter.java | 1543 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.gradle.junit;
import java.lang.reflect.Field;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.springframework.boot.gradle.testkit.GradleBuild;
import org.springframework.util.ReflectionUtils;
/**
* {@link BeforeEachCallback} to set a test class's {@code gradleBuild} field prior to
* test exection.
*
* @author Andy Wilkinson
*/
final class GradleBuildFieldSetter implements BeforeEachCallback {
private final GradleBuild gradleBuild;
GradleBuildFieldSetter(GradleBuild gradleBuild) {
this.gradleBuild = gradleBuild;
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
Field field = ReflectionUtils.findField(context.getRequiredTestClass(), "gradleBuild");
field.setAccessible(true);
field.set(context.getRequiredTestInstance(), this.gradleBuild);
}
}
| apache-2.0 |
pquentin/libcloud | libcloud/dns/drivers/zerigo.py | 18254 | # 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.
__all__ = [
'ZerigoDNSDriver'
]
import copy
import base64
from libcloud.utils.py3 import httplib
from libcloud.utils.py3 import b
from libcloud.utils.py3 import ET
from libcloud.utils.misc import merge_valid_keys, get_new_obj
from libcloud.utils.xml import findtext, findall
from libcloud.common.base import XmlResponse, ConnectionUserAndKey
from libcloud.common.types import InvalidCredsError, LibcloudError
from libcloud.common.types import MalformedResponseError
from libcloud.dns.types import Provider, RecordType
from libcloud.dns.types import ZoneDoesNotExistError, RecordDoesNotExistError
from libcloud.dns.base import DNSDriver, Zone, Record
API_HOST = 'ns.zerigo.com'
API_VERSION = '1.1'
API_ROOT = '/api/%s/' % (API_VERSION)
VALID_ZONE_EXTRA_PARAMS = ['notes', 'tag-list', 'ns1', 'slave-nameservers']
VALID_RECORD_EXTRA_PARAMS = ['notes', 'ttl', 'priority']
# Number of items per page (maximum limit is 1000)
ITEMS_PER_PAGE = 100
class ZerigoError(LibcloudError):
def __init__(self, code, errors):
self.code = code
self.errors = errors or []
def __str__(self):
return 'Errors: %s' % (', '.join(self.errors))
def __repr__(self):
return ('<ZerigoError response code=%s, errors count=%s>' % (
self.code, len(self.errors)))
class ZerigoDNSResponse(XmlResponse):
def success(self):
return self.status in [httplib.OK, httplib.CREATED, httplib.ACCEPTED]
def parse_error(self):
status = int(self.status)
if status == 401:
if not self.body:
raise InvalidCredsError(str(self.status) + ': ' + self.error)
else:
raise InvalidCredsError(self.body)
elif status == 404:
context = self.connection.context
if context['resource'] == 'zone':
raise ZoneDoesNotExistError(value='', driver=self,
zone_id=context['id'])
elif context['resource'] == 'record':
raise RecordDoesNotExistError(value='', driver=self,
record_id=context['id'])
elif status != 503:
try:
body = ET.XML(self.body)
except:
raise MalformedResponseError('Failed to parse XML',
body=self.body)
errors = []
for error in findall(element=body, xpath='error'):
errors.append(error.text)
raise ZerigoError(code=status, errors=errors)
return self.body
class ZerigoDNSConnection(ConnectionUserAndKey):
host = API_HOST
secure = True
responseCls = ZerigoDNSResponse
def add_default_headers(self, headers):
auth_b64 = base64.b64encode(b('%s:%s' % (self.user_id, self.key)))
headers['Authorization'] = 'Basic %s' % (auth_b64.decode('utf-8'))
return headers
def request(self, action, params=None, data='', headers=None,
method='GET'):
if not headers:
headers = {}
if not params:
params = {}
if method in ("POST", "PUT"):
headers = {'Content-Type': 'application/xml; charset=UTF-8'}
return super(ZerigoDNSConnection, self).request(action=action,
params=params,
data=data,
method=method,
headers=headers)
class ZerigoDNSDriver(DNSDriver):
type = Provider.ZERIGO
name = 'Zerigo DNS'
website = 'http://www.zerigo.com/'
connectionCls = ZerigoDNSConnection
RECORD_TYPE_MAP = {
RecordType.A: 'A',
RecordType.AAAA: 'AAAA',
RecordType.CNAME: 'CNAME',
RecordType.GEO: 'GEO',
RecordType.MX: 'MX',
RecordType.NAPTR: 'NAPTR',
RecordType.NS: 'NS',
RecordType.PTR: 'PTR',
RecordType.REDIRECT: 'REDIRECT',
RecordType.SPF: 'SPF',
RecordType.SRV: 'SRV',
RecordType.TXT: 'TXT',
RecordType.URL: 'URL',
}
def iterate_zones(self):
return self._get_more('zones')
def iterate_records(self, zone):
return self._get_more('records', zone=zone)
def get_zone(self, zone_id):
path = API_ROOT + 'zones/%s.xml' % (zone_id)
self.connection.set_context({'resource': 'zone', 'id': zone_id})
data = self.connection.request(path).object
zone = self._to_zone(elem=data)
return zone
def get_record(self, zone_id, record_id):
zone = self.get_zone(zone_id=zone_id)
self.connection.set_context({'resource': 'record', 'id': record_id})
path = API_ROOT + 'hosts/%s.xml' % (record_id)
data = self.connection.request(path).object
record = self._to_record(elem=data, zone=zone)
return record
def create_zone(self, domain, type='master', ttl=None, extra=None):
"""
Create a new zone.
Provider API docs:
https://www.zerigo.com/docs/apis/dns/1.1/zones/create
@inherits: :class:`DNSDriver.create_zone`
"""
path = API_ROOT + 'zones.xml'
zone_elem = self._to_zone_elem(domain=domain, type=type, ttl=ttl,
extra=extra)
data = self.connection.request(action=path,
data=ET.tostring(zone_elem),
method='POST').object
zone = self._to_zone(elem=data)
return zone
def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None):
"""
Update an existing zone.
Provider API docs:
https://www.zerigo.com/docs/apis/dns/1.1/zones/update
@inherits: :class:`DNSDriver.update_zone`
"""
if domain:
raise LibcloudError('Domain cannot be changed', driver=self)
path = API_ROOT + 'zones/%s.xml' % (zone.id)
zone_elem = self._to_zone_elem(domain=domain, type=type, ttl=ttl,
extra=extra)
response = self.connection.request(action=path,
data=ET.tostring(zone_elem),
method='PUT')
assert response.status == httplib.OK
merged = merge_valid_keys(params=copy.deepcopy(zone.extra),
valid_keys=VALID_ZONE_EXTRA_PARAMS,
extra=extra)
updated_zone = get_new_obj(obj=zone, klass=Zone,
attributes={'type': type,
'ttl': ttl,
'extra': merged})
return updated_zone
def create_record(self, name, zone, type, data, extra=None):
"""
Create a new record.
Provider API docs:
https://www.zerigo.com/docs/apis/dns/1.1/hosts/create
@inherits: :class:`DNSDriver.create_record`
"""
path = API_ROOT + 'zones/%s/hosts.xml' % (zone.id)
record_elem = self._to_record_elem(name=name, type=type, data=data,
extra=extra)
response = self.connection.request(action=path,
data=ET.tostring(record_elem),
method='POST')
assert response.status == httplib.CREATED
record = self._to_record(elem=response.object, zone=zone)
return record
def update_record(self, record, name=None, type=None, data=None,
extra=None):
path = API_ROOT + 'hosts/%s.xml' % (record.id)
record_elem = self._to_record_elem(name=name, type=type, data=data,
extra=extra)
response = self.connection.request(action=path,
data=ET.tostring(record_elem),
method='PUT')
assert response.status == httplib.OK
merged = merge_valid_keys(params=copy.deepcopy(record.extra),
valid_keys=VALID_RECORD_EXTRA_PARAMS,
extra=extra)
updated_record = get_new_obj(obj=record, klass=Record,
attributes={'type': type,
'data': data,
'extra': merged})
return updated_record
def delete_zone(self, zone):
path = API_ROOT + 'zones/%s.xml' % (zone.id)
self.connection.set_context({'resource': 'zone', 'id': zone.id})
response = self.connection.request(action=path, method='DELETE')
return response.status == httplib.OK
def delete_record(self, record):
path = API_ROOT + 'hosts/%s.xml' % (record.id)
self.connection.set_context({'resource': 'record', 'id': record.id})
response = self.connection.request(action=path, method='DELETE')
return response.status == httplib.OK
def ex_get_zone_by_domain(self, domain):
"""
Retrieve a zone object by the domain name.
:param domain: The domain which should be used
:type domain: ``str``
:rtype: :class:`Zone`
"""
path = API_ROOT + 'zones/%s.xml' % (domain)
self.connection.set_context({'resource': 'zone', 'id': domain})
data = self.connection.request(path).object
zone = self._to_zone(elem=data)
return zone
def ex_force_slave_axfr(self, zone):
"""
Force a zone transfer.
:param zone: Zone which should be used.
:type zone: :class:`Zone`
:rtype: :class:`Zone`
"""
path = API_ROOT + 'zones/%s/force_slave_axfr.xml' % (zone.id)
self.connection.set_context({'resource': 'zone', 'id': zone.id})
response = self.connection.request(path, method='POST')
assert response.status == httplib.ACCEPTED
return zone
def _to_zone_elem(self, domain=None, type=None, ttl=None, extra=None):
zone_elem = ET.Element('zone', {})
if domain:
domain_elem = ET.SubElement(zone_elem, 'domain')
domain_elem.text = domain
if type:
ns_type_elem = ET.SubElement(zone_elem, 'ns-type')
if type == 'master':
ns_type_elem.text = 'pri_sec'
elif type == 'slave':
if not extra or 'ns1' not in extra:
raise LibcloudError('ns1 extra attribute is required ' +
'when zone type is slave', driver=self)
ns_type_elem.text = 'sec'
ns1_elem = ET.SubElement(zone_elem, 'ns1')
ns1_elem.text = extra['ns1']
elif type == 'std_master':
# TODO: Each driver should provide supported zone types
# Slave name servers are elsewhere
if not extra or 'slave-nameservers' not in extra:
raise LibcloudError('slave-nameservers extra ' +
'attribute is required whenzone ' +
'type is std_master', driver=self)
ns_type_elem.text = 'pri'
slave_nameservers_elem = ET.SubElement(zone_elem,
'slave-nameservers')
slave_nameservers_elem.text = extra['slave-nameservers']
if ttl:
default_ttl_elem = ET.SubElement(zone_elem, 'default-ttl')
default_ttl_elem.text = str(ttl)
if extra and 'tag-list' in extra:
tags = extra['tag-list']
tags_elem = ET.SubElement(zone_elem, 'tag-list')
tags_elem.text = ' '.join(tags)
return zone_elem
def _to_record_elem(self, name=None, type=None, data=None, extra=None):
record_elem = ET.Element('host', {})
if name:
name_elem = ET.SubElement(record_elem, 'hostname')
name_elem.text = name
if type is not None:
type_elem = ET.SubElement(record_elem, 'host-type')
type_elem.text = self.RECORD_TYPE_MAP[type]
if data:
data_elem = ET.SubElement(record_elem, 'data')
data_elem.text = data
if extra:
if 'ttl' in extra:
ttl_elem = ET.SubElement(record_elem, 'ttl',
{'type': 'integer'})
ttl_elem.text = str(extra['ttl'])
if 'priority' in extra:
# Only MX and SRV records support priority
priority_elem = ET.SubElement(record_elem, 'priority',
{'type': 'integer'})
priority_elem.text = str(extra['priority'])
if 'notes' in extra:
notes_elem = ET.SubElement(record_elem, 'notes')
notes_elem.text = extra['notes']
return record_elem
def _to_zones(self, elem):
zones = []
for item in findall(element=elem, xpath='zone'):
zone = self._to_zone(elem=item)
zones.append(zone)
return zones
def _to_zone(self, elem):
id = findtext(element=elem, xpath='id')
domain = findtext(element=elem, xpath='domain')
type = findtext(element=elem, xpath='ns-type')
type = 'master' if type.find('pri') == 0 else 'slave'
ttl = findtext(element=elem, xpath='default-ttl')
hostmaster = findtext(element=elem, xpath='hostmaster')
custom_ns = findtext(element=elem, xpath='custom-ns')
custom_nameservers = findtext(element=elem, xpath='custom-nameservers')
notes = findtext(element=elem, xpath='notes')
nx_ttl = findtext(element=elem, xpath='nx-ttl')
slave_nameservers = findtext(element=elem, xpath='slave-nameservers')
tags = findtext(element=elem, xpath='tag-list')
tags = tags.split(' ') if tags else []
extra = {'hostmaster': hostmaster, 'custom-ns': custom_ns,
'custom-nameservers': custom_nameservers, 'notes': notes,
'nx-ttl': nx_ttl, 'slave-nameservers': slave_nameservers,
'tags': tags}
zone = Zone(id=str(id), domain=domain, type=type, ttl=int(ttl),
driver=self, extra=extra)
return zone
def _to_records(self, elem, zone):
records = []
for item in findall(element=elem, xpath='host'):
record = self._to_record(elem=item, zone=zone)
records.append(record)
return records
def _to_record(self, elem, zone):
id = findtext(element=elem, xpath='id')
name = findtext(element=elem, xpath='hostname')
type = findtext(element=elem, xpath='host-type')
type = self._string_to_record_type(type)
data = findtext(element=elem, xpath='data')
notes = findtext(element=elem, xpath='notes', no_text_value=None)
state = findtext(element=elem, xpath='state', no_text_value=None)
fqdn = findtext(element=elem, xpath='fqdn', no_text_value=None)
priority = findtext(element=elem, xpath='priority', no_text_value=None)
ttl = findtext(element=elem, xpath='ttl', no_text_value=None)
if not name:
name = None
if ttl:
ttl = int(ttl)
extra = {'notes': notes, 'state': state, 'fqdn': fqdn,
'priority': priority, 'ttl': ttl}
record = Record(id=id, name=name, type=type, data=data,
zone=zone, driver=self, ttl=ttl, extra=extra)
return record
def _get_more(self, rtype, **kwargs):
exhausted = False
last_key = None
while not exhausted:
items, last_key, exhausted = self._get_data(rtype, last_key,
**kwargs)
for item in items:
yield item
def _get_data(self, rtype, last_key, **kwargs):
# Note: last_key in this case really is a "last_page".
# TODO: Update base driver and change last_key to something more
# generic - e.g. marker
params = {}
params['per_page'] = ITEMS_PER_PAGE
params['page'] = last_key + 1 if last_key else 1
if rtype == 'zones':
path = API_ROOT + 'zones.xml'
response = self.connection.request(path)
transform_func = self._to_zones
elif rtype == 'records':
zone = kwargs['zone']
path = API_ROOT + 'zones/%s/hosts.xml' % (zone.id)
self.connection.set_context({'resource': 'zone', 'id': zone.id})
response = self.connection.request(path, params=params)
transform_func = self._to_records
exhausted = False
result_count = int(response.headers.get('x-query-count', 0))
if (params['page'] * ITEMS_PER_PAGE) >= result_count:
exhausted = True
if response.status == httplib.OK:
items = transform_func(elem=response.object, **kwargs)
return items, params['page'], exhausted
else:
return [], None, True
| apache-2.0 |
ricepanda/rice-git2 | rice-framework/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/service/UifDefaultingService.java | 4499 | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.krad.uif.service;
import org.kuali.rice.krad.data.metadata.DataObjectAttribute;
import org.kuali.rice.krad.data.metadata.DataObjectMetadata;
import org.kuali.rice.krad.datadictionary.AttributeDefinition;
import org.kuali.rice.krad.datadictionary.DataObjectEntry;
import org.kuali.rice.krad.datadictionary.validation.constraint.ValidCharactersConstraint;
import org.kuali.rice.krad.lookup.LookupView;
import org.kuali.rice.krad.uif.control.Control;
import org.kuali.rice.krad.uif.view.InquiryView;
/**
* This service helps build/define default controls for the UIF based on the associated data-level metadata.
*
* It will use the information provided by the krad-data module to attempt to build sensible
* default controls based on the data type, maximum length, and other attributes available
* in the ORM-level metadata or provided as annotations on the data object classes.
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public interface UifDefaultingService {
/**
* Derives a UIF control from the information available on the passed in Data Dictionary {@link AttributeDefinition}.
*
* Attempts to build reasonable defaults based on the data type and other metadata which has
* been included.
*
* If no special information is found in the metadata, it will return a standard/default text control.
* @param attrDef attribute definition
* @return derived control
*/
Control deriveControlAttributeFromMetadata( AttributeDefinition attrDef );
/**
* Helper method to allow reasonable names to be defaulted from class or property names.
*
* This method assumes that the passed in name is camel-cased and will create the
* name by adding spaces before each capital letter or digit as well as capitalizing each word.
*
* In the case that the name given is a nested property, only the portion of the
* name after the last period will be used.
* @param camelCasedName property name, in camel case
* @return human friendly property name
*/
String deriveHumanFriendlyNameFromPropertyName(String camelCasedName);
/**
* Derives a default valid characters constraint definition given the metadata in the {@link AttributeDefinition}
* @param attrDef attribute definition
*
* @return A {@link ValidCharactersConstraint} object or null if no information in the {@link AttributeDefinition} suggests an appropriate default.
*/
ValidCharactersConstraint deriveValidCharactersConstraint( AttributeDefinition attrDef );
/**
* Build an instance of an {@link InquiryView} for the given data object entry.
* Information will be pulled from the {@link DataObjectEntry} and the embedded
* {@link DataObjectMetadata} and {@link DataObjectAttribute} instances as needed.
*
* In the present implementation, all non-hidden properties on the DataObjectEntry
* will be added to the inquiry. Additionally, any collections on the object will be
* displayed in their own sections.
* @param dataObjectEntry data object entry
* @return inquiry view based on the data object
*/
InquiryView deriveInquiryViewFromMetadata( DataObjectEntry dataObjectEntry );
/**
* Build an instance of an {@link LookupView} for the given data object entry.
* Information will be pulled from the {@link DataObjectEntry} and the embedded
* {@link DataObjectMetadata} and {@link DataObjectAttribute} instances as needed.
*
* In the present implementation, all non-hidden properties on the DataObjectEntry
* will be added to the lookup search criteria and results.
* @param dataObjectEntry data object entry
* @return lookup view based on the data object
*/
LookupView deriveLookupViewFromMetadata( DataObjectEntry dataObjectEntry );
}
| apache-2.0 |
jumpbytehq/cordova-plugin-geofence | src/android/RemoveGeofenceCommand.java | 1671 | package com.cowbell.cordova.geofence;
import java.util.List;
import android.app.PendingIntent;
import android.content.Context;
import android.util.Log;
import com.google.android.gms.location.LocationClient.OnRemoveGeofencesResultListener;
public class RemoveGeofenceCommand extends AbstractGoogleServiceCommand
implements OnRemoveGeofencesResultListener {
private PendingIntent pendingIntent;
private List<String> geofencesIds;
public RemoveGeofenceCommand(Context context, PendingIntent pendingIntent) {
super(context);
this.pendingIntent = pendingIntent;
}
public RemoveGeofenceCommand(Context context, List<String> geofencesIds) {
super(context);
this.geofencesIds = geofencesIds;
}
@Override
public void onRemoveGeofencesByPendingIntentResult(int arg0,
PendingIntent arg1) {
logger.log(Log.DEBUG, "All Geofences removed");
CommandExecuted();
}
@Override
public void onRemoveGeofencesByRequestIdsResult(int arg0, String[] arg1) {
logger.log(Log.DEBUG, "Geofences removed");
CommandExecuted();
}
@Override
protected void ExecuteCustomCode() {
if (pendingIntent != null) {
locationClient.removeGeofences(pendingIntent, this);
//for some reason an exception is thrown when clearing an empty set of geofences
} else if (geofencesIds != null && geofencesIds.size() > 0) {
locationClient.removeGeofences(geofencesIds, this);
} else {
logger.log(Log.DEBUG, "Tried to remove Geofences when there were none");
CommandExecuted();
}
}
}
| apache-2.0 |
mikekap/buck | src/com/facebook/buck/rules/BuildRuleParams.java | 5541 | /*
* Copyright 2012-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.rules;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.Flavor;
import com.google.common.annotations.Beta;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Sets;
import java.nio.file.Path;
import java.util.Set;
/**
* Standard set of parameters that is passed to all build rules.
*/
@Beta
public class BuildRuleParams {
private final BuildTarget buildTarget;
private final Supplier<ImmutableSortedSet<BuildRule>> declaredDeps;
private final Supplier<ImmutableSortedSet<BuildRule>> extraDeps;
private final Supplier<ImmutableSortedSet<BuildRule>> totalDeps;
private final ProjectFilesystem projectFilesystem;
private final Function<Optional<String>, Path> cellRoots;
public BuildRuleParams(
BuildTarget buildTarget,
final Supplier<ImmutableSortedSet<BuildRule>> declaredDeps,
final Supplier<ImmutableSortedSet<BuildRule>> extraDeps,
ProjectFilesystem projectFilesystem,
Function<Optional<String>, Path> cellRoots) {
this.buildTarget = buildTarget;
this.declaredDeps = Suppliers.memoize(declaredDeps);
this.extraDeps = Suppliers.memoize(extraDeps);
this.projectFilesystem = projectFilesystem;
this.cellRoots = cellRoots;
this.totalDeps = Suppliers.memoize(
new Supplier<ImmutableSortedSet<BuildRule>>() {
@Override
public ImmutableSortedSet<BuildRule> get() {
return ImmutableSortedSet.<BuildRule>naturalOrder()
.addAll(declaredDeps.get())
.addAll(extraDeps.get())
.build();
}
});
}
public BuildRuleParams copyWithExtraDeps(Supplier<ImmutableSortedSet<BuildRule>> extraDeps) {
return copyWithDeps(declaredDeps, extraDeps);
}
public BuildRuleParams appendExtraDeps(
final Supplier<? extends Iterable<? extends BuildRule>> additional) {
return copyWithDeps(
declaredDeps,
new Supplier<ImmutableSortedSet<BuildRule>>() {
@Override
public ImmutableSortedSet<BuildRule> get() {
return ImmutableSortedSet.<BuildRule>naturalOrder()
.addAll(extraDeps.get())
.addAll(additional.get())
.build();
}
});
}
public BuildRuleParams appendExtraDeps(Iterable<? extends BuildRule> additional) {
return appendExtraDeps(Suppliers.ofInstance(additional));
}
public BuildRuleParams copyWithDeps(
Supplier<ImmutableSortedSet<BuildRule>> declaredDeps,
Supplier<ImmutableSortedSet<BuildRule>> extraDeps) {
return copyWithChanges(buildTarget, declaredDeps, extraDeps);
}
public BuildRuleParams copyWithBuildTarget(BuildTarget target) {
return copyWithChanges(target, declaredDeps, extraDeps);
}
public BuildRuleParams copyWithChanges(
BuildTarget buildTarget,
Supplier<ImmutableSortedSet<BuildRule>> declaredDeps,
Supplier<ImmutableSortedSet<BuildRule>> extraDeps) {
return new BuildRuleParams(
buildTarget,
declaredDeps,
extraDeps,
projectFilesystem,
cellRoots);
}
public BuildRuleParams withoutFlavor(Flavor flavor) {
Set<Flavor> flavors = Sets.newHashSet(getBuildTarget().getFlavors());
Preconditions.checkArgument(flavors.contains(flavor));
flavors.remove(flavor);
BuildTarget target = BuildTarget
.builder(getBuildTarget().getUnflavoredBuildTarget())
.addAllFlavors(flavors)
.build();
return copyWithChanges(
target,
declaredDeps,
extraDeps);
}
public BuildRuleParams withFlavor(Flavor flavor) {
Set<Flavor> flavors = Sets.newHashSet(getBuildTarget().getFlavors());
Preconditions.checkArgument(!flavors.contains(flavor));
flavors.add(flavor);
BuildTarget target = BuildTarget
.builder(getBuildTarget().getUnflavoredBuildTarget())
.addAllFlavors(flavors)
.build();
return copyWithChanges(
target,
declaredDeps,
extraDeps);
}
public BuildTarget getBuildTarget() {
return buildTarget;
}
public Function<Optional<String>, Path> getCellRoots() {
return cellRoots;
}
public ImmutableSortedSet<BuildRule> getDeps() {
return totalDeps.get();
}
public Supplier<ImmutableSortedSet<BuildRule>> getTotalDeps() {
return totalDeps;
}
public Supplier<ImmutableSortedSet<BuildRule>> getDeclaredDeps() {
return declaredDeps;
}
public Supplier<ImmutableSortedSet<BuildRule>> getExtraDeps() {
return extraDeps;
}
public ProjectFilesystem getProjectFilesystem() {
return projectFilesystem;
}
}
| apache-2.0 |
Niksok/Prebid.js | modules/operaadsBidAdapter.js | 20945 | import { logWarn, isArray, isStr, triggerPixel, deepAccess, deepSetValue, isPlainObject, generateUUID, parseUrl, isFn, getDNT, logError } from '../src/utils.js';
import { registerBidder } from '../src/adapters/bidderFactory.js';
import { config } from '../src/config.js';
import { BANNER, VIDEO, NATIVE } from '../src/mediaTypes.js';
import { Renderer } from '../src/Renderer.js';
import { OUTSTREAM } from '../src/video.js';
const BIDDER_CODE = 'operaads';
const ENDPOINT = 'https://s.adx.opera.com/ortb/v2/';
const USER_SYNC_ENDPOINT = 'https://s.adx.opera.com/usersync/page';
const OUTSTREAM_RENDERER_URL = 'https://acdn.adnxs.com/video/outstream/ANOutstreamVideo.js';
const DEFAULT_CURRENCY = 'USD';
const DEFAULT_LANGUAGE = 'en';
const NET_REVENUE = true;
const BANNER_DEFAULTS = {
SIZE: [300, 250]
}
const VIDEO_DEFAULTS = {
PROTOCOLS: [2, 3, 5, 6],
MIMES: ['video/mp4'],
PLAYBACK_METHODS: [1, 2, 3, 4],
DELIVERY: [1],
API: [1, 2, 5],
SIZE: [640, 480]
}
const NATIVE_DEFAULTS = {
IMAGE_TYPE: {
ICON: 1,
MAIN: 3,
},
ASSET_ID: {
TITLE: 1,
IMAGE: 2,
ICON: 3,
BODY: 4,
SPONSORED: 5,
CTA: 6
},
DATA_ASSET_TYPE: {
SPONSORED: 1,
DESC: 2,
CTA_TEXT: 12,
},
LENGTH: {
TITLE: 90,
BODY: 140,
SPONSORED: 25,
CTA: 20
}
}
export const spec = {
code: BIDDER_CODE,
// short code
aliases: ['opera'],
supportedMediaTypes: [BANNER, VIDEO, NATIVE],
/**
* Determines whether or not the given bid request is valid.
*
* @param {BidRequest} bid
* @returns boolean True if this is a valid bid, and false otherwise.
*/
isBidRequestValid: function (bid) {
if (!bid) {
logWarn(BIDDER_CODE, 'Invalid bid,', bid);
return false;
}
if (!bid.params) {
logWarn(BIDDER_CODE, 'bid.params is required.')
return false;
}
if (!bid.params.placementId) {
logWarn(BIDDER_CODE, 'bid.params.placementId is required.')
return false;
}
if (!bid.params.endpointId) {
logWarn(BIDDER_CODE, 'bid.params.endpointId is required.')
return false;
}
if (!bid.params.publisherId) {
logWarn(BIDDER_CODE, 'bid.params.publisherId is required.')
return false;
}
return true;
},
/**
* Make a server request from the list of BidRequests.
*
* @param {validBidRequests[]} validBidRequests An array of bidRequest objects
* @param {bidderRequest} bidderRequest The master bidRequest object.
* @return ServerRequest Info describing the request to the server.
*/
buildRequests: function (validBidRequests, bidderRequest) {
return validBidRequests.map(validBidRequest => (buildOpenRtbBidRequest(validBidRequest, bidderRequest)))
},
/**
* Unpack the response from the server into a list of bids.
*
* @param {ServerResponse} serverResponse A successful response from the server.
* @return {Bid[]} An array of bids which were nested inside the server.
*/
interpretResponse: function (serverResponse, bidRequest) {
let bidResponses = [];
let serverBody;
if ((serverBody = serverResponse.body) && serverBody.seatbid && isArray(serverBody.seatbid)) {
serverBody.seatbid.forEach((seatbidder) => {
if (seatbidder.bid && isArray(seatbidder.bid)) {
bidResponses = seatbidder.bid.map((bid) => buildBidResponse(bid, bidRequest.originalBidRequest, serverBody));
}
});
}
return bidResponses;
},
/**
* Register the user sync pixels which should be dropped after the auction.
*
* @param {SyncOptions} syncOptions Which user syncs are allowed?
* @param {ServerResponse[]} serverResponses List of server's responses.
* @return {UserSync[]} The user syncs which should be dropped.
*/
getUserSyncs: function (syncOptions, serverResponses, gdprConsent, uspConsent) {
if ('iframeEnabled' in syncOptions && syncOptions.iframeEnabled) {
return [{
type: 'iframe',
url: USER_SYNC_ENDPOINT
}];
}
if ('pixelEnabled' in syncOptions && syncOptions.pixelEnabled) {
const pixels = deepAccess(serverResponses, '0.body.pixels')
if (Array.isArray(pixels)) {
const userSyncPixels = []
for (const pixel of pixels) {
userSyncPixels.push({
type: 'image',
url: pixel
})
}
return userSyncPixels;
}
}
return [];
},
/**
* Register bidder specific code, which will execute if bidder timed out after an auction
*
* @param {data} timeoutData Containing timeout specific data
*/
onTimeout: function (timeoutData) { },
/**
* Register bidder specific code, which will execute if a bid from this bidder won the auction
*
* @param {Bid} bid The bid that won the auction
*/
onBidWon: function (bid) {
if (!bid || !isStr(bid.nurl)) {
return;
}
let winCpm, winCurr;
if (Object.prototype.hasOwnProperty.call(bid, 'originalCpm')) {
winCpm = bid.originalCpm;
winCurr = bid.originalCurrency;
} else {
winCpm = bid.cpm;
winCurr = bid.currency;
}
triggerPixel(
bid.nurl
.replace(/\$\{AUCTION_PRICE\}/g, winCpm)
.replace(/\$\{AUCTION_CURRENCY\}/g, winCurr)
);
},
/**
* Register bidder specific code, which will execute when the adserver targeting has been set for a bid from this bidder
*
* @param {Bid} bid The bid of which the targeting has been set
*/
onSetTargeting: function (bid) { }
}
/**
* Buid openRtb request from bidRequest and bidderRequest
*
* @param {BidRequest} bidRequest
* @param {BidderRequest} bidderRequest
* @returns {Request}
*/
function buildOpenRtbBidRequest(bidRequest, bidderRequest) {
const pageReferrer = deepAccess(bidderRequest, 'refererInfo.referer');
// build OpenRTB request body
const payload = {
id: bidderRequest.auctionId,
tmax: bidderRequest.timeout || config.getConfig('bidderTimeout'),
test: config.getConfig('debug') ? 1 : 0,
imp: createImp(bidRequest),
device: getDevice(),
site: {
id: String(deepAccess(bidRequest, 'params.publisherId')),
domain: getDomain(pageReferrer),
page: pageReferrer,
ref: window.self === window.top ? document.referrer : '',
},
at: 1,
bcat: getBcat(bidRequest),
cur: [DEFAULT_CURRENCY],
regs: {
coppa: config.getConfig('coppa') ? 1 : 0,
ext: {}
},
user: {
buyeruid: getUserId(bidRequest)
}
}
const gdprConsent = deepAccess(bidderRequest, 'gdprConsent');
if (!!gdprConsent && gdprConsent.gdprApplies) {
deepSetValue(payload, 'regs.ext.gdpr', 1);
deepSetValue(payload, 'user.ext.consent', gdprConsent.consentString);
}
const uspConsent = deepAccess(bidderRequest, 'uspConsent');
if (uspConsent) {
deepSetValue(payload, 'regs.ext.us_privacy', uspConsent);
}
const eids = deepAccess(bidRequest, 'userIdAsEids', []);
if (eids.length > 0) {
deepSetValue(payload, 'user.eids', eids);
}
return {
method: 'POST',
url: ENDPOINT + String(deepAccess(bidRequest, 'params.publisherId')) +
'?ep=' + String(deepAccess(bidRequest, 'params.endpointId')),
data: JSON.stringify(payload),
options: {
contentType: 'application/json',
customHeaders: {
'x-openrtb-version': 2.5
}
},
// set original bid request, so we can get it from interpretResponse
originalBidRequest: bidRequest
}
}
/**
* Build bid response from openrtb bid response.
*
* @param {OpenRtbBid} bid
* @param {BidRequest} bidRequest
* @param {OpenRtbResponseBody} responseBody
* @returns {BidResponse}
*/
function buildBidResponse(bid, bidRequest, responseBody) {
let mediaType = BANNER;
let nativeResponse;
if (/VAST\s+version/.test(bid.adm)) {
mediaType = VIDEO;
} else {
let markup;
try {
markup = JSON.parse(bid.adm);
} catch (e) {
markup = null;
}
// OpenRtb Markup Response Object
// https://www.iab.com/wp-content/uploads/2016/03/OpenRTB-Native-Ads-Specification-1-1_2016.pdf#5.1
if (markup && isPlainObject(markup.native)) {
mediaType = NATIVE;
nativeResponse = markup.native;
}
}
const currency = responseBody.cur || DEFAULT_CURRENCY;
const cpm = (parseFloat(bid.price) || 0).toFixed(2);
const categories = deepAccess(bid, 'cat', []);
const bidResponse = {
requestId: bid.impid,
cpm: cpm,
currency: currency,
mediaType: mediaType,
ttl: 300,
creativeId: bid.crid || bid.id,
netRevenue: NET_REVENUE,
nurl: bid.nurl,
lurl: bid.lurl,
meta: {
mediaType: mediaType,
primaryCatId: categories[0],
secondaryCatIds: categories.slice(1),
}
};
if (bid.adomain && isArray(bid.adomain) && bid.adomain.length > 0) {
bidResponse.meta.advertiserDomains = bid.adomain;
bidResponse.meta.clickUrl = bid.adomain[0];
}
switch (mediaType) {
case VIDEO: {
const playerSize = deepAccess(bidRequest, 'mediaTypes.video.playerSize', VIDEO_DEFAULTS.SIZE);
const size = canonicalizeSizesArray(playerSize)[0];
bidResponse.vastXml = bid.adm;
bidResponse.width = bid.w || size[0];
bidResponse.height = bid.h || size[1];
const context = deepAccess(bidRequest, 'mediaTypes.video.context');
// if outstream video, add a default render for it.
if (context === OUTSTREAM) {
// fill adResponse, will be used in ANOutstreamVideo.renderAd
bidResponse.adResponse = {
content: bidResponse.vastXml,
width: bidResponse.width,
height: bidResponse.height,
player_width: size[0],
player_height: size[1],
};
bidResponse.renderer = createRenderer(bidRequest);
}
break;
}
case NATIVE: {
bidResponse.native = interpretNativeAd(nativeResponse, currency, cpm);
break;
}
default: {
bidResponse.ad = bid.adm;
bidResponse.width = bid.w;
bidResponse.height = bid.h;
}
}
return bidResponse;
}
/**
* Convert OpenRtb native response to bid native object.
*
* @param {OpenRtbNativeResponse} nativeResponse
* @param {String} currency
* @param {String} cpm
* @returns {BidNative} native
*/
function interpretNativeAd(nativeResponse, currency, cpm) {
const native = {};
// OpenRtb Link Object
// https://www.iab.com/wp-content/uploads/2016/03/OpenRTB-Native-Ads-Specification-1-1_2016.pdf#5.7
const clickUrl = deepAccess(nativeResponse, 'link.url');
if (clickUrl && isStr(clickUrl)) {
native.clickUrl = decodeURIComponent(clickUrl);
}
const clickTrackers = deepAccess(nativeResponse, 'link.clicktrackers');
if (clickTrackers && isArray(clickTrackers)) {
native.clickTrackers = clickTrackers
.filter(Boolean)
.map(
url => decodeURIComponent(url)
.replace(/\$\{AUCTION_PRICE\}/g, cpm)
.replace(/\$\{AUCTION_CURRENCY\}/g, currency)
);
}
if (nativeResponse.imptrackers && isArray(nativeResponse.imptrackers)) {
native.impressionTrackers = nativeResponse.imptrackers
.filter(Boolean)
.map(
url => decodeURIComponent(url)
.replace(/\$\{AUCTION_PRICE\}/g, cpm)
.replace(/\$\{AUCTION_CURRENCY\}/g, currency)
);
}
if (nativeResponse.jstracker && isStr(nativeResponse.jstracker)) {
native.javascriptTrackers = [nativeResponse.jstracker];
}
let assets;
if ((assets = nativeResponse.assets) && isArray(assets)) {
assets.forEach((asset) => {
switch (asset.id) {
case NATIVE_DEFAULTS.ASSET_ID.TITLE: {
const title = deepAccess(asset, 'title.text');
if (title) {
native.title = title;
}
break;
}
case NATIVE_DEFAULTS.ASSET_ID.IMAGE: {
if (asset.img) {
native.image = {
url: decodeURIComponent(asset.img.url),
width: asset.img.w,
height: asset.img.h
}
}
break;
}
case NATIVE_DEFAULTS.ASSET_ID.ICON: {
if (asset.img) {
native.icon = {
url: decodeURIComponent(asset.img.url),
width: asset.img.w,
height: asset.img.h
}
}
break;
}
case NATIVE_DEFAULTS.ASSET_ID.BODY: {
const body = deepAccess(asset, 'data.value');
if (body) {
native.body = body;
}
break;
}
case NATIVE_DEFAULTS.ASSET_ID.SPONSORED: {
const sponsoredBy = deepAccess(asset, 'data.value');
if (sponsoredBy) {
native.sponsoredBy = sponsoredBy;
}
break;
}
case NATIVE_DEFAULTS.ASSET_ID.CTA: {
const cta = deepAccess(asset, 'data.value');
if (cta) {
native.cta = cta;
}
break;
}
}
});
}
return native;
}
/**
* Create an imp array
*
* @param {BidRequest} bidRequest
* @param {Currency} cur
* @returns {Imp[]}
*/
function createImp(bidRequest) {
const imp = [];
const impItem = {
id: bidRequest.bidId,
tagid: String(deepAccess(bidRequest, 'params.placementId')),
};
let mediaType, size;
let bannerReq, videoReq, nativeReq;
if ((bannerReq = deepAccess(bidRequest, 'mediaTypes.banner'))) {
size = canonicalizeSizesArray(bannerReq.sizes || BANNER_DEFAULTS.SIZE)[0];
impItem.banner = {
w: size[0],
h: size[1],
pos: 0,
};
mediaType = BANNER;
} else if ((videoReq = deepAccess(bidRequest, 'mediaTypes.video'))) {
size = canonicalizeSizesArray(videoReq.playerSize || VIDEO_DEFAULTS.SIZE)[0];
impItem.video = {
w: size[0],
h: size[1],
pos: 0,
mimes: videoReq.mimes || VIDEO_DEFAULTS.MIMES,
protocols: videoReq.protocols || VIDEO_DEFAULTS.PROTOCOLS,
startdelay: typeof videoReq.startdelay === 'number' ? videoReq.startdelay : 0,
skip: typeof videoReq.skip === 'number' ? videoReq.skip : 0,
playbackmethod: videoReq.playbackmethod || VIDEO_DEFAULTS.PLAYBACK_METHODS,
delivery: videoReq.delivery || VIDEO_DEFAULTS.DELIVERY,
api: videoReq.api || VIDEO_DEFAULTS.API,
placement: videoReq.context === OUTSTREAM ? 3 : 1,
};
mediaType = VIDEO;
} else if ((nativeReq = deepAccess(bidRequest, 'mediaTypes.native'))) {
const params = bidRequest.nativeParams || nativeReq;
const request = {
native: {
ver: '1.1',
assets: createNativeAssets(params),
}
};
impItem.native = {
ver: '1.1',
request: JSON.stringify(request),
};
mediaType = NATIVE;
}
const floorDetail = getBidFloor(bidRequest, {
mediaType: mediaType || '*',
size: size || '*'
})
impItem.bidfloor = floorDetail.floor;
impItem.bidfloorcur = floorDetail.currency;
if (mediaType) {
imp.push(impItem);
}
return imp;
}
/**
* Convert bid sizes to size array
*
* @param {Size[]|Size[][]} sizes
* @returns {Size[][]}
*/
function canonicalizeSizesArray(sizes) {
if (sizes.length === 2 && !isArray(sizes[0])) {
return [sizes];
}
return sizes;
}
/**
* Create Assets Object for Native request
*
* @param {Object} params
* @returns {Asset[]}
*/
function createNativeAssets(params) {
const assets = [];
if (params.title) {
assets.push({
id: NATIVE_DEFAULTS.ASSET_ID.TITLE,
required: params.title.required ? 1 : 0,
title: {
len: params.title.len || NATIVE_DEFAULTS.LENGTH.TITLE
}
})
}
if (params.image) {
assets.push({
id: NATIVE_DEFAULTS.ASSET_ID.IMAGE,
required: params.image.required ? 1 : 0,
img: mapNativeImage(params.image, NATIVE_DEFAULTS.IMAGE_TYPE.MAIN)
})
}
if (params.icon) {
assets.push({
id: NATIVE_DEFAULTS.ASSET_ID.ICON,
required: params.icon.required ? 1 : 0,
img: mapNativeImage(params.icon, NATIVE_DEFAULTS.IMAGE_TYPE.ICON)
})
}
if (params.sponsoredBy) {
assets.push({
id: NATIVE_DEFAULTS.ASSET_ID.SPONSORED,
required: params.sponsoredBy.required ? 1 : 0,
data: {
type: NATIVE_DEFAULTS.DATA_ASSET_TYPE.SPONSORED,
len: params.sponsoredBy.len | NATIVE_DEFAULTS.LENGTH.SPONSORED
}
})
}
if (params.body) {
assets.push({
id: NATIVE_DEFAULTS.ASSET_ID.BODY,
required: params.body.required ? 1 : 0,
data: {
type: NATIVE_DEFAULTS.DATA_ASSET_TYPE.DESC,
len: params.body.len || NATIVE_DEFAULTS.LENGTH.BODY
}
})
}
if (params.cta) {
assets.push({
id: NATIVE_DEFAULTS.ASSET_ID.CTA,
required: params.cta.required ? 1 : 0,
data: {
type: NATIVE_DEFAULTS.DATA_ASSET_TYPE.CTA_TEXT,
len: params.cta.len || NATIVE_DEFAULTS.LENGTH.CTA
}
})
}
return assets;
}
/**
* Create native image object
*
* @param {Object} image
* @param {Number} type
* @returns {NativeImage}
*/
function mapNativeImage(image, type) {
const img = { type: type };
if (image.aspect_ratios) {
const ratio = image.aspect_ratios[0];
const minWidth = ratio.min_width || 100;
img.wmin = minWidth;
img.hmin = (minWidth / ratio.ratio_width * ratio.ratio_height);
}
if (image.sizes) {
const size = canonicalizeSizesArray(image.sizes)[0];
img.w = size[0];
img.h = size[1];
}
return img;
}
/**
* Get user id from bid request. if no user id module used, return a new uuid.
*
* @param {BidRequest} bidRequest
* @returns {String} userId
*/
function getUserId(bidRequest) {
let sharedId = deepAccess(bidRequest, 'userId.sharedid.id');
if (sharedId) {
return sharedId;
}
for (const idModule of ['pubcid', 'tdid']) {
let userId = deepAccess(bidRequest, `userId.${idModule}`);
if (userId) {
return userId;
}
}
return generateUUID();
}
/**
* Get publisher domain
*
* @param {String} referer
* @returns {String} domain
*/
function getDomain(referer) {
let domain;
if (!(domain = config.getConfig('publisherDomain'))) {
const u = parseUrl(referer);
domain = u.hostname;
}
return domain.replace(/^https?:\/\/([\w\-\.]+)(?::\d+)?/, '$1');
}
/**
* Get bid floor price
*
* @param {BidRequest} bid
* @param {Params} params
* @returns {Floor} floor price
*/
function getBidFloor(bid, {mediaType = '*', size = '*'}) {
if (isFn(bid.getFloor)) {
const floorInfo = bid.getFloor({
currency: DEFAULT_CURRENCY,
mediaType,
size
});
if (isPlainObject(floorInfo) && !isNaN(floorInfo.floor)) {
return {
currency: floorInfo.currency || DEFAULT_CURRENCY,
floor: floorInfo.floor
};
}
}
return {
currency: DEFAULT_CURRENCY,
floor: 0.0
}
}
/**
* Get bcat
*
* @param {BidRequest} bidRequest
* @returns {String[]}
*/
function getBcat(bidRequest) {
let bcat = [];
const pBcat = deepAccess(bidRequest, 'params.bcat');
if (pBcat) {
bcat = bcat.concat(pBcat);
}
return bcat;
}
/**
* Get device info
*
* @returns {Object}
*/
function getDevice() {
const device = config.getConfig('device') || {};
device.w = device.w || window.screen.width;
device.h = device.h || window.screen.height;
device.ua = device.ua || navigator.userAgent;
device.language = device.language || getLanguage();
device.dnt = typeof device.dnt === 'number'
? device.dnt : (getDNT() ? 1 : 0);
return device;
}
/**
* Get browser language
*
* @returns {String} language
*/
function getLanguage() {
const lang = (navigator.languages && navigator.languages[0]) ||
navigator.language || navigator.userLanguage;
return lang ? lang.split('-')[0] : DEFAULT_LANGUAGE;
}
/**
* Create render for outstream video.
*
* @param {BidRequest} bidRequest
* @returns
*/
function createRenderer(bidRequest) {
const globalRenderer = deepAccess(bidRequest, 'renderer');
const currentRenderer = deepAccess(bidRequest, 'mediaTypes.video.renderer');
let url = OUTSTREAM_RENDERER_URL;
let config = {};
let render = function (bid) {
bid.renderer.push(() => {
window.ANOutstreamVideo.renderAd({
sizes: [bid.width, bid.height],
targetId: bid.adUnitCode,
adResponse: bid.adResponse,
});
});
};
if (currentRenderer) {
url = currentRenderer.url;
config = currentRenderer.options;
render = currentRenderer.render;
} else if (globalRenderer) {
url = globalRenderer.url;
config = globalRenderer.options;
render = globalRenderer.render;
}
const renderer = Renderer.install({
id: bidRequest.bidId,
url: url,
loaded: false,
config: config,
adUnitCode: bidRequest.adUnitCode
});
try {
renderer.setRender(render);
} catch (e) {
logError(BIDDER_CODE, 'Error calling setRender on renderer', e);
}
return renderer;
}
registerBidder(spec);
| apache-2.0 |
scorelab/DroneMap | tracker/server.js | 1233 |
/**
* Module dependencies.
*
* Routs
* Views
* index
* API
* tracker
* -locations
* -location
*
*/
var express = require('express'),
http = require('http'),
path = require('path'),
engine = require('ejs-locals');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
// use ejs-locals for all ejs templates:
app.engine('ejs', engine);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
return next();
});
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
require('./db');
var controllers = require('./controllers'),
tracker = require('./controllers/tracker');
app.configure('development', function(){
app.use(express.errorHandler());
});
//Routes
require('./routes')(app);
//===============================
//Start server
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
| apache-2.0 |
leoleegit/cipango | cipango-diameter/src/main/java/org/cipango/diameter/node/DiameterConnector.java | 1349 | // ========================================================================
// Copyright 2008-2009 NEXCOM Systems
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
package org.cipango.diameter.node;
import java.io.IOException;
import java.net.InetAddress;
import org.eclipse.jetty.util.component.LifeCycle;
public interface DiameterConnector extends LifeCycle
{
void setNode(Node node);
Object getTransport();
void open() throws IOException;
void close() throws IOException;
DiameterConnection getConnection(Peer peer) throws IOException;
void setHost(String host);
String getHost();
void setPort(int port);
int getPort();
int getLocalPort();
InetAddress getLocalAddress();
}
| apache-2.0 |
alexeagle/TypeScript | tests/baselines/reference/invalidSyntaxNamespaceImportWithCommonjs.js | 453 | //// [tests/cases/conformance/externalModules/invalidSyntaxNamespaceImportWithCommonjs.ts] ////
//// [0.ts]
export class C { }
//// [1.ts]
import * from Zero from "./0"
//// [0.js]
"use strict";
exports.__esModule = true;
exports.C = void 0;
var C = /** @class */ (function () {
function C() {
}
return C;
}());
exports.C = C;
//// [1.js]
"use strict";
exports.__esModule = true;
var from = require();
from;
"./0";
| apache-2.0 |
coughman/incubator-parquet-mr | parquet-thrift/src/main/java/org/apache/parquet/thrift/ThriftMetaData.java | 5087 | /*
* 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.parquet.thrift;
import java.util.*;
import org.apache.parquet.Log;
import org.apache.parquet.hadoop.BadConfigurationException;
import org.apache.parquet.thrift.struct.ThriftType;
import org.apache.parquet.thrift.struct.ThriftType.StructType;
import org.apache.thrift.TBase;
/**
*
* Metadata for thrift stored in the file footer
*
* @author Julien Le Dem
*
*/
public class ThriftMetaData {
private static final Log LOG = Log.getLog(ThriftMetaData.class);
private static final String THRIFT_CLASS = "thrift.class";
private static final String THRIFT_DESCRIPTOR = "thrift.descriptor";
private Class<?> thriftClass;
private final String thriftClassName;
private final StructType descriptor;
/**
* @param thriftClassName the class used to serialize
* @param descriptor the json representation of the thrift structure
*/
public ThriftMetaData(String thriftClassName, StructType descriptor) {
this.thriftClassName = thriftClassName;
this.descriptor = descriptor;
}
/**
* Get the Thrift Class encoded in the metadata.
* @return Thrift Class encoded in the metadata.
* @throws BadConfigurationException if the encoded class does not
* extend TBase or is not available in the current classloader.
*/
public Class<?> getThriftClass() {
if (thriftClass == null) {
thriftClass = getThriftClass(thriftClassName);
}
return thriftClass;
}
/**
* @param thriftClassName the name of the thrift class
* @return the class
*/
public static Class<?> getThriftClass(String thriftClassName) {
try {
Class<?> thriftClass = Class.forName(thriftClassName);
return thriftClass;
} catch (ClassNotFoundException e) {
throw new BadConfigurationException("Could not instantiate thrift class " + thriftClassName, e);
}
}
/**
* @return the thrift descriptor
*/
public StructType getDescriptor() {
return descriptor;
}
/**
* Reads ThriftMetadata from the parquet file footer.
*
* @param extraMetaData extraMetaData field of the parquet footer
* @return the ThriftMetaData used to write a data file
*/
public static ThriftMetaData fromExtraMetaData(
Map<String, String> extraMetaData) {
final String thriftClassName = extraMetaData.get(THRIFT_CLASS);
final String thriftDescriptorString = extraMetaData.get(THRIFT_DESCRIPTOR);
if (thriftClassName == null || thriftDescriptorString == null) {
return null;
}
final StructType descriptor = parseDescriptor(thriftDescriptorString);
return new ThriftMetaData(thriftClassName, descriptor);
}
/**
* Creates ThriftMetaData from a Thrift-generated class.
*
* @param thriftClass a Thrift-generated class
* @return ThriftMetaData for the given class
*/
@SuppressWarnings("unchecked")
public static ThriftMetaData fromThriftClass(Class<?> thriftClass) {
if (thriftClass != null && TBase.class.isAssignableFrom(thriftClass)) {
Class<? extends TBase<?, ?>> tClass = (Class<? extends TBase<?, ?>>) thriftClass;
StructType descriptor = new ThriftSchemaConverter().toStructType(tClass);
return new ThriftMetaData(thriftClass.getName(), descriptor);
}
return null;
}
private static StructType parseDescriptor(String json) {
try {
return (StructType)ThriftType.fromJSON(json);
} catch (RuntimeException e) {
throw new BadConfigurationException("Could not read the thrift descriptor " + json, e);
}
}
/**
* generates a map of key values to store in the footer
* @return the key values
*/
public Map<String, String> toExtraMetaData() {
final Map<String, String> map = new HashMap<String, String>();
map.put(THRIFT_CLASS, getThriftClass().getName());
map.put(THRIFT_DESCRIPTOR, descriptor.toJSON());
return map;
}
/**
* @param fileMetadata the merged metadata from ultiple files
* @return the list of thrift classes used to write them
*/
public static Set<String> getThriftClassNames(Map<String, Set<String>> fileMetadata) {
return fileMetadata.get(THRIFT_CLASS);
}
@Override
public String toString() {
return String.format("ThriftMetaData(thriftClassName: %s, descriptor: %s)", thriftClassName, descriptor);
}
}
| apache-2.0 |
sassson/TypeScript | src/server/editorServices.ts | 86677 | /// <reference path="..\compiler\commandLineParser.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="protocol.d.ts" />
/// <reference path="session.ts" />
namespace ts.server {
export interface Logger {
close(): void;
isVerbose(): boolean;
loggingEnabled(): boolean;
perftrc(s: string): void;
info(s: string): void;
startGroup(): void;
endGroup(): void;
msg(s: string, type?: string): void;
}
var lineCollectionCapacity = 4;
function mergeFormatOptions(formatCodeOptions: FormatCodeOptions, formatOptions: protocol.FormatOptions): void {
var hasOwnProperty = Object.prototype.hasOwnProperty;
Object.keys(formatOptions).forEach((key) => {
var codeKey = key.charAt(0).toUpperCase() + key.substring(1);
if (hasOwnProperty.call(formatCodeOptions, codeKey)) {
formatCodeOptions[codeKey] = formatOptions[key];
}
});
}
export class ScriptInfo {
svc: ScriptVersionCache;
children: ScriptInfo[] = []; // files referenced by this file
defaultProject: Project; // project to use by default for file
fileWatcher: FileWatcher;
formatCodeOptions = ts.clone(CompilerService.defaultFormatCodeOptions);
constructor(private host: ServerHost, public fileName: string, public content: string, public isOpen = false) {
this.svc = ScriptVersionCache.fromString(host, content);
}
setFormatOptions(formatOptions: protocol.FormatOptions): void {
if (formatOptions) {
mergeFormatOptions(this.formatCodeOptions, formatOptions);
}
}
close() {
this.isOpen = false;
}
addChild(childInfo: ScriptInfo) {
this.children.push(childInfo);
}
snap() {
return this.svc.getSnapshot();
}
getText() {
var snap = this.snap();
return snap.getText(0, snap.getLength());
}
getLineInfo(line: number) {
var snap = this.snap();
return snap.index.lineNumberToInfo(line);
}
editContent(start: number, end: number, newText: string): void {
this.svc.edit(start, end - start, newText);
}
getTextChangeRangeBetweenVersions(startVersion: number, endVersion: number): ts.TextChangeRange {
return this.svc.getTextChangesBetweenVersions(startVersion, endVersion);
}
getChangeRange(oldSnapshot: ts.IScriptSnapshot): ts.TextChangeRange {
return this.snap().getChangeRange(oldSnapshot);
}
}
interface TimestampedResolvedModule extends ResolvedModule {
lastCheckTime: number;
}
export class LSHost implements ts.LanguageServiceHost {
ls: ts.LanguageService = null;
compilationSettings: ts.CompilerOptions;
filenameToScript: ts.Map<ScriptInfo> = {};
roots: ScriptInfo[] = [];
private resolvedModuleNames: ts.FileMap<Map<TimestampedResolvedModule>>;
private moduleResolutionHost: ts.ModuleResolutionHost;
constructor(public host: ServerHost, public project: Project) {
this.resolvedModuleNames = ts.createFileMap<Map<TimestampedResolvedModule>>(ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames))
this.moduleResolutionHost = {
fileExists: fileName => this.fileExists(fileName),
readFile: fileName => this.host.readFile(fileName)
}
}
resolveModuleNames(moduleNames: string[], containingFile: string): string[] {
let currentResolutionsInFile = this.resolvedModuleNames.get(containingFile);
let newResolutions: Map<TimestampedResolvedModule> = {};
let resolvedFileNames: string[] = [];
let compilerOptions = this.getCompilationSettings();
for (let moduleName of moduleNames) {
// check if this is a duplicate entry in the list
let resolution = lookUp(newResolutions, moduleName);
if (!resolution) {
let existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, moduleName);
if (moduleResolutionIsValid(existingResolution)) {
// ok, it is safe to use existing module resolution results
resolution = existingResolution;
}
else {
resolution = <TimestampedResolvedModule>resolveModuleName(moduleName, containingFile, compilerOptions, this.moduleResolutionHost);
resolution.lastCheckTime = Date.now();
newResolutions[moduleName] = resolution;
}
}
ts.Debug.assert(resolution !== undefined);
resolvedFileNames.push(resolution.resolvedFileName);
}
// replace old results with a new one
this.resolvedModuleNames.set(containingFile, newResolutions);
return resolvedFileNames;
function moduleResolutionIsValid(resolution: TimestampedResolvedModule): boolean {
if (!resolution) {
return false;
}
if (resolution.resolvedFileName) {
// TODO: consider checking failedLookupLocations
// TODO: use lastCheckTime to track expiration for module name resolution
return true;
}
// consider situation if we have no candidate locations as valid resolution.
// after all there is no point to invalidate it if we have no idea where to look for the module.
return resolution.failedLookupLocations.length === 0;
}
}
getDefaultLibFileName() {
var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath()));
return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings));
}
getScriptSnapshot(filename: string): ts.IScriptSnapshot {
var scriptInfo = this.getScriptInfo(filename);
if (scriptInfo) {
return scriptInfo.snap();
}
}
setCompilationSettings(opt: ts.CompilerOptions) {
this.compilationSettings = opt;
// conservatively assume that changing compiler options might affect module resolution strategy
this.resolvedModuleNames.clear();
}
lineAffectsRefs(filename: string, line: number) {
var info = this.getScriptInfo(filename);
var lineInfo = info.getLineInfo(line);
if (lineInfo && lineInfo.text) {
var regex = /reference|import|\/\*|\*\//;
return regex.test(lineInfo.text);
}
}
getCompilationSettings() {
// change this to return active project settings for file
return this.compilationSettings;
}
getScriptFileNames() {
return this.roots.map(root => root.fileName);
}
getScriptVersion(filename: string) {
return this.getScriptInfo(filename).svc.latestVersion().toString();
}
getCurrentDirectory(): string {
return "";
}
getScriptIsOpen(filename: string) {
return this.getScriptInfo(filename).isOpen;
}
removeReferencedFile(info: ScriptInfo) {
if (!info.isOpen) {
this.filenameToScript[info.fileName] = undefined;
this.resolvedModuleNames.remove(info.fileName);
}
}
getScriptInfo(filename: string): ScriptInfo {
var scriptInfo = ts.lookUp(this.filenameToScript, filename);
if (!scriptInfo) {
scriptInfo = this.project.openReferencedFile(filename);
if (scriptInfo) {
this.filenameToScript[scriptInfo.fileName] = scriptInfo;
}
}
else {
}
return scriptInfo;
}
addRoot(info: ScriptInfo) {
var scriptInfo = ts.lookUp(this.filenameToScript, info.fileName);
if (!scriptInfo) {
this.filenameToScript[info.fileName] = info;
this.roots.push(info);
}
}
removeRoot(info: ScriptInfo) {
var scriptInfo = ts.lookUp(this.filenameToScript, info.fileName);
if (scriptInfo) {
this.filenameToScript[info.fileName] = undefined;
this.roots = copyListRemovingItem(info, this.roots);
}
}
saveTo(filename: string, tmpfilename: string) {
var script = this.getScriptInfo(filename);
if (script) {
var snap = script.snap();
this.host.writeFile(tmpfilename, snap.getText(0, snap.getLength()));
}
}
reloadScript(filename: string, tmpfilename: string, cb: () => any) {
var script = this.getScriptInfo(filename);
if (script) {
script.svc.reloadFromFile(tmpfilename, cb);
}
}
editScript(filename: string, start: number, end: number, newText: string) {
var script = this.getScriptInfo(filename);
if (script) {
script.editContent(start, end, newText);
return;
}
throw new Error("No script with name '" + filename + "'");
}
resolvePath(path: string): string {
var start = new Date().getTime();
var result = this.host.resolvePath(path);
return result;
}
fileExists(path: string): boolean {
var start = new Date().getTime();
var result = this.host.fileExists(path);
return result;
}
directoryExists(path: string): boolean {
return this.host.directoryExists(path);
}
/**
* @param line 1 based index
*/
lineToTextSpan(filename: string, line: number): ts.TextSpan {
var script: ScriptInfo = this.filenameToScript[filename];
var index = script.snap().index;
var lineInfo = index.lineNumberToInfo(line + 1);
var len: number;
if (lineInfo.leaf) {
len = lineInfo.leaf.text.length;
}
else {
var nextLineInfo = index.lineNumberToInfo(line + 2);
len = nextLineInfo.offset - lineInfo.offset;
}
return ts.createTextSpan(lineInfo.offset, len);
}
/**
* @param line 1 based index
* @param offset 1 based index
*/
lineOffsetToPosition(filename: string, line: number, offset: number): number {
var script: ScriptInfo = this.filenameToScript[filename];
var index = script.snap().index;
var lineInfo = index.lineNumberToInfo(line);
// TODO: assert this offset is actually on the line
return (lineInfo.offset + offset - 1);
}
/**
* @param line 1-based index
* @param offset 1-based index
*/
positionToLineOffset(filename: string, position: number): ILineInfo {
var script: ScriptInfo = this.filenameToScript[filename];
var index = script.snap().index;
var lineOffset = index.charOffsetToLineNumberAndPos(position);
return { line: lineOffset.line, offset: lineOffset.offset + 1 };
}
}
// assumes normalized paths
function getAbsolutePath(filename: string, directory: string) {
var rootLength = ts.getRootLength(filename);
if (rootLength > 0) {
return filename;
}
else {
var splitFilename = filename.split('/');
var splitDir = directory.split('/');
var i = 0;
var dirTail = 0;
var sflen = splitFilename.length;
while ((i < sflen) && (splitFilename[i].charAt(0) == '.')) {
var dots = splitFilename[i];
if (dots == '..') {
dirTail++;
}
else if (dots != '.') {
return undefined;
}
i++;
}
return splitDir.slice(0, splitDir.length - dirTail).concat(splitFilename.slice(i)).join('/');
}
}
export interface ProjectOptions {
// these fields can be present in the project file
files?: string[];
compilerOptions?: ts.CompilerOptions;
}
export class Project {
compilerService: CompilerService;
projectFilename: string;
projectFileWatcher: FileWatcher;
program: ts.Program;
filenameToSourceFile: ts.Map<ts.SourceFile> = {};
updateGraphSeq = 0;
/** Used for configured projects which may have multiple open roots */
openRefCount = 0;
constructor(public projectService: ProjectService, public projectOptions?: ProjectOptions) {
this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions);
}
addOpenRef() {
this.openRefCount++;
}
deleteOpenRef() {
this.openRefCount--;
return this.openRefCount;
}
openReferencedFile(filename: string) {
return this.projectService.openFile(filename, false);
}
getFileNames() {
let sourceFiles = this.program.getSourceFiles();
return sourceFiles.map(sourceFile => sourceFile.fileName);
}
getSourceFile(info: ScriptInfo) {
return this.filenameToSourceFile[info.fileName];
}
getSourceFileFromName(filename: string, requireOpen?: boolean) {
var info = this.projectService.getScriptInfo(filename);
if (info) {
if ((!requireOpen) || info.isOpen) {
return this.getSourceFile(info);
}
}
}
isRoot(info: ScriptInfo) {
return this.compilerService.host.roots.some(root => root === info);
}
removeReferencedFile(info: ScriptInfo) {
this.compilerService.host.removeReferencedFile(info);
this.updateGraph();
}
updateFileMap() {
this.filenameToSourceFile = {};
var sourceFiles = this.program.getSourceFiles();
for (var i = 0, len = sourceFiles.length; i < len; i++) {
var normFilename = ts.normalizePath(sourceFiles[i].fileName);
this.filenameToSourceFile[normFilename] = sourceFiles[i];
}
}
finishGraph() {
this.updateGraph();
this.compilerService.languageService.getNavigateToItems(".*");
}
updateGraph() {
this.program = this.compilerService.languageService.getProgram();
this.updateFileMap();
}
isConfiguredProject() {
return this.projectFilename;
}
// add a root file to project
addRoot(info: ScriptInfo) {
info.defaultProject = this;
this.compilerService.host.addRoot(info);
}
// remove a root file from project
removeRoot(info: ScriptInfo) {
info.defaultProject = undefined;
this.compilerService.host.removeRoot(info);
}
filesToString() {
var strBuilder = "";
ts.forEachValue(this.filenameToSourceFile,
sourceFile => { strBuilder += sourceFile.fileName + "\n"; });
return strBuilder;
}
setProjectOptions(projectOptions: ProjectOptions) {
this.projectOptions = projectOptions;
if (projectOptions.compilerOptions) {
this.compilerService.setCompilerOptions(projectOptions.compilerOptions);
}
}
}
export interface ProjectOpenResult {
success?: boolean;
errorMsg?: string;
project?: Project;
}
function copyListRemovingItem<T>(item: T, list: T[]) {
var copiedList: T[] = [];
for (var i = 0, len = list.length; i < len; i++) {
if (list[i] != item) {
copiedList.push(list[i]);
}
}
return copiedList;
}
export interface ProjectServiceEventHandler {
(eventName: string, project: Project, fileName: string): void;
}
export interface HostConfiguration {
formatCodeOptions: ts.FormatCodeOptions;
hostInfo: string;
}
export class ProjectService {
filenameToScriptInfo: ts.Map<ScriptInfo> = {};
// open, non-configured root files
openFileRoots: ScriptInfo[] = [];
// projects built from openFileRoots
inferredProjects: Project[] = [];
// projects specified by a tsconfig.json file
configuredProjects: Project[] = [];
// open files referenced by a project
openFilesReferenced: ScriptInfo[] = [];
// open files that are roots of a configured project
openFileRootsConfigured: ScriptInfo[] = [];
hostConfiguration: HostConfiguration;
constructor(public host: ServerHost, public psLogger: Logger, public eventHandler?: ProjectServiceEventHandler) {
// ts.disableIncrementalParsing = true;
this.addDefaultHostConfiguration();
}
addDefaultHostConfiguration() {
this.hostConfiguration = {
formatCodeOptions: ts.clone(CompilerService.defaultFormatCodeOptions),
hostInfo: "Unknown host"
}
}
getFormatCodeOptions(file?: string) {
if (file) {
var info = this.filenameToScriptInfo[file];
if (info) {
return info.formatCodeOptions;
}
}
return this.hostConfiguration.formatCodeOptions;
}
watchedFileChanged(fileName: string) {
var info = this.filenameToScriptInfo[fileName];
if (!info) {
this.psLogger.info("Error: got watch notification for unknown file: " + fileName);
}
if (!this.host.fileExists(fileName)) {
// File was deleted
this.fileDeletedInFilesystem(info);
}
else {
if (info && (!info.isOpen)) {
info.svc.reloadFromFile(info.fileName);
}
}
}
watchedProjectConfigFileChanged(project: Project) {
this.log("Config File Changed: " + project.projectFilename);
this.updateConfiguredProject(project);
this.updateProjectStructure();
}
log(msg: string, type = "Err") {
this.psLogger.msg(msg, type);
}
setHostConfiguration(args: ts.server.protocol.ConfigureRequestArguments) {
if (args.file) {
var info = this.filenameToScriptInfo[args.file];
if (info) {
info.setFormatOptions(args.formatOptions);
this.log("Host configuration update for file " + args.file, "Info");
}
}
else {
if (args.hostInfo !== undefined) {
this.hostConfiguration.hostInfo = args.hostInfo;
this.log("Host information " + args.hostInfo, "Info");
}
if (args.formatOptions) {
mergeFormatOptions(this.hostConfiguration.formatCodeOptions, args.formatOptions);
this.log("Format host information updated", "Info");
}
}
}
closeLog() {
this.psLogger.close();
}
createInferredProject(root: ScriptInfo) {
var iproj = new Project(this);
iproj.addRoot(root);
iproj.finishGraph();
this.inferredProjects.push(iproj);
return iproj;
}
fileDeletedInFilesystem(info: ScriptInfo) {
this.psLogger.info(info.fileName + " deleted");
if (info.fileWatcher) {
info.fileWatcher.close();
info.fileWatcher = undefined;
}
if (!info.isOpen) {
this.filenameToScriptInfo[info.fileName] = undefined;
var referencingProjects = this.findReferencingProjects(info);
for (var i = 0, len = referencingProjects.length; i < len; i++) {
referencingProjects[i].removeReferencedFile(info);
}
for (var j = 0, flen = this.openFileRoots.length; j < flen; j++) {
var openFile = this.openFileRoots[j];
if (this.eventHandler) {
this.eventHandler("context", openFile.defaultProject, openFile.fileName);
}
}
for (var j = 0, flen = this.openFilesReferenced.length; j < flen; j++) {
var openFile = this.openFilesReferenced[j];
if (this.eventHandler) {
this.eventHandler("context", openFile.defaultProject, openFile.fileName);
}
}
}
this.printProjects();
}
updateConfiguredProjectList() {
var configuredProjects: Project[] = [];
for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
if (this.configuredProjects[i].openRefCount > 0) {
configuredProjects.push(this.configuredProjects[i]);
}
}
this.configuredProjects = configuredProjects;
}
removeConfiguredProject(project: Project) {
project.projectFileWatcher.close();
this.configuredProjects = copyListRemovingItem(project, this.configuredProjects);
let fileNames = project.getFileNames();
for (let fileName of fileNames) {
let info = this.getScriptInfo(fileName);
if (info.defaultProject == project){
info.defaultProject = undefined;
}
}
}
setConfiguredProjectRoot(info: ScriptInfo) {
for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
let configuredProject = this.configuredProjects[i];
if (configuredProject.isRoot(info)) {
info.defaultProject = configuredProject;
configuredProject.addOpenRef();
return true;
}
}
return false;
}
addOpenFile(info: ScriptInfo) {
if (this.setConfiguredProjectRoot(info)) {
this.openFileRootsConfigured.push(info);
}
else {
this.findReferencingProjects(info);
if (info.defaultProject) {
this.openFilesReferenced.push(info);
}
else {
// create new inferred project p with the newly opened file as root
info.defaultProject = this.createInferredProject(info);
var openFileRoots: ScriptInfo[] = [];
// for each inferred project root r
for (var i = 0, len = this.openFileRoots.length; i < len; i++) {
var r = this.openFileRoots[i];
// if r referenced by the new project
if (info.defaultProject.getSourceFile(r)) {
// remove project rooted at r
this.inferredProjects =
copyListRemovingItem(r.defaultProject, this.inferredProjects);
// put r in referenced open file list
this.openFilesReferenced.push(r);
// set default project of r to the new project
r.defaultProject = info.defaultProject;
}
else {
// otherwise, keep r as root of inferred project
openFileRoots.push(r);
}
}
this.openFileRoots = openFileRoots;
this.openFileRoots.push(info);
}
}
this.updateConfiguredProjectList();
}
/**
* Remove this file from the set of open, non-configured files.
* @param info The file that has been closed or newly configured
*/
closeOpenFile(info: ScriptInfo) {
var openFileRoots: ScriptInfo[] = [];
var removedProject: Project;
for (var i = 0, len = this.openFileRoots.length; i < len; i++) {
// if closed file is root of project
if (info === this.openFileRoots[i]) {
// remove that project and remember it
removedProject = info.defaultProject;
}
else {
openFileRoots.push(this.openFileRoots[i]);
}
}
this.openFileRoots = openFileRoots;
if (!removedProject) {
var openFileRootsConfigured: ScriptInfo[] = [];
for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) {
if (info === this.openFileRootsConfigured[i]) {
if (info.defaultProject.deleteOpenRef() === 0) {
removedProject = info.defaultProject;
}
}
else {
openFileRootsConfigured.push(this.openFileRootsConfigured[i]);
}
}
this.openFileRootsConfigured = openFileRootsConfigured;
}
if (removedProject) {
if (removedProject.isConfiguredProject()) {
this.configuredProjects = copyListRemovingItem(removedProject, this.configuredProjects);
}
else {
this.inferredProjects = copyListRemovingItem(removedProject, this.inferredProjects);
}
var openFilesReferenced: ScriptInfo[] = [];
var orphanFiles: ScriptInfo[] = [];
// for all open, referenced files f
for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) {
var f = this.openFilesReferenced[i];
// if f was referenced by the removed project, remember it
if (f.defaultProject === removedProject) {
f.defaultProject = undefined;
orphanFiles.push(f);
}
else {
// otherwise add it back to the list of referenced files
openFilesReferenced.push(f);
}
}
this.openFilesReferenced = openFilesReferenced;
// treat orphaned files as newly opened
for (var i = 0, len = orphanFiles.length; i < len; i++) {
this.addOpenFile(orphanFiles[i]);
}
}
else {
this.openFilesReferenced = copyListRemovingItem(info, this.openFilesReferenced);
}
info.close();
}
findReferencingProjects(info: ScriptInfo, excludedProject?: Project) {
var referencingProjects: Project[] = [];
info.defaultProject = undefined;
for (var i = 0, len = this.inferredProjects.length; i < len; i++) {
var inferredProject = this.inferredProjects[i];
inferredProject.updateGraph();
if (inferredProject !== excludedProject) {
if (inferredProject.getSourceFile(info)) {
info.defaultProject = inferredProject;
referencingProjects.push(inferredProject);
}
}
}
for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
var configuredProject = this.configuredProjects[i];
configuredProject.updateGraph();
if (configuredProject.getSourceFile(info)) {
info.defaultProject = configuredProject;
}
}
return referencingProjects;
}
reloadProjects() {
// First check if there is new tsconfig file added for inferred project roots
for (let info of this.openFileRoots) {
this.openOrUpdateConfiguredProjectForFile(info.fileName);
}
this.updateProjectStructure();
}
/**
* This function is to update the project structure for every projects.
* It is called on the premise that all the configured projects are
* up to date.
*/
updateProjectStructure() {
this.log("updating project structure from ...", "Info");
this.printProjects();
let unattachedOpenFiles: ScriptInfo[] = [];
let openFileRootsConfigured: ScriptInfo[] = [];
for (let info of this.openFileRootsConfigured) {
let project = info.defaultProject;
if (!project || !(project.getSourceFile(info))) {
info.defaultProject = undefined;
unattachedOpenFiles.push(info);
}
else {
openFileRootsConfigured.push(info);
}
}
this.openFileRootsConfigured = openFileRootsConfigured;
// First loop through all open files that are referenced by projects but are not
// project roots. For each referenced file, see if the default project still
// references that file. If so, then just keep the file in the referenced list.
// If not, add the file to an unattached list, to be rechecked later.
var openFilesReferenced: ScriptInfo[] = [];
for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) {
var referencedFile = this.openFilesReferenced[i];
referencedFile.defaultProject.updateGraph();
var sourceFile = referencedFile.defaultProject.getSourceFile(referencedFile);
if (sourceFile) {
openFilesReferenced.push(referencedFile);
}
else {
unattachedOpenFiles.push(referencedFile);
}
}
this.openFilesReferenced = openFilesReferenced;
// Then, loop through all of the open files that are project roots.
// For each root file, note the project that it roots. Then see if
// any other projects newly reference the file. If zero projects
// newly reference the file, keep it as a root. If one or more
// projects newly references the file, remove its project from the
// inferred projects list (since it is no longer a root) and add
// the file to the open, referenced file list.
var openFileRoots: ScriptInfo[] = [];
for (var i = 0, len = this.openFileRoots.length; i < len; i++) {
var rootFile = this.openFileRoots[i];
var rootedProject = rootFile.defaultProject;
var referencingProjects = this.findReferencingProjects(rootFile, rootedProject);
if (referencingProjects.length === 0) {
rootFile.defaultProject = rootedProject;
openFileRoots.push(rootFile);
}
else {
// remove project from inferred projects list because root captured
this.inferredProjects = copyListRemovingItem(rootedProject, this.inferredProjects);
this.openFilesReferenced.push(rootFile);
}
}
this.openFileRoots = openFileRoots;
// Finally, if we found any open, referenced files that are no longer
// referenced by their default project, treat them as newly opened
// by the editor.
for (var i = 0, len = unattachedOpenFiles.length; i < len; i++) {
this.addOpenFile(unattachedOpenFiles[i]);
}
this.printProjects();
}
getScriptInfo(filename: string) {
filename = ts.normalizePath(filename);
return ts.lookUp(this.filenameToScriptInfo, filename);
}
/**
* @param filename is absolute pathname
*/
openFile(fileName: string, openedByClient: boolean) {
fileName = ts.normalizePath(fileName);
var info = ts.lookUp(this.filenameToScriptInfo, fileName);
if (!info) {
var content: string;
if (this.host.fileExists(fileName)) {
content = this.host.readFile(fileName);
}
if (!content) {
if (openedByClient) {
content = "";
}
}
if (content !== undefined) {
var indentSize: number;
info = new ScriptInfo(this.host, fileName, content, openedByClient);
info.setFormatOptions(this.getFormatCodeOptions());
this.filenameToScriptInfo[fileName] = info;
if (!info.isOpen) {
info.fileWatcher = this.host.watchFile(fileName, _ => { this.watchedFileChanged(fileName); });
}
}
}
if (info) {
if (openedByClient) {
info.isOpen = true;
}
}
return info;
}
// This is different from the method the compiler uses because
// the compiler can assume it will always start searching in the
// current directory (the directory in which tsc was invoked).
// The server must start searching from the directory containing
// the newly opened file.
findConfigFile(searchPath: string): string {
while (true) {
var fileName = ts.combinePaths(searchPath, "tsconfig.json");
if (this.host.fileExists(fileName)) {
return fileName;
}
var parentPath = ts.getDirectoryPath(searchPath);
if (parentPath === searchPath) {
break;
}
searchPath = parentPath;
}
return undefined;
}
/**
* Open file whose contents is managed by the client
* @param filename is absolute pathname
*/
openClientFile(fileName: string) {
this.openOrUpdateConfiguredProjectForFile(fileName);
var info = this.openFile(fileName, true);
this.addOpenFile(info);
this.printProjects();
return info;
}
openOrUpdateConfiguredProjectForFile(fileName: string) {
let searchPath = ts.normalizePath(getDirectoryPath(fileName));
this.log("Search path: " + searchPath,"Info");
let configFileName = this.findConfigFile(searchPath);
if (configFileName) {
this.log("Config file name: " + configFileName, "Info");
let project = this.findConfiguredProjectByConfigFile(configFileName);
if (!project) {
var configResult = this.openConfigFile(configFileName, fileName);
if (!configResult.success) {
this.log("Error opening config file " + configFileName + " " + configResult.errorMsg);
}
else {
this.log("Opened configuration file " + configFileName,"Info");
this.configuredProjects.push(configResult.project);
}
}
else {
this.updateConfiguredProject(project);
}
}
else {
this.log("No config files found.");
}
}
/**
* Close file whose contents is managed by the client
* @param filename is absolute pathname
*/
closeClientFile(filename: string) {
var info = ts.lookUp(this.filenameToScriptInfo, filename);
if (info) {
this.closeOpenFile(info);
info.isOpen = false;
}
this.printProjects();
}
getProjectForFile(filename: string) {
var scriptInfo = ts.lookUp(this.filenameToScriptInfo, filename);
if (scriptInfo) {
return scriptInfo.defaultProject;
}
}
printProjectsForFile(filename: string) {
var scriptInfo = ts.lookUp(this.filenameToScriptInfo, filename);
if (scriptInfo) {
this.psLogger.startGroup();
this.psLogger.info("Projects for " + filename)
var projects = this.findReferencingProjects(scriptInfo);
for (var i = 0, len = projects.length; i < len; i++) {
this.psLogger.info("Project " + i.toString());
}
this.psLogger.endGroup();
}
else {
this.psLogger.info(filename + " not in any project");
}
}
printProjects() {
if (!this.psLogger.isVerbose()) {
return;
}
this.psLogger.startGroup();
for (var i = 0, len = this.inferredProjects.length; i < len; i++) {
var project = this.inferredProjects[i];
project.updateGraph();
this.psLogger.info("Project " + i.toString());
this.psLogger.info(project.filesToString());
this.psLogger.info("-----------------------------------------------");
}
for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
var project = this.configuredProjects[i];
project.updateGraph();
this.psLogger.info("Project (configured) " + (i+this.inferredProjects.length).toString());
this.psLogger.info(project.filesToString());
this.psLogger.info("-----------------------------------------------");
}
this.psLogger.info("Open file roots of inferred projects: ")
for (var i = 0, len = this.openFileRoots.length; i < len; i++) {
this.psLogger.info(this.openFileRoots[i].fileName);
}
this.psLogger.info("Open files referenced by inferred or configured projects: ")
for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) {
var fileInfo = this.openFilesReferenced[i].fileName;
if (this.openFilesReferenced[i].defaultProject.isConfiguredProject()) {
fileInfo += " (configured)";
}
this.psLogger.info(fileInfo);
}
this.psLogger.info("Open file roots of configured projects: ")
for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) {
this.psLogger.info(this.openFileRootsConfigured[i].fileName);
}
this.psLogger.endGroup();
}
configProjectIsActive(fileName: string) {
return this.findConfiguredProjectByConfigFile(fileName) === undefined;
}
findConfiguredProjectByConfigFile(configFileName: string) {
for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
if (this.configuredProjects[i].projectFilename == configFileName) {
return this.configuredProjects[i];
}
}
return undefined;
}
configFileToProjectOptions(configFilename: string): { succeeded: boolean, projectOptions?: ProjectOptions, error?: ProjectOpenResult } {
configFilename = ts.normalizePath(configFilename);
// file references will be relative to dirPath (or absolute)
var dirPath = ts.getDirectoryPath(configFilename);
var contents = this.host.readFile(configFilename)
var rawConfig: { config?: ProjectOptions; error?: Diagnostic; } = ts.parseConfigFileText(configFilename, contents);
if (rawConfig.error) {
return { succeeded: false, error: rawConfig.error };
}
else {
var parsedCommandLine = ts.parseConfigFile(rawConfig.config, this.host, dirPath);
if (parsedCommandLine.errors && (parsedCommandLine.errors.length > 0)) {
return { succeeded: false, error: { errorMsg: "tsconfig option errors" }};
}
else if (parsedCommandLine.fileNames == null) {
return { succeeded: false, error: { errorMsg: "no files found" }}
}
else {
var projectOptions: ProjectOptions = {
files: parsedCommandLine.fileNames,
compilerOptions: parsedCommandLine.options
};
return { succeeded: true, projectOptions };
}
}
}
openConfigFile(configFilename: string, clientFileName?: string): ProjectOpenResult {
let { succeeded, projectOptions, error } = this.configFileToProjectOptions(configFilename);
if (!succeeded) {
return error;
}
else {
let proj = this.createProject(configFilename, projectOptions);
for (let i = 0, len = projectOptions.files.length; i < len; i++) {
let rootFilename = projectOptions.files[i];
if (this.host.fileExists(rootFilename)) {
let info = this.openFile(rootFilename, /*openedByClient*/ clientFileName == rootFilename);
proj.addRoot(info);
}
else {
return { errorMsg: "specified file " + rootFilename + " not found" };
}
}
proj.finishGraph();
proj.projectFileWatcher = this.host.watchFile(configFilename, _ => this.watchedProjectConfigFileChanged(proj));
return { success: true, project: proj };
}
}
updateConfiguredProject(project: Project) {
if (!this.host.fileExists(project.projectFilename)) {
this.log("Config file deleted");
this.removeConfiguredProject(project);
}
else {
let { succeeded, projectOptions, error } = this.configFileToProjectOptions(project.projectFilename);
if (!succeeded) {
return error;
}
else {
let oldFileNames = project.compilerService.host.roots.map(info => info.fileName);
let newFileNames = projectOptions.files;
let fileNamesToRemove = oldFileNames.filter(f => newFileNames.indexOf(f) < 0);
let fileNamesToAdd = newFileNames.filter(f => oldFileNames.indexOf(f) < 0);
for (let fileName of fileNamesToRemove) {
let info = this.getScriptInfo(fileName);
project.removeRoot(info);
}
for (let fileName of fileNamesToAdd) {
let info = this.getScriptInfo(fileName);
if (!info) {
info = this.openFile(fileName, false);
}
else {
// if the root file was opened by client, it would belong to either
// openFileRoots or openFileReferenced.
if (info.isOpen) {
if (this.openFileRoots.indexOf(info) >= 0) {
this.openFileRoots = copyListRemovingItem(info, this.openFileRoots);
}
if (this.openFilesReferenced.indexOf(info) >= 0) {
this.openFilesReferenced = copyListRemovingItem(info, this.openFilesReferenced);
}
this.openFileRootsConfigured.push(info);
}
}
project.addRoot(info);
}
project.setProjectOptions(projectOptions);
project.finishGraph();
}
}
}
createProject(projectFilename: string, projectOptions?: ProjectOptions) {
var project = new Project(this, projectOptions);
project.projectFilename = projectFilename;
return project;
}
}
export class CompilerService {
host: LSHost;
languageService: ts.LanguageService;
classifier: ts.Classifier;
settings: ts.CompilerOptions;
documentRegistry = ts.createDocumentRegistry();
constructor(public project: Project, opt?: ts.CompilerOptions) {
this.host = new LSHost(project.projectService.host, project);
if (opt) {
this.setCompilerOptions(opt);
}
else {
this.setCompilerOptions(ts.getDefaultCompilerOptions());
}
this.languageService = ts.createLanguageService(this.host, this.documentRegistry);
this.classifier = ts.createClassifier();
}
setCompilerOptions(opt: ts.CompilerOptions) {
this.settings = opt;
this.host.setCompilationSettings(opt);
}
isExternalModule(filename: string): boolean {
var sourceFile = this.languageService.getSourceFile(filename);
return ts.isExternalModule(sourceFile);
}
static defaultFormatCodeOptions: ts.FormatCodeOptions = {
IndentSize: 4,
TabSize: 4,
NewLineCharacter: ts.sys ? ts.sys.newLine : '\n',
ConvertTabsToSpaces: true,
InsertSpaceAfterCommaDelimiter: true,
InsertSpaceAfterSemicolonInForStatements: true,
InsertSpaceBeforeAndAfterBinaryOperators: true,
InsertSpaceAfterKeywordsInControlFlowStatements: true,
InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
PlaceOpenBraceOnNewLineForFunctions: false,
PlaceOpenBraceOnNewLineForControlBlocks: false,
}
}
export interface LineCollection {
charCount(): number;
lineCount(): number;
isLeaf(): boolean;
walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker): void;
}
export interface ILineInfo {
line: number;
offset: number;
text?: string;
leaf?: LineLeaf;
}
export enum CharRangeSection {
PreStart,
Start,
Entire,
Mid,
End,
PostEnd
}
export interface ILineIndexWalker {
goSubtree: boolean;
done: boolean;
leaf(relativeStart: number, relativeLength: number, lineCollection: LineLeaf): void;
pre? (relativeStart: number, relativeLength: number, lineCollection: LineCollection,
parent: LineNode, nodeType: CharRangeSection): LineCollection;
post? (relativeStart: number, relativeLength: number, lineCollection: LineCollection,
parent: LineNode, nodeType: CharRangeSection): LineCollection;
}
class BaseLineIndexWalker implements ILineIndexWalker {
goSubtree = true;
done = false;
leaf(rangeStart: number, rangeLength: number, ll: LineLeaf) {
}
}
class EditWalker extends BaseLineIndexWalker {
lineIndex = new LineIndex();
// path to start of range
startPath: LineCollection[];
endBranch: LineCollection[] = [];
branchNode: LineNode;
// path to current node
stack: LineNode[];
state = CharRangeSection.Entire;
lineCollectionAtBranch: LineCollection;
initialText = "";
trailingText = "";
suppressTrailingText = false;
constructor() {
super();
this.lineIndex.root = new LineNode();
this.startPath = [this.lineIndex.root];
this.stack = [this.lineIndex.root];
}
insertLines(insertedText: string) {
if (this.suppressTrailingText) {
this.trailingText = "";
}
if (insertedText) {
insertedText = this.initialText + insertedText + this.trailingText;
}
else {
insertedText = this.initialText + this.trailingText;
}
var lm = LineIndex.linesFromText(insertedText);
var lines = lm.lines;
if (lines.length > 1) {
if (lines[lines.length - 1] == "") {
lines.length--;
}
}
var branchParent: LineNode;
var lastZeroCount: LineCollection;
for (var k = this.endBranch.length - 1; k >= 0; k--) {
(<LineNode>this.endBranch[k]).updateCounts();
if (this.endBranch[k].charCount() === 0) {
lastZeroCount = this.endBranch[k];
if (k > 0) {
branchParent = <LineNode>this.endBranch[k - 1];
}
else {
branchParent = this.branchNode;
}
}
}
if (lastZeroCount) {
branchParent.remove(lastZeroCount);
}
// path at least length two (root and leaf)
var insertionNode = <LineNode>this.startPath[this.startPath.length - 2];
var leafNode = <LineLeaf>this.startPath[this.startPath.length - 1];
var len = lines.length;
if (len > 0) {
leafNode.text = lines[0];
if (len > 1) {
var insertedNodes = <LineCollection[]>new Array(len - 1);
var startNode = <LineCollection>leafNode;
for (var i = 1, len = lines.length; i < len; i++) {
insertedNodes[i - 1] = new LineLeaf(lines[i]);
}
var pathIndex = this.startPath.length - 2;
while (pathIndex >= 0) {
insertionNode = <LineNode>this.startPath[pathIndex];
insertedNodes = insertionNode.insertAt(startNode, insertedNodes);
pathIndex--;
startNode = insertionNode;
}
var insertedNodesLen = insertedNodes.length;
while (insertedNodesLen > 0) {
var newRoot = new LineNode();
newRoot.add(this.lineIndex.root);
insertedNodes = newRoot.insertAt(this.lineIndex.root, insertedNodes);
insertedNodesLen = insertedNodes.length;
this.lineIndex.root = newRoot;
}
this.lineIndex.root.updateCounts();
}
else {
for (var j = this.startPath.length - 2; j >= 0; j--) {
(<LineNode>this.startPath[j]).updateCounts();
}
}
}
else {
// no content for leaf node, so delete it
insertionNode.remove(leafNode);
for (var j = this.startPath.length - 2; j >= 0; j--) {
(<LineNode>this.startPath[j]).updateCounts();
}
}
return this.lineIndex;
}
post(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineCollection, nodeType: CharRangeSection): LineCollection {
// have visited the path for start of range, now looking for end
// if range is on single line, we will never make this state transition
if (lineCollection === this.lineCollectionAtBranch) {
this.state = CharRangeSection.End;
}
// always pop stack because post only called when child has been visited
this.stack.length--;
return undefined;
}
pre(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineCollection, nodeType: CharRangeSection) {
// currentNode corresponds to parent, but in the new tree
var currentNode = this.stack[this.stack.length - 1];
if ((this.state === CharRangeSection.Entire) && (nodeType === CharRangeSection.Start)) {
// if range is on single line, we will never make this state transition
this.state = CharRangeSection.Start;
this.branchNode = currentNode;
this.lineCollectionAtBranch = lineCollection;
}
var child: LineCollection;
function fresh(node: LineCollection): LineCollection {
if (node.isLeaf()) {
return new LineLeaf("");
}
else return new LineNode();
}
switch (nodeType) {
case CharRangeSection.PreStart:
this.goSubtree = false;
if (this.state !== CharRangeSection.End) {
currentNode.add(lineCollection);
}
break;
case CharRangeSection.Start:
if (this.state === CharRangeSection.End) {
this.goSubtree = false;
}
else {
child = fresh(lineCollection);
currentNode.add(child);
this.startPath[this.startPath.length] = child;
}
break;
case CharRangeSection.Entire:
if (this.state !== CharRangeSection.End) {
child = fresh(lineCollection);
currentNode.add(child);
this.startPath[this.startPath.length] = child;
}
else {
if (!lineCollection.isLeaf()) {
child = fresh(lineCollection);
currentNode.add(child);
this.endBranch[this.endBranch.length] = child;
}
}
break;
case CharRangeSection.Mid:
this.goSubtree = false;
break;
case CharRangeSection.End:
if (this.state !== CharRangeSection.End) {
this.goSubtree = false;
}
else {
if (!lineCollection.isLeaf()) {
child = fresh(lineCollection);
currentNode.add(child);
this.endBranch[this.endBranch.length] = child;
}
}
break;
case CharRangeSection.PostEnd:
this.goSubtree = false;
if (this.state !== CharRangeSection.Start) {
currentNode.add(lineCollection);
}
break;
}
if (this.goSubtree) {
this.stack[this.stack.length] = <LineNode>child;
}
return lineCollection;
}
// just gather text from the leaves
leaf(relativeStart: number, relativeLength: number, ll: LineLeaf) {
if (this.state === CharRangeSection.Start) {
this.initialText = ll.text.substring(0, relativeStart);
}
else if (this.state === CharRangeSection.Entire) {
this.initialText = ll.text.substring(0, relativeStart);
this.trailingText = ll.text.substring(relativeStart + relativeLength);
}
else {
// state is CharRangeSection.End
this.trailingText = ll.text.substring(relativeStart + relativeLength);
}
}
}
// text change information
export class TextChange {
constructor(public pos: number, public deleteLen: number, public insertedText?: string) {
}
getTextChangeRange() {
return ts.createTextChangeRange(ts.createTextSpan(this.pos, this.deleteLen),
this.insertedText ? this.insertedText.length : 0);
}
}
export class ScriptVersionCache {
changes: TextChange[] = [];
versions: LineIndexSnapshot[] = [];
minVersion = 0; // no versions earlier than min version will maintain change history
private currentVersion = 0;
private host: ServerHost;
static changeNumberThreshold = 8;
static changeLengthThreshold = 256;
static maxVersions = 8;
// REVIEW: can optimize by coalescing simple edits
edit(pos: number, deleteLen: number, insertedText?: string) {
this.changes[this.changes.length] = new TextChange(pos, deleteLen, insertedText);
if ((this.changes.length > ScriptVersionCache.changeNumberThreshold) ||
(deleteLen > ScriptVersionCache.changeLengthThreshold) ||
(insertedText && (insertedText.length > ScriptVersionCache.changeLengthThreshold))) {
this.getSnapshot();
}
}
latest() {
return this.versions[this.currentVersion];
}
latestVersion() {
if (this.changes.length > 0) {
this.getSnapshot();
}
return this.currentVersion;
}
reloadFromFile(filename: string, cb?: () => any) {
var content = this.host.readFile(filename);
this.reload(content);
if (cb)
cb();
}
// reload whole script, leaving no change history behind reload
reload(script: string) {
this.currentVersion++;
this.changes = []; // history wiped out by reload
var snap = new LineIndexSnapshot(this.currentVersion, this);
this.versions[this.currentVersion] = snap;
snap.index = new LineIndex();
var lm = LineIndex.linesFromText(script);
snap.index.load(lm.lines);
// REVIEW: could use linked list
for (var i = this.minVersion; i < this.currentVersion; i++) {
this.versions[i] = undefined;
}
this.minVersion = this.currentVersion;
}
getSnapshot() {
var snap = this.versions[this.currentVersion];
if (this.changes.length > 0) {
var snapIndex = this.latest().index;
for (var i = 0, len = this.changes.length; i < len; i++) {
var change = this.changes[i];
snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText);
}
snap = new LineIndexSnapshot(this.currentVersion + 1, this);
snap.index = snapIndex;
snap.changesSincePreviousVersion = this.changes;
this.currentVersion = snap.version;
this.versions[snap.version] = snap;
this.changes = [];
if ((this.currentVersion - this.minVersion) >= ScriptVersionCache.maxVersions) {
var oldMin = this.minVersion;
this.minVersion = (this.currentVersion - ScriptVersionCache.maxVersions) + 1;
for (var j = oldMin; j < this.minVersion; j++) {
this.versions[j] = undefined;
}
}
}
return snap;
}
getTextChangesBetweenVersions(oldVersion: number, newVersion: number) {
if (oldVersion < newVersion) {
if (oldVersion >= this.minVersion) {
var textChangeRanges: ts.TextChangeRange[] = [];
for (var i = oldVersion + 1; i <= newVersion; i++) {
var snap = this.versions[i];
for (var j = 0, len = snap.changesSincePreviousVersion.length; j < len; j++) {
var textChange = snap.changesSincePreviousVersion[j];
textChangeRanges[textChangeRanges.length] = textChange.getTextChangeRange();
}
}
return ts.collapseTextChangeRangesAcrossMultipleVersions(textChangeRanges);
}
else {
return undefined;
}
}
else {
return ts.unchangedTextChangeRange;
}
}
static fromString(host: ServerHost, script: string) {
var svc = new ScriptVersionCache();
var snap = new LineIndexSnapshot(0, svc);
svc.versions[svc.currentVersion] = snap;
svc.host = host;
snap.index = new LineIndex();
var lm = LineIndex.linesFromText(script);
snap.index.load(lm.lines);
return svc;
}
}
export class LineIndexSnapshot implements ts.IScriptSnapshot {
index: LineIndex;
changesSincePreviousVersion: TextChange[] = [];
constructor(public version: number, public cache: ScriptVersionCache) {
}
getText(rangeStart: number, rangeEnd: number) {
return this.index.getText(rangeStart, rangeEnd - rangeStart);
}
getLength() {
return this.index.root.charCount();
}
// this requires linear space so don't hold on to these
getLineStartPositions(): number[] {
var starts: number[] = [-1];
var count = 1;
var pos = 0;
this.index.every((ll, s, len) => {
starts[count++] = pos;
pos += ll.text.length;
return true;
}, 0);
return starts;
}
getLineMapper() {
return ((line: number) => {
return this.index.lineNumberToInfo(line).offset;
});
}
getTextChangeRangeSinceVersion(scriptVersion: number) {
if (this.version <= scriptVersion) {
return ts.unchangedTextChangeRange;
}
else {
return this.cache.getTextChangesBetweenVersions(scriptVersion, this.version);
}
}
getChangeRange(oldSnapshot: ts.IScriptSnapshot): ts.TextChangeRange {
var oldSnap = <LineIndexSnapshot>oldSnapshot;
return this.getTextChangeRangeSinceVersion(oldSnap.version);
}
}
export class LineIndex {
root: LineNode;
// set this to true to check each edit for accuracy
checkEdits = false;
charOffsetToLineNumberAndPos(charOffset: number) {
return this.root.charOffsetToLineNumberAndPos(1, charOffset);
}
lineNumberToInfo(lineNumber: number): ILineInfo {
var lineCount = this.root.lineCount();
if (lineNumber <= lineCount) {
var lineInfo = this.root.lineNumberToInfo(lineNumber, 0);
lineInfo.line = lineNumber;
return lineInfo;
}
else {
return {
line: lineNumber,
offset: this.root.charCount()
}
}
}
load(lines: string[]) {
if (lines.length > 0) {
var leaves: LineLeaf[] = [];
for (var i = 0, len = lines.length; i < len; i++) {
leaves[i] = new LineLeaf(lines[i]);
}
this.root = LineIndex.buildTreeFromBottom(leaves);
}
else {
this.root = new LineNode();
}
}
walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker) {
this.root.walk(rangeStart, rangeLength, walkFns);
}
getText(rangeStart: number, rangeLength: number) {
var accum = "";
if ((rangeLength > 0) && (rangeStart < this.root.charCount())) {
this.walk(rangeStart, rangeLength, {
goSubtree: true,
done: false,
leaf: (relativeStart: number, relativeLength: number, ll: LineLeaf) => {
accum = accum.concat(ll.text.substring(relativeStart, relativeStart + relativeLength));
}
});
}
return accum;
}
getLength(): number {
return this.root.charCount();
}
every(f: (ll: LineLeaf, s: number, len: number) => boolean, rangeStart: number, rangeEnd?: number) {
if (!rangeEnd) {
rangeEnd = this.root.charCount();
}
var walkFns = {
goSubtree: true,
done: false,
leaf: function (relativeStart: number, relativeLength: number, ll: LineLeaf) {
if (!f(ll, relativeStart, relativeLength)) {
this.done = true;
}
}
}
this.walk(rangeStart, rangeEnd - rangeStart, walkFns);
return !walkFns.done;
}
edit(pos: number, deleteLength: number, newText?: string) {
function editFlat(source: string, s: number, dl: number, nt = "") {
return source.substring(0, s) + nt + source.substring(s + dl, source.length);
}
if (this.root.charCount() === 0) {
// TODO: assert deleteLength === 0
if (newText) {
this.load(LineIndex.linesFromText(newText).lines);
return this;
}
}
else {
if (this.checkEdits) {
var checkText = editFlat(this.getText(0, this.root.charCount()), pos, deleteLength, newText);
}
var walker = new EditWalker();
if (pos >= this.root.charCount()) {
// insert at end
pos = this.root.charCount() - 1;
var endString = this.getText(pos, 1);
if (newText) {
newText = endString + newText;
}
else {
newText = endString;
}
deleteLength = 0;
walker.suppressTrailingText = true;
}
else if (deleteLength > 0) {
// check whether last characters deleted are line break
var e = pos + deleteLength;
var lineInfo = this.charOffsetToLineNumberAndPos(e);
if ((lineInfo && (lineInfo.offset === 0))) {
// move range end just past line that will merge with previous line
deleteLength += lineInfo.text.length;
// store text by appending to end of insertedText
if (newText) {
newText = newText + lineInfo.text;
}
else {
newText = lineInfo.text;
}
}
}
if (pos < this.root.charCount()) {
this.root.walk(pos, deleteLength, walker);
walker.insertLines(newText);
}
if (this.checkEdits) {
var updatedText = this.getText(0, this.root.charCount());
Debug.assert(checkText == updatedText, "buffer edit mismatch");
}
return walker.lineIndex;
}
}
static buildTreeFromBottom(nodes: LineCollection[]): LineNode {
var nodeCount = Math.ceil(nodes.length / lineCollectionCapacity);
var interiorNodes: LineNode[] = [];
var nodeIndex = 0;
for (var i = 0; i < nodeCount; i++) {
interiorNodes[i] = new LineNode();
var charCount = 0;
var lineCount = 0;
for (var j = 0; j < lineCollectionCapacity; j++) {
if (nodeIndex < nodes.length) {
interiorNodes[i].add(nodes[nodeIndex]);
charCount += nodes[nodeIndex].charCount();
lineCount += nodes[nodeIndex].lineCount();
}
else {
break;
}
nodeIndex++;
}
interiorNodes[i].totalChars = charCount;
interiorNodes[i].totalLines = lineCount;
}
if (interiorNodes.length === 1) {
return interiorNodes[0];
}
else {
return this.buildTreeFromBottom(interiorNodes);
}
}
static linesFromText(text: string) {
var lineStarts = ts.computeLineStarts(text);
if (lineStarts.length === 0) {
return { lines: <string[]>[], lineMap: lineStarts };
}
var lines = <string[]>new Array(lineStarts.length);
var lc = lineStarts.length - 1;
for (var lmi = 0; lmi < lc; lmi++) {
lines[lmi] = text.substring(lineStarts[lmi], lineStarts[lmi + 1]);
}
var endText = text.substring(lineStarts[lc]);
if (endText.length > 0) {
lines[lc] = endText;
}
else {
lines.length--;
}
return { lines: lines, lineMap: lineStarts };
}
}
export class LineNode implements LineCollection {
totalChars = 0;
totalLines = 0;
children: LineCollection[] = [];
isLeaf() {
return false;
}
updateCounts() {
this.totalChars = 0;
this.totalLines = 0;
for (var i = 0, len = this.children.length; i < len; i++) {
var child = this.children[i];
this.totalChars += child.charCount();
this.totalLines += child.lineCount();
}
}
execWalk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker, childIndex: number, nodeType: CharRangeSection) {
if (walkFns.pre) {
walkFns.pre(rangeStart, rangeLength, this.children[childIndex], this, nodeType);
}
if (walkFns.goSubtree) {
this.children[childIndex].walk(rangeStart, rangeLength, walkFns);
if (walkFns.post) {
walkFns.post(rangeStart, rangeLength, this.children[childIndex], this, nodeType);
}
}
else {
walkFns.goSubtree = true;
}
return walkFns.done;
}
skipChild(relativeStart: number, relativeLength: number, childIndex: number, walkFns: ILineIndexWalker, nodeType: CharRangeSection) {
if (walkFns.pre && (!walkFns.done)) {
walkFns.pre(relativeStart, relativeLength, this.children[childIndex], this, nodeType);
walkFns.goSubtree = true;
}
}
walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker) {
// assume (rangeStart < this.totalChars) && (rangeLength <= this.totalChars)
var childIndex = 0;
var child = this.children[0];
var childCharCount = child.charCount();
// find sub-tree containing start
var adjustedStart = rangeStart;
while (adjustedStart >= childCharCount) {
this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, CharRangeSection.PreStart);
adjustedStart -= childCharCount;
child = this.children[++childIndex];
childCharCount = child.charCount();
}
// Case I: both start and end of range in same subtree
if ((adjustedStart + rangeLength) <= childCharCount) {
if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, CharRangeSection.Entire)) {
return;
}
}
else {
// Case II: start and end of range in different subtrees (possibly with subtrees in the middle)
if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, CharRangeSection.Start)) {
return;
}
var adjustedLength = rangeLength - (childCharCount - adjustedStart);
child = this.children[++childIndex];
childCharCount = child.charCount();
while (adjustedLength > childCharCount) {
if (this.execWalk(0, childCharCount, walkFns, childIndex, CharRangeSection.Mid)) {
return;
}
adjustedLength -= childCharCount;
child = this.children[++childIndex];
childCharCount = child.charCount();
}
if (adjustedLength > 0) {
if (this.execWalk(0, adjustedLength, walkFns, childIndex, CharRangeSection.End)) {
return;
}
}
}
// Process any subtrees after the one containing range end
if (walkFns.pre) {
var clen = this.children.length;
if (childIndex < (clen - 1)) {
for (var ej = childIndex + 1; ej < clen; ej++) {
this.skipChild(0, 0, ej, walkFns, CharRangeSection.PostEnd);
}
}
}
}
charOffsetToLineNumberAndPos(lineNumber: number, charOffset: number): ILineInfo {
var childInfo = this.childFromCharOffset(lineNumber, charOffset);
if (!childInfo.child) {
return {
line: lineNumber,
offset: charOffset,
}
}
else if (childInfo.childIndex < this.children.length) {
if (childInfo.child.isLeaf()) {
return {
line: childInfo.lineNumber,
offset: childInfo.charOffset,
text: (<LineLeaf>(childInfo.child)).text,
leaf: (<LineLeaf>(childInfo.child))
};
}
else {
var lineNode = <LineNode>(childInfo.child);
return lineNode.charOffsetToLineNumberAndPos(childInfo.lineNumber, childInfo.charOffset);
}
}
else {
var lineInfo = this.lineNumberToInfo(this.lineCount(), 0);
return { line: this.lineCount(), offset: lineInfo.leaf.charCount() };
}
}
lineNumberToInfo(lineNumber: number, charOffset: number): ILineInfo {
var childInfo = this.childFromLineNumber(lineNumber, charOffset);
if (!childInfo.child) {
return {
line: lineNumber,
offset: charOffset
}
}
else if (childInfo.child.isLeaf()) {
return {
line: lineNumber,
offset: childInfo.charOffset,
text: (<LineLeaf>(childInfo.child)).text,
leaf: (<LineLeaf>(childInfo.child))
}
}
else {
var lineNode = <LineNode>(childInfo.child);
return lineNode.lineNumberToInfo(childInfo.relativeLineNumber, childInfo.charOffset);
}
}
childFromLineNumber(lineNumber: number, charOffset: number) {
var child: LineCollection;
var relativeLineNumber = lineNumber;
for (var i = 0, len = this.children.length; i < len; i++) {
child = this.children[i];
var childLineCount = child.lineCount();
if (childLineCount >= relativeLineNumber) {
break;
}
else {
relativeLineNumber -= childLineCount;
charOffset += child.charCount();
}
}
return {
child: child,
childIndex: i,
relativeLineNumber: relativeLineNumber,
charOffset: charOffset
};
}
childFromCharOffset(lineNumber: number, charOffset: number) {
var child: LineCollection;
for (var i = 0, len = this.children.length; i < len; i++) {
child = this.children[i];
if (child.charCount() > charOffset) {
break;
}
else {
charOffset -= child.charCount();
lineNumber += child.lineCount();
}
}
return {
child: child,
childIndex: i,
charOffset: charOffset,
lineNumber: lineNumber
}
}
splitAfter(childIndex: number) {
var splitNode: LineNode;
var clen = this.children.length;
childIndex++;
var endLength = childIndex;
if (childIndex < clen) {
splitNode = new LineNode();
while (childIndex < clen) {
splitNode.add(this.children[childIndex++]);
}
splitNode.updateCounts();
}
this.children.length = endLength;
return splitNode;
}
remove(child: LineCollection) {
var childIndex = this.findChildIndex(child);
var clen = this.children.length;
if (childIndex < (clen - 1)) {
for (var i = childIndex; i < (clen - 1); i++) {
this.children[i] = this.children[i + 1];
}
}
this.children.length--;
}
findChildIndex(child: LineCollection) {
var childIndex = 0;
var clen = this.children.length;
while ((this.children[childIndex] !== child) && (childIndex < clen)) childIndex++;
return childIndex;
}
insertAt(child: LineCollection, nodes: LineCollection[]) {
var childIndex = this.findChildIndex(child);
var clen = this.children.length;
var nodeCount = nodes.length;
// if child is last and there is more room and only one node to place, place it
if ((clen < lineCollectionCapacity) && (childIndex === (clen - 1)) && (nodeCount === 1)) {
this.add(nodes[0]);
this.updateCounts();
return [];
}
else {
var shiftNode = this.splitAfter(childIndex);
var nodeIndex = 0;
childIndex++;
while ((childIndex < lineCollectionCapacity) && (nodeIndex < nodeCount)) {
this.children[childIndex++] = nodes[nodeIndex++];
}
var splitNodes: LineNode[] = [];
var splitNodeCount = 0;
if (nodeIndex < nodeCount) {
splitNodeCount = Math.ceil((nodeCount - nodeIndex) / lineCollectionCapacity);
splitNodes = <LineNode[]>new Array(splitNodeCount);
var splitNodeIndex = 0;
for (var i = 0; i < splitNodeCount; i++) {
splitNodes[i] = new LineNode();
}
var splitNode = <LineNode>splitNodes[0];
while (nodeIndex < nodeCount) {
splitNode.add(nodes[nodeIndex++]);
if (splitNode.children.length === lineCollectionCapacity) {
splitNodeIndex++;
splitNode = <LineNode>splitNodes[splitNodeIndex];
}
}
for (i = splitNodes.length - 1; i >= 0; i--) {
if (splitNodes[i].children.length === 0) {
splitNodes.length--;
}
}
}
if (shiftNode) {
splitNodes[splitNodes.length] = shiftNode;
}
this.updateCounts();
for (i = 0; i < splitNodeCount; i++) {
(<LineNode>splitNodes[i]).updateCounts();
}
return splitNodes;
}
}
// assume there is room for the item; return true if more room
add(collection: LineCollection) {
this.children[this.children.length] = collection;
return (this.children.length < lineCollectionCapacity);
}
charCount() {
return this.totalChars;
}
lineCount() {
return this.totalLines;
}
}
export class LineLeaf implements LineCollection {
udata: any;
constructor(public text: string) {
}
setUdata(data: any) {
this.udata = data;
}
getUdata() {
return this.udata;
}
isLeaf() {
return true;
}
walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker) {
walkFns.leaf(rangeStart, rangeLength, this);
}
charCount() {
return this.text.length;
}
lineCount() {
return 1;
}
}
}
| apache-2.0 |
superm1a3/mamute | src/test/java/org/mamute/validators/UrlValidatorTest.java | 1076 | package org.mamute.validators;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.mamute.validators.UrlValidator;
import br.com.caelum.vraptor.environment.Environment;
public class UrlValidatorTest {
private Environment env;
@Before
public void setup() {
env = mock(Environment.class);
when(env.get("host")).thenReturn("http://localhost:8080/");
}
@Test
public void should_check_url_outside_domain() throws Exception {
UrlValidator urlValidator = new UrlValidator(env);
assertFalse(urlValidator.isValid("http://mamutee.org/login"));
}
@Test
public void should_check_url_inside_domain() throws Exception {
UrlValidator urlValidator = new UrlValidator(env);
assertTrue(urlValidator.isValid("http://localhost:8080/perguntas/lala"));
assertTrue(urlValidator.isValid("http://localhost:8080/"));
assertTrue(urlValidator.isValid("http://localhost:8080/facebook"));
}
}
| apache-2.0 |
dotty-staging/dotty | tests/pos/duplicate-parents.scala | 328 | case class Foo1(x: Int) extends Serializable
case class Foo2(x: Int) extends scala.Serializable
case class Foo3(x: Int) extends Product
case object Foo4 extends Serializable
object Scope {
class Serializable
case class Foo5(x: Int) extends Serializable
val f = Foo5(1)
f: Scope.Serializable
f: scala.Serializable
}
| apache-2.0 |
tunneln/CarnotKE | jyhton/src/org/python/core/PyPropertyDerived.java | 39268 | /* Generated file, do not modify. See jython/src/templates/gderived.py. */
package org.python.core;
import java.io.Serializable;
import org.python.core.finalization.FinalizeTrigger;
import org.python.core.finalization.FinalizablePyObjectDerived;
public class PyPropertyDerived extends PyProperty implements Slotted,FinalizablePyObjectDerived,TraverseprocDerived {
public PyObject getSlot(int index) {
return slots[index];
}
public void setSlot(int index,PyObject value) {
slots[index]=value;
}
private PyObject[]slots;
public void __del_derived__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__del__");
if (impl!=null) {
impl.__get__(this,self_type).__call__();
}
}
public void __ensure_finalizer__() {
FinalizeTrigger.ensureFinalizer(this);
}
/* TraverseprocDerived implementation */
public int traverseDerived(Visitproc visit,Object arg) {
int retVal;
for(int i=0;i<slots.length;++i) {
if (slots[i]!=null) {
retVal=visit.visit(slots[i],arg);
if (retVal!=0) {
return retVal;
}
}
}
retVal=visit.visit(objtype,arg);
return retVal!=0?retVal:traverseDictIfAny(visit,arg);
}
/* end of TraverseprocDerived implementation */
private PyObject dict;
public PyObject fastGetDict() {
return dict;
}
public PyObject getDict() {
return dict;
}
public void setDict(PyObject newDict) {
if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) {
dict=newDict;
if (dict.__finditem__(PyString.fromInterned("__del__"))!=null&&!JyAttribute.hasAttr(this,JyAttribute.FINALIZE_TRIGGER_ATTR)) {
FinalizeTrigger.ensureFinalizer(this);
}
} else {
throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName());
}
}
public void delDict() {
// deleting an object's instance dict makes it grow a new one
dict=new PyStringMap();
}
public PyPropertyDerived(PyType subtype) {
super(subtype);
slots=new PyObject[subtype.getNumSlots()];
dict=subtype.instDict();
if (subtype.needsFinalizer()) {
FinalizeTrigger.ensureFinalizer(this);
}
}
public int traverseDictIfAny(Visitproc visit,Object arg) {
return visit.visit(dict,arg);
}
public PyString __str__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__str__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__();
if (res instanceof PyString)
return(PyString)res;
throw Py.TypeError("__str__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")");
}
return super.__str__();
}
public PyString __repr__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__repr__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__();
if (res instanceof PyString)
return(PyString)res;
throw Py.TypeError("__repr__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")");
}
return super.__repr__();
}
public PyString __hex__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__hex__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__();
if (res instanceof PyString)
return(PyString)res;
throw Py.TypeError("__hex__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")");
}
return super.__hex__();
}
public PyString __oct__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__oct__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__();
if (res instanceof PyString)
return(PyString)res;
throw Py.TypeError("__oct__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")");
}
return super.__oct__();
}
public PyFloat __float__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__float__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__();
if (res instanceof PyFloat)
return(PyFloat)res;
throw Py.TypeError("__float__"+" returned non-"+"float"+" (type "+res.getType().fastGetName()+")");
}
return super.__float__();
}
public PyComplex __complex__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__complex__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__();
if (res instanceof PyComplex)
return(PyComplex)res;
throw Py.TypeError("__complex__"+" returned non-"+"complex"+" (type "+res.getType().fastGetName()+")");
}
return super.__complex__();
}
public PyObject __pos__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__pos__");
if (impl!=null)
return impl.__get__(this,self_type).__call__();
return super.__pos__();
}
public PyObject __neg__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__neg__");
if (impl!=null)
return impl.__get__(this,self_type).__call__();
return super.__neg__();
}
public PyObject __abs__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__abs__");
if (impl!=null)
return impl.__get__(this,self_type).__call__();
return super.__abs__();
}
public PyObject __invert__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__invert__");
if (impl!=null)
return impl.__get__(this,self_type).__call__();
return super.__invert__();
}
public PyObject __reduce__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__reduce__");
if (impl!=null)
return impl.__get__(this,self_type).__call__();
return super.__reduce__();
}
public PyObject __dir__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__dir__");
if (impl!=null)
return impl.__get__(this,self_type).__call__();
return super.__dir__();
}
public PyObject __add__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__add__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__add__(other);
}
public PyObject __radd__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__radd__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__radd__(other);
}
public PyObject __sub__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__sub__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__sub__(other);
}
public PyObject __rsub__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__rsub__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__rsub__(other);
}
public PyObject __mul__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__mul__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__mul__(other);
}
public PyObject __rmul__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__rmul__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__rmul__(other);
}
public PyObject __div__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__div__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__div__(other);
}
public PyObject __rdiv__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__rdiv__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__rdiv__(other);
}
public PyObject __floordiv__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__floordiv__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__floordiv__(other);
}
public PyObject __rfloordiv__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__rfloordiv__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__rfloordiv__(other);
}
public PyObject __truediv__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__truediv__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__truediv__(other);
}
public PyObject __rtruediv__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__rtruediv__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__rtruediv__(other);
}
public PyObject __mod__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__mod__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__mod__(other);
}
public PyObject __rmod__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__rmod__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__rmod__(other);
}
public PyObject __divmod__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__divmod__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__divmod__(other);
}
public PyObject __rdivmod__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__rdivmod__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__rdivmod__(other);
}
public PyObject __rpow__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__rpow__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__rpow__(other);
}
public PyObject __lshift__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__lshift__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__lshift__(other);
}
public PyObject __rlshift__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__rlshift__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__rlshift__(other);
}
public PyObject __rshift__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__rshift__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__rshift__(other);
}
public PyObject __rrshift__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__rrshift__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__rrshift__(other);
}
public PyObject __and__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__and__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__and__(other);
}
public PyObject __rand__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__rand__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__rand__(other);
}
public PyObject __or__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__or__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__or__(other);
}
public PyObject __ror__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__ror__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__ror__(other);
}
public PyObject __xor__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__xor__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__xor__(other);
}
public PyObject __rxor__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__rxor__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__rxor__(other);
}
public PyObject __lt__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__lt__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__lt__(other);
}
public PyObject __le__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__le__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__le__(other);
}
public PyObject __gt__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__gt__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__gt__(other);
}
public PyObject __ge__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__ge__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__ge__(other);
}
public PyObject __eq__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__eq__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__eq__(other);
}
public PyObject __ne__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__ne__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__ne__(other);
}
public PyObject __format__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__format__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__format__(other);
}
public PyObject __iadd__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__iadd__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__iadd__(other);
}
public PyObject __isub__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__isub__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__isub__(other);
}
public PyObject __imul__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__imul__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__imul__(other);
}
public PyObject __idiv__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__idiv__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__idiv__(other);
}
public PyObject __ifloordiv__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__ifloordiv__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__ifloordiv__(other);
}
public PyObject __itruediv__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__itruediv__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__itruediv__(other);
}
public PyObject __imod__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__imod__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__imod__(other);
}
public PyObject __ipow__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__ipow__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__ipow__(other);
}
public PyObject __ilshift__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__ilshift__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__ilshift__(other);
}
public PyObject __irshift__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__irshift__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__irshift__(other);
}
public PyObject __iand__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__iand__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__iand__(other);
}
public PyObject __ior__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__ior__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__ior__(other);
}
public PyObject __ixor__(PyObject other) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__ixor__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__ixor__(other);
}
public PyObject __int__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__int__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__();
if (res instanceof PyInteger||res instanceof PyLong)
return res;
throw Py.TypeError("__int__"+" should return an integer");
}
return super.__int__();
}
public PyObject __long__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__long__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__();
if (res instanceof PyLong||res instanceof PyInteger)
return res;
throw Py.TypeError("__long__"+" returned non-"+"long"+" (type "+res.getType().fastGetName()+")");
}
return super.__long__();
}
public int hashCode() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__hash__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__();
if (res instanceof PyInteger) {
return((PyInteger)res).getValue();
} else
if (res instanceof PyLong) {
return((PyLong)res).getValue().intValue();
}
throw Py.TypeError("__hash__ should return a int");
}
if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) {
throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName()));
}
return super.hashCode();
}
public PyUnicode __unicode__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__unicode__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__();
if (res instanceof PyUnicode)
return(PyUnicode)res;
if (res instanceof PyString)
return new PyUnicode((PyString)res);
throw Py.TypeError("__unicode__"+" should return a "+"unicode");
}
return super.__unicode__();
}
public int __cmp__(PyObject other) {
PyType self_type=getType();
PyObject[]where_type=new PyObject[1];
PyObject impl=self_type.lookup_where("__cmp__",where_type);
// Full Compatibility with CPython __cmp__:
// If the derived type don't override __cmp__, the
// *internal* super().__cmp__ should be called, not the
// exposed one. The difference is that the exposed __cmp__
// throws a TypeError if the argument is an instance of the same type.
if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) {
return super.__cmp__(other);
}
PyObject res=impl.__get__(this,self_type).__call__(other);
if (res==Py.NotImplemented) {
return-2;
}
int c=res.asInt();
return c<0?-1:c>0?1:0;
}
public boolean __nonzero__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__nonzero__");
if (impl==null) {
impl=self_type.lookup("__len__");
if (impl==null)
return super.__nonzero__();
}
PyObject o=impl.__get__(this,self_type).__call__();
Class c=o.getClass();
if (c!=PyInteger.class&&c!=PyBoolean.class) {
throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName()));
}
return o.__nonzero__();
}
public boolean __contains__(PyObject o) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__contains__");
if (impl==null)
return super.__contains__(o);
return impl.__get__(this,self_type).__call__(o).__nonzero__();
}
public int __len__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__len__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__();
return res.asInt();
}
return super.__len__();
}
public PyObject __iter__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__iter__");
if (impl!=null)
return impl.__get__(this,self_type).__call__();
impl=self_type.lookup("__getitem__");
if (impl==null)
return super.__iter__();
return new PySequenceIter(this);
}
public PyObject __iternext__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("next");
if (impl!=null) {
try {
return impl.__get__(this,self_type).__call__();
} catch (PyException exc) {
if (exc.match(Py.StopIteration))
return null;
throw exc;
}
}
return super.__iternext__(); // ???
}
public PyObject __finditem__(PyObject key) { // ???
PyType self_type=getType();
PyObject impl=self_type.lookup("__getitem__");
if (impl!=null)
try {
return impl.__get__(this,self_type).__call__(key);
} catch (PyException exc) {
if (exc.match(Py.LookupError))
return null;
throw exc;
}
return super.__finditem__(key);
}
public PyObject __finditem__(int key) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__getitem__");
if (impl!=null)
try {
return impl.__get__(this,self_type).__call__(new PyInteger(key));
} catch (PyException exc) {
if (exc.match(Py.LookupError))
return null;
throw exc;
}
return super.__finditem__(key);
}
public PyObject __getitem__(PyObject key) {
// Same as __finditem__, without swallowing LookupErrors. This allows
// __getitem__ implementations written in Python to raise custom
// exceptions (such as subclasses of KeyError).
//
// We are forced to duplicate the code, instead of defining __finditem__
// in terms of __getitem__. That's because PyObject defines __getitem__
// in terms of __finditem__. Therefore, we would end with an infinite
// loop when self_type.lookup("__getitem__") returns null:
//
// __getitem__ -> super.__getitem__ -> __finditem__ -> __getitem__
//
// By duplicating the (short) lookup and call code, we are safe, because
// the call chains will be:
//
// __finditem__ -> super.__finditem__
//
// __getitem__ -> super.__getitem__ -> __finditem__ -> super.__finditem__
PyType self_type=getType();
PyObject impl=self_type.lookup("__getitem__");
if (impl!=null)
return impl.__get__(this,self_type).__call__(key);
return super.__getitem__(key);
}
public void __setitem__(PyObject key,PyObject value) { // ???
PyType self_type=getType();
PyObject impl=self_type.lookup("__setitem__");
if (impl!=null) {
impl.__get__(this,self_type).__call__(key,value);
return;
}
super.__setitem__(key,value);
}
public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ???
if (step!=null) {
return __getitem__(new PySlice(start,stop,step));
}
PyType self_type=getType();
PyObject impl=self_type.lookup("__getslice__");
if (impl!=null) {
PyObject[]indices=PySlice.indices2(this,start,stop);
return impl.__get__(this,self_type).__call__(indices[0],indices[1]);
}
return super.__getslice__(start,stop,step);
}
public void __setslice__(PyObject start,PyObject stop,PyObject step,PyObject value) {
if (step!=null) {
__setitem__(new PySlice(start,stop,step),value);
return;
}
PyType self_type=getType();
PyObject impl=self_type.lookup("__setslice__");
if (impl!=null) {
PyObject[]indices=PySlice.indices2(this,start,stop);
impl.__get__(this,self_type).__call__(indices[0],indices[1],value);
return;
}
super.__setslice__(start,stop,step,value);
}
public void __delslice__(PyObject start,PyObject stop,PyObject step) {
if (step!=null) {
__delitem__(new PySlice(start,stop,step));
return;
}
PyType self_type=getType();
PyObject impl=self_type.lookup("__delslice__");
if (impl!=null) {
PyObject[]indices=PySlice.indices2(this,start,stop);
impl.__get__(this,self_type).__call__(indices[0],indices[1]);
return;
}
super.__delslice__(start,stop,step);
}
public void __delitem__(PyObject key) { // ???
PyType self_type=getType();
PyObject impl=self_type.lookup("__delitem__");
if (impl!=null) {
impl.__get__(this,self_type).__call__(key);
return;
}
super.__delitem__(key);
}
public PyObject __call__(PyObject args[],String keywords[]) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__call__");
if (impl!=null) {
return impl.__get__(this,self_type).__call__(args,keywords);
}
return super.__call__(args,keywords);
}
public PyObject __findattr_ex__(String name) {
return Deriveds.__findattr_ex__(this,name);
}
public void __setattr__(String name,PyObject value) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__setattr__");
if (impl!=null) {
impl.__get__(this,self_type).__call__(PyString.fromInterned(name),value);
//CPython does not support instance-acquired finalizers.
//So we don't check for __del__ here.
return;
}
super.__setattr__(name,value);
}
public void __delattr__(String name) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__delattr__");
if (impl!=null) {
impl.__get__(this,self_type).__call__(PyString.fromInterned(name));
return;
}
super.__delattr__(name);
}
public PyObject __get__(PyObject obj,PyObject type) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__get__");
if (impl!=null) {
if (obj==null)
obj=Py.None;
if (type==null)
type=Py.None;
return impl.__get__(this,self_type).__call__(obj,type);
}
return super.__get__(obj,type);
}
public void __set__(PyObject obj,PyObject value) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__set__");
if (impl!=null) {
impl.__get__(this,self_type).__call__(obj,value);
return;
}
super.__set__(obj,value);
}
public void __delete__(PyObject obj) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__delete__");
if (impl!=null) {
impl.__get__(this,self_type).__call__(obj);
return;
}
super.__delete__(obj);
}
public PyObject __pow__(PyObject other,PyObject modulo) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__pow__");
if (impl!=null) {
PyObject res;
if (modulo==null) {
res=impl.__get__(this,self_type).__call__(other);
} else {
res=impl.__get__(this,self_type).__call__(other,modulo);
}
if (res==Py.NotImplemented)
return null;
return res;
}
return super.__pow__(other,modulo);
}
public void dispatch__init__(PyObject[]args,String[]keywords) {
Deriveds.dispatch__init__(this,args,keywords);
}
public PyObject __index__() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__index__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__();
if (res instanceof PyInteger||res instanceof PyLong) {
return res;
}
throw Py.TypeError(String.format("__index__ returned non-(int,long) (type %s)",res.getType().fastGetName()));
}
return super.__index__();
}
public Object __tojava__(Class c) {
// If we are not being asked by the "default" conversion to java, then
// we can provide this as the result, as long as it is a instance of the
// specified class. Without this, derived.__tojava__(PyObject.class)
// would broke. (And that's not pure speculation: PyReflectedFunction's
// ReflectedArgs asks for things like that).
if ((c!=Object.class)&&(c!=Serializable.class)&&(c.isInstance(this))) {
return this;
}
// Otherwise, we call the derived __tojava__, if it exists:
PyType self_type=getType();
PyObject impl=self_type.lookup("__tojava__");
if (impl!=null) {
PyObject delegate=impl.__get__(this,self_type).__call__(Py.java2py(c));
if (delegate!=this)
return delegate.__tojava__(Object.class);
}
return super.__tojava__(c);
}
public Object __coerce_ex__(PyObject o) {
PyType self_type=getType();
PyObject impl=self_type.lookup("__coerce__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__(o);
if (res==Py.NotImplemented)
return Py.None;
if (!(res instanceof PyTuple))
throw Py.TypeError("__coerce__ didn't return a 2-tuple");
return((PyTuple)res).getArray();
}
return super.__coerce_ex__(o);
}
public String toString() {
PyType self_type=getType();
PyObject impl=self_type.lookup("__repr__");
if (impl!=null) {
PyObject res=impl.__get__(this,self_type).__call__();
if (!(res instanceof PyString))
throw Py.TypeError("__repr__ returned non-string (type "+res.getType().fastGetName()+")");
return((PyString)res).toString();
}
return super.toString();
}
}
| apache-2.0 |
jmluy/elasticsearch | server/src/main/java/org/elasticsearch/action/admin/indices/forcemerge/ForceMergeRequestBuilder.java | 2104 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.action.admin.indices.forcemerge;
import org.elasticsearch.action.support.broadcast.BroadcastOperationRequestBuilder;
import org.elasticsearch.client.ElasticsearchClient;
/**
* A request to force merge one or more indices. In order to force merge all
* indices, pass an empty array or {@code null} for the indices.
* {@link #setMaxNumSegments(int)} allows to control the number of segments to force
* merge down to. By default, will cause the force merge process to merge down
* to half the configured number of segments.
*/
public class ForceMergeRequestBuilder extends BroadcastOperationRequestBuilder<
ForceMergeRequest,
ForceMergeResponse,
ForceMergeRequestBuilder> {
public ForceMergeRequestBuilder(ElasticsearchClient client, ForceMergeAction action) {
super(client, action, new ForceMergeRequest());
}
/**
* Will force merge the index down to <= maxNumSegments. By default, will
* cause the merge process to merge down to half the configured number of
* segments.
*/
public ForceMergeRequestBuilder setMaxNumSegments(int maxNumSegments) {
request.maxNumSegments(maxNumSegments);
return this;
}
/**
* Should the merge only expunge deletes from the index, without full merging.
* Defaults to full merging ({@code false}).
*/
public ForceMergeRequestBuilder setOnlyExpungeDeletes(boolean onlyExpungeDeletes) {
request.onlyExpungeDeletes(onlyExpungeDeletes);
return this;
}
/**
* Should flush be performed after the merge. Defaults to {@code true}.
*/
public ForceMergeRequestBuilder setFlush(boolean flush) {
request.flush(flush);
return this;
}
}
| apache-2.0 |
dotunolafunmiloye/owf-framework | web-app/js-lib/dojo-release-1.5.0-src/dojox/grid/enhanced/_Plugin.js | 12763 | dojo.provide("dojox.grid.enhanced._Plugin");
dojo.require("dojox.grid.enhanced._Builder");
dojo.require("dojox.grid.enhanced._Events");
dojo.declare("dojox.grid.enhanced._Plugin", null, {
// summary:
// Singleton plugin manager
//
// description:
// Plugin manager is responsible for
// 1. Loading required plugins
// 2. Handling collaboration and dependencies among plugins
// 3. Overwriting some default behavior of DataGrid
//
// Note: Mixin and method caching are used for #3, this might be refined once
// an overall plugin architecture is set up for DataGrid.
//
// Some plugin dependencies:
// - DnD plugin depends on NestedSorting plugin
// - RowSelector should be used for DnD plugin.
// e.g. <div dojoType="dojox.grid.EnhancedGrid" plugins='{dnd: true, ...}}' rowSelector="20px" .../>
// - "columnReordering" attribute won't work when either DnD or Indirect Selections plugin is on.
//fixedCellNum: Integer
// Number of fixed cells(columns), e.g. cell(column) of indirect selection is fixed and can't be moved
fixedCellNum: -1,
//funcMap: Object
// Map for caching default DataGrid methods.
funcMap:{},
constructor: function(inGrid){
this.grid = inGrid;
this._parseProps(this.grid);
},
_parseProps: function(grid){
// summary:
// Parse plugins properties
// grid: Grid
// Grid this plugin manager belongs to
//mixin all plugin properties into Grid
grid.plugins && dojo.mixin(grid, grid.plugins);
//cell(column) of indirect selection
grid.rowSelectCell = null;
//DnD plugin depends on NestedSorting plugin
grid.dnd && (grid.nestedSorting = true);
//"columnReordering" attribute won't work when either DnD or Indirect Selections plugin is used.
(grid.dnd || grid.indirectSelection) && (grid.columnReordering = false);
},
preInit: function(){
// summary:
// Pre initialization, some plugins must be loaded before DataGrid.postCreate().
// See EnhancedGrid.postCreate()
var grid = this.grid;
//load Indirect Selection plugin
grid.indirectSelection && (new (this.getPluginClazz('dojox.grid.enhanced.plugins.IndirectSelection'))(grid));
if(grid.dnd && (!grid.rowSelector || grid.rowSelector=="false")) {
//RowSelector should be used for DnD plugin.
grid.rowSelector = "20px";
}
//overwrite header and content builders
if(grid.nestedSorting){
dojox.grid._View.prototype._headerBuilderClass = dojox.grid.enhanced._HeaderBuilder;
}
dojox.grid._View.prototype._contentBuilderClass = dojox.grid.enhanced._ContentBuilder;
},
postInit: function(){
// summary:
// Post initialization, by default, plugins are loaded after DataGrid.postCreate().
// See EnhancedGrid.postCreate()
var grid = this.grid;
//overwrite some default events of DataGrid
new dojox.grid.enhanced._Events(grid);
//load Menu plugin
grid.menus && (new (this.getPluginClazz('dojox.grid.enhanced.plugins.Menu'))(grid));
//load NestedSorting plugin
grid.nestedSorting && (new (this.getPluginClazz('dojox.grid.enhanced.plugins.NestedSorting'))(grid));
//load DnD plugin
if(grid.dnd){
grid.isDndSelectEnable = grid.dnd;
//by default disable cell selection for EnhancedGrid M1
grid.dndDisabledTypes = ["cell"];
//new dojox.grid.enhanced.dnd._DndMovingManager(grid);
new (this.getPluginClazz('dojox.grid.enhanced.plugins.DnD'))(grid);
}
//TODO - see if any better ways for this
//fix inherit issue for mixin, an null/undefined exception will be thrown from the "this.inherited(...)" in
//the following functions, like saying there is no "startup" in "this" scope
dojo.isChrome < 3 && (grid.constructor.prototype.startup = grid.startup);
//grid.constructor.prototype.onStyleRow = grid.onStyleRow;
//get fixed cell(column) number
this.fixedCellNum = this.getFixedCellNumber();
//overwrite some default methods of DataGrid by method caching
this.grid.plugins && this._bindFuncs();
},
getPluginClazz: function(clazzStr){
//summary:
// Load target plugin which must be already required (dojo.require(..))
//clazzStr: String
// Plugin class name
var clazz = dojo.getObject(clazzStr);
if(clazz){
return clazz;
}
throw new Error('Please make sure class "' + clazzStr + '" is required.');
},
isFixedCell: function(cell) {
//summary:
// See if target cell(column) is fixed or not.
//cell: Object
// Target cell(column)
//return: Boolean
// True - fixed| False - not fixed
//target cell can use Boolean attributes named "isRowSelector" or "positionFixed" to mark it's a fixed cell(column)
return cell && (cell.isRowSelector || cell.positionFixed);
},
getFixedCellNumber: function(){
//summary:
// See if target cell(column) is fixed or not.
//return: Number
// True - fixed| False - not fixed
if(this.fixedCellNum >= 0){
return this.fixedCellNum;
}
var i = 0;
dojo.forEach(this.grid.layout.cells, dojo.hitch(this, function(cell){
this.isFixedCell(cell) && (i++);
}));
return i;
},
inSingleSelection: function(){
//summary:
// See if Grid is in single selection mode
//return: Boolean
// True - in single selection mode | False - not in single selection mode
return this.grid.selectionMode && this.grid.selectionMode == 'single';
},
needUpdateRow: function(){
//summary:
// See if needed to update row. See this.updateRow()
//return: Boolean
// True - need update row | False - don't update row
//always true when either indirect selection or DnD disabled
return ((this.grid.indirectSelection || this.grid.isDndSelectEnable) ? this.grid.edit.isEditing() : true);
},
_bindFuncs: function(){
//summary:
// Overwrite some default methods of DataGrid by method caching
dojo.forEach(this.grid.views.views, dojo.hitch(this, function(view){
//add more events handler - _View
dojox.grid.util.funnelEvents(view.contentNode, view, "doContentEvent", ['mouseup', 'mousemove']);
dojox.grid.util.funnelEvents(view.headerNode, view, "doHeaderEvent", ['mouseup']);
//overwrite _View.setColumnsWidth()
this.funcMap[view.id + '-' +'setColumnsWidth'] = view.setColumnsWidth;
view.setColumnsWidth = this.setColumnsWidth;
//overwrite _View._getHeaderContent()
this.grid.nestedSorting && (view._getHeaderContent = this.grid._getNestedSortHeaderContent);
//overwrite _View.setScrollTop(),
//#10273 fix of base DataGrid seems to bring some side effects to Enhanced Grid,
//TODO - need a more close look post v.1.4 rather than simply overwrite it
this.grid.dnd && (view.setScrollTop = this.setScrollTop);
}));
//overwrite _FocusManager.nextKey()
this.funcMap['nextKey'] = this.grid.focus.nextKey;
this.grid.focus.nextKey = this.nextKey;
//overwrite _FocusManager.previousKey()
this.funcMap['previousKey'] = this.grid.focus.previousKey;
this.grid.focus.previousKey = this.previousKey;
//overwrite _Scroller.renderPage()
if(this.grid.indirectSelection){
this.funcMap['renderPage'] = this.grid.scroller.renderPage;
this.grid.scroller.renderPage = this.renderPage;
this.funcMap['measurePage'] = this.grid.scroller.measurePage;
this.grid.scroller.measurePage = this.measurePage;
}
//overwrite _Grid.updateRow()
this.funcMap['updateRow'] = this.grid.updateRow;
this.grid.updateRow = this.updateRow;
if(this.grid.nestedSorting && dojox.grid.cells._Widget){
dojox.grid.cells._Widget.prototype.sizeWidget = this.sizeWidget;
}
dojox.grid.cells._Base.prototype.getEditNode = this.getEditNode;
dojox.grid._EditManager.prototype.styleRow = function(inRow){};
},
setColumnsWidth: function(width){
//summary:
// Overwrite _View.setColumnsWidth(), "this" - _View scope
// Fix rtl issue in IE.
if(dojo.isIE && !dojo._isBodyLtr()) {
this.headerContentNode.style.width = width + 'px';
this.headerContentNode.parentNode.style.width = width + 'px';
}
//invoke _View.setColumnsWidth()
dojo.hitch(this, this.grid.pluginMgr.funcMap[this.id + '-' +'setColumnsWidth'])(width);
},
previousKey: function(e){
//summary:
// Overwrite _FocusManager.previousKey(), "this" - _FocusManager scope
var isEditing = this.grid.edit.isEditing();
if(!isEditing && !this.isNavHeader() && !this._isHeaderHidden()) {
if(!this.grid.isDndSelectEnable){
this.focusHeader();
}else{
if(!this.isRowBar()){
this.focusRowBar();
} else {
this._blurRowBar();
this.focusHeader();
}
}
dojo.stopEvent(e);
return;
}
//invoke _FocusManager.previousKey()
dojo.hitch(this, this.grid.pluginMgr.funcMap['previousKey'])(e);
},
nextKey: function(e) {
//summary:
// Overwrite _FocusManager.nextKey(), "this" - _FocusManager scope
var isEmpty = this.grid.rowCount == 0;
var isRootEvt = (e.target === this.grid.domNode);
if(!isRootEvt && this.grid.isDndSelectEnable && this.isNavHeader()){
// if tabbing from col header, then go to grid proper. If grid is empty this.grid.rowCount == 0
this._colHeadNode = this._colHeadFocusIdx= null;
this.focusRowBar();
return;
}else if(!isRootEvt && (!this.grid.isDndSelectEnable && this.isNavHeader()) || (this.grid.isDndSelectEnable && this.isRowBar())){
this._colHeadNode = this._colHeadFocusIdx= null;
if (this.grid.isDndSelectEnable) {
this._blurRowBar();
}
if(this.isNoFocusCell() && !isEmpty){
this.setFocusIndex(0, 0);
}else if(this.cell && !isEmpty){
if(this.focusView && !this.focusView.rowNodes[this.rowIndex]){
// if rowNode for current index is undefined (likely as a result of a sort and because of #7304)
// scroll to that row
this.grid.scrollToRow(this.rowIndex);
}
this.focusGrid();
}else if(!this.findAndFocusGridCell()){
this.tabOut(this.grid.lastFocusNode);
}
return;
}
//invoke _FocusManager.nextKey()
dojo.hitch(this, this.grid.pluginMgr.funcMap['nextKey'])(e);
},
renderPage: function(inPageIndex){
//summary:
// Overwrite _Scroller.renderPage(), "this" - _Scroller scope
// To add progress cursor when rendering the indirect selection cell(column) with checkbox
for(var i=0, j=inPageIndex*this.rowsPerPage; (i<this.rowsPerPage)&&(j<this.rowCount); i++, j++){}
this.grid.lastRenderingRowIdx = --j;
dojo.addClass(this.grid.domNode, 'dojoxGridSortInProgress');
//invoke _Scroller.renderPage()
dojo.hitch(this, this.grid.pluginMgr.funcMap['renderPage'])(inPageIndex);
},
measurePage: function(inPageIndex){
//summary:
// Overwrite _Scroller.measurePage(), "this" - _Scroller scope
// Fix a regression similar as #5552
// invoke _Scroller.measurePage()
var pageHeight = dojo.hitch(this, this.grid.pluginMgr.funcMap['measurePage'])(inPageIndex);
return (!dojo.isIE || this.grid.rowHeight || pageHeight > this.rowsPerPage * this.grid.minRowHeight) ? pageHeight : undefined;
},
updateRow: function(inRowIndex){
//summary:
// Overwrite _Scroller.renderPage(), "this" - _Grid scope
var caller = arguments.callee.caller;
if(caller.nom == "move" && /* caller.ctor.prototype.declaredClass == "dojox.grid._FocusManager" && */ !this.pluginMgr.needUpdateRow()){
//if is called from dojox.grid._FocusManager.move(), and no need to update row, then return
return;
}
//invoke _Grid.updateRow()
dojo.hitch(this, this.pluginMgr.funcMap['updateRow'])(inRowIndex);
},
getEditNode: function(inRowIndex) {
//summary:
// Overwrite dojox.grid.cells._Base.getEditNode, "this" - _Base scope
return ((this.getNode(inRowIndex) || 0).firstChild || 0).firstChild || 0;
},
sizeWidget: function(inNode, inDatum, inRowIndex){
//summary:
// Overwrite dojox.grid.cells._Widget.sizeWidget, "this" - _Widget scope
var p = this.getNode(inRowIndex).firstChild,
box = dojo.contentBox(p);
dojo.marginBox(this.widget.domNode, {w: box.w});
},
setScrollTop: function(inTop){
//summary:
// Overwrite dojox.grid._View.setScrollTop, "this" - _View scope
this.lastTop = inTop;
this.scrollboxNode.scrollTop = inTop;
return this.scrollboxNode.scrollTop;
},
getViewByCellIdx: function(cellIdx){
//summary:
// Find view that contains the cell with 'cellIdx'
//cellIdx: Integer
// Index of target cell
//return: Object
// Matched view
var cellMatched = function(cells){
var j = 0, matched = false;
for(; j < cells.length; j++){
if(dojo.isArray(cells[j])){
if(cellMatched(cells[j])){ return true;}
}else if(cells[j].index == cellIdx){
return true;
}
}
};
var i = 0, views = this.grid.views.views;
for(; i < views.length; i++){
cells = views[i].structure.cells;
if(cellMatched(cells)){ return views[i]; }
}
return null;
}
});
| apache-2.0 |
Teagan42/home-assistant | homeassistant/components/skybell/__init__.py | 2664 | """Support for the Skybell HD Doorbell."""
import logging
from requests.exceptions import ConnectTimeout, HTTPError
from skybellpy import Skybell
import voluptuous as vol
from homeassistant.const import ATTR_ATTRIBUTION, CONF_PASSWORD, CONF_USERNAME
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
_LOGGER = logging.getLogger(__name__)
ATTRIBUTION = "Data provided by Skybell.com"
NOTIFICATION_ID = "skybell_notification"
NOTIFICATION_TITLE = "Skybell Sensor Setup"
DOMAIN = "skybell"
DEFAULT_CACHEDB = "./skybell_cache.pickle"
DEFAULT_ENTITY_NAMESPACE = "skybell"
CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.Schema(
{
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
}
)
},
extra=vol.ALLOW_EXTRA,
)
def setup(hass, config):
"""Set up the Skybell component."""
conf = config[DOMAIN]
username = conf.get(CONF_USERNAME)
password = conf.get(CONF_PASSWORD)
try:
cache = hass.config.path(DEFAULT_CACHEDB)
skybell = Skybell(
username=username, password=password, get_devices=True, cache_path=cache
)
hass.data[DOMAIN] = skybell
except (ConnectTimeout, HTTPError) as ex:
_LOGGER.error("Unable to connect to Skybell service: %s", str(ex))
hass.components.persistent_notification.create(
"Error: {}<br />"
"You will need to restart hass after fixing."
"".format(ex),
title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID,
)
return False
return True
class SkybellDevice(Entity):
"""A HA implementation for Skybell devices."""
def __init__(self, device):
"""Initialize a sensor for Skybell device."""
self._device = device
@property
def should_poll(self):
"""Return the polling state."""
return True
def update(self):
"""Update automation state."""
self._device.refresh()
@property
def device_state_attributes(self):
"""Return the state attributes."""
return {
ATTR_ATTRIBUTION: ATTRIBUTION,
"device_id": self._device.device_id,
"status": self._device.status,
"location": self._device.location,
"wifi_ssid": self._device.wifi_ssid,
"wifi_status": self._device.wifi_status,
"last_check_in": self._device.last_check_in,
"motion_threshold": self._device.motion_threshold,
"video_profile": self._device.video_profile,
}
| apache-2.0 |
iriscouch/stew | node_modules/kanso/lib/data-stream/index.js | 146 | exports.ParseStream = require('./ParseStream');
exports.createParseStream = function createParseStream() {
return new exports.ParseStream;
}
| apache-2.0 |
vbatts/cri-o | vendor/github.com/go-zoo/bone/route.go | 5212 | /********************************
*** Multiplexer for Go ***
*** Bone is under MIT license ***
*** Code by CodingFerret ***
*** github.com/go-zoo ***
*********************************/
package bone
import (
"net/http"
"regexp"
"strings"
)
const (
//PARAM value store in Atts if the route have parameters
PARAM = 2
//SUB value store in Atts if the route is a sub router
SUB = 4
//WC value store in Atts if the route have wildcard
WC = 8
//REGEX value store in Atts if the route contains regex
REGEX = 16
)
// Route content the required information for a valid route
// Path: is the Route URL
// Size: is the length of the path
// Token: is the value of each part of the path, split by /
// Pattern: is content information about the route, if it's have a route variable
// handler: is the handler who handle this route
// Method: define HTTP method on the route
type Route struct {
Path string
Method string
Size int
Atts int
wildPos int
Token Token
Pattern map[int]string
Compile map[int]*regexp.Regexp
Tag map[int]string
Handler http.Handler
}
// Token content all value of a spliting route path
// Tokens: string value of each token
// size: number of token
type Token struct {
raw []int
Tokens []string
Size int
}
// NewRoute return a pointer to a Route instance and call save() on it
func NewRoute(url string, h http.Handler) *Route {
r := &Route{Path: url, Handler: h}
r.save()
return r
}
// Save, set automatically the the Route.Size and Route.Pattern value
func (r *Route) save() {
r.Size = len(r.Path)
r.Token.Tokens = strings.Split(r.Path, "/")
for i, s := range r.Token.Tokens {
if len(s) >= 1 {
switch s[:1] {
case ":":
if r.Pattern == nil {
r.Pattern = make(map[int]string)
}
r.Pattern[i] = s[1:]
r.Atts |= PARAM
case "#":
if r.Compile == nil {
r.Compile = make(map[int]*regexp.Regexp)
r.Tag = make(map[int]string)
}
tmp := strings.Split(s, "^")
r.Tag[i] = tmp[0][1:]
r.Compile[i] = regexp.MustCompile("^" + tmp[1][:len(tmp[1])-1])
r.Atts |= REGEX
case "*":
r.wildPos = i
r.Atts |= WC
default:
r.Token.raw = append(r.Token.raw, i)
}
}
r.Token.Size++
}
}
// Match check if the request match the route Pattern
func (r *Route) Match(req *http.Request) bool {
ok, _ := r.matchAndParse(req)
return ok
}
// matchAndParse check if the request matches the route Pattern and returns a map of the parsed
// variables if it matches
func (r *Route) matchAndParse(req *http.Request) (bool, map[string]string) {
ss := strings.Split(req.URL.EscapedPath(), "/")
if r.matchRawTokens(&ss) {
if len(ss) == r.Token.Size || r.Atts&WC != 0 {
totalSize := len(r.Pattern)
if r.Atts®EX != 0 {
totalSize += len(r.Compile)
}
vars := make(map[string]string, totalSize)
for k, v := range r.Pattern {
vars[v] = ss[k]
}
if r.Atts®EX != 0 {
for k, v := range r.Compile {
if !v.MatchString(ss[k]) {
return false, nil
}
vars[r.Tag[k]] = ss[k]
}
}
return true, vars
}
}
return false, nil
}
func (r *Route) parse(rw http.ResponseWriter, req *http.Request) bool {
if r.Atts != 0 {
if r.Atts&SUB != 0 {
if len(req.URL.Path) >= r.Size {
if req.URL.Path[:r.Size] == r.Path {
req.URL.Path = req.URL.Path[r.Size:]
r.Handler.ServeHTTP(rw, req)
return true
}
}
}
if ok, vars := r.matchAndParse(req); ok {
r.serveMatchedRequest(rw, req, vars)
return true
}
}
if req.URL.Path == r.Path {
r.Handler.ServeHTTP(rw, req)
return true
}
return false
}
func (r *Route) matchRawTokens(ss *[]string) bool {
if len(*ss) >= r.Token.Size {
for i, v := range r.Token.raw {
if (*ss)[v] != r.Token.Tokens[v] {
if r.Atts&WC != 0 && r.wildPos == i {
return true
}
return false
}
}
return true
}
return false
}
func (r *Route) exists(rw http.ResponseWriter, req *http.Request) bool {
if r.Atts != 0 {
if r.Atts&SUB != 0 {
if len(req.URL.Path) >= r.Size {
if req.URL.Path[:r.Size] == r.Path {
return true
}
}
}
if ok, _ := r.matchAndParse(req); ok {
return true
}
}
if req.URL.Path == r.Path {
return true
}
return false
}
// Get set the route method to Get
func (r *Route) Get() *Route {
r.Method = "GET"
return r
}
// Post set the route method to Post
func (r *Route) Post() *Route {
r.Method = "POST"
return r
}
// Put set the route method to Put
func (r *Route) Put() *Route {
r.Method = "PUT"
return r
}
// Delete set the route method to Delete
func (r *Route) Delete() *Route {
r.Method = "DELETE"
return r
}
// Head set the route method to Head
func (r *Route) Head() *Route {
r.Method = "HEAD"
return r
}
// Patch set the route method to Patch
func (r *Route) Patch() *Route {
r.Method = "PATCH"
return r
}
// Options set the route method to Options
func (r *Route) Options() *Route {
r.Method = "OPTIONS"
return r
}
func (r *Route) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if r.Method != "" {
if req.Method == r.Method {
r.Handler.ServeHTTP(rw, req)
return
}
http.NotFound(rw, req)
return
}
r.Handler.ServeHTTP(rw, req)
}
| apache-2.0 |
dexequiel87/zendesk-java-client | src/main/java/org/zendesk/client/v2/model/Request.java | 2431 | package org.zendesk.client.v2.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Date;
/**
* @author stephenc
* @since 09/04/2013 15:08
*/
public class Request {
protected Long id;
protected String url;
protected String subject;
protected String description;
protected Status status;
protected Ticket.Requester requester;
protected Long requesterId;
protected Long organizationId;
protected Via via;
protected Date createdAt;
protected Date updatedAt;
protected Comment comment;
@JsonProperty("created_at")
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
@JsonProperty()
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@JsonProperty("organization_id")
public Long getOrganizationId() {
return organizationId;
}
public void setOrganizationId(Long organizationId) {
this.organizationId = organizationId;
}
@JsonProperty("requester_id")
public Long getRequesterId() {
return requesterId;
}
public void setRequesterId(Long requesterId) {
this.requesterId = requesterId;
if (requesterId != null) {
this.requester = null;
}
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
@JsonProperty("updated_at")
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Via getVia() {
return via;
}
public void setVia(Via via) {
this.via = via;
}
public Comment getComment() {
return comment;
}
public void setComment(Comment comment) {
this.comment = comment;
}
}
| apache-2.0 |
tkruse/incubator-groovy | src/main/org/codehaus/groovy/transform/MemoizedASTTransformation.java | 8967 | /*
* 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.codehaus.groovy.transform;
import groovy.transform.Memoized;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.AnnotatedNode;
import org.codehaus.groovy.ast.AnnotationNode;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.expr.ClosureExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.MethodCallExpression;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.classgen.VariableScopeVisitor;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.control.SourceUnit;
import java.util.ArrayList;
import java.util.List;
import static org.codehaus.groovy.ast.ClassHelper.make;
import static org.codehaus.groovy.ast.tools.GeneralUtils.args;
import static org.codehaus.groovy.ast.tools.GeneralUtils.callThisX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.callX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.cloneParams;
import static org.codehaus.groovy.ast.tools.GeneralUtils.constX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.fieldX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.returnS;
import static org.codehaus.groovy.ast.tools.GeneralUtils.stmt;
import static org.codehaus.groovy.ast.tools.GeneralUtils.varX;
import static org.codehaus.groovy.ast.tools.GenericsUtils.newClass;
/**
* Handles generation of code for the {@link Memoized} annotation.
*
* @author Andrey Bloschetsov
*/
@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
public class MemoizedASTTransformation extends AbstractASTTransformation {
private static final String CLOSURE_CALL_METHOD_NAME = "call";
private static final Class<Memoized> MY_CLASS = Memoized.class;
private static final ClassNode MY_TYPE = make(MY_CLASS);
private static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage();
private static final String PROTECTED_CACHE_SIZE_NAME = "protectedCacheSize";
private static final String MAX_CACHE_SIZE_NAME = "maxCacheSize";
private static final String CLOSURE_LABEL = "Closure";
private static final String METHOD_LABEL = "Priv";
public void visit(ASTNode[] nodes, final SourceUnit source) {
init(nodes, source);
AnnotationNode annotationNode = (AnnotationNode) nodes[0];
AnnotatedNode annotatedNode = (AnnotatedNode) nodes[1];
if (MY_TYPE.equals(annotationNode.getClassNode()) && annotatedNode instanceof MethodNode) {
MethodNode methodNode = (MethodNode) annotatedNode;
if (methodNode.isAbstract()) {
addError("Annotation " + MY_TYPE_NAME + " cannot be used for abstract methods.", methodNode);
return;
}
if (methodNode.isVoidMethod()) {
addError("Annotation " + MY_TYPE_NAME + " cannot be used for void methods.", methodNode);
return;
}
ClassNode ownerClassNode = methodNode.getDeclaringClass();
MethodNode delegatingMethod = buildDelegatingMethod(methodNode, ownerClassNode);
ownerClassNode.addMethod(delegatingMethod);
int modifiers = FieldNode.ACC_PRIVATE | FieldNode.ACC_FINAL;
if (methodNode.isStatic()) {
modifiers = modifiers | FieldNode.ACC_STATIC;
}
int protectedCacheSize = getMemberIntValue(annotationNode, PROTECTED_CACHE_SIZE_NAME);
int maxCacheSize = getMemberIntValue(annotationNode, MAX_CACHE_SIZE_NAME);
MethodCallExpression memoizeClosureCallExpression =
buildMemoizeClosureCallExpression(delegatingMethod, protectedCacheSize, maxCacheSize);
String memoizedClosureFieldName = buildUniqueName(ownerClassNode, CLOSURE_LABEL, methodNode);
FieldNode memoizedClosureField = new FieldNode(memoizedClosureFieldName, modifiers,
newClass(ClassHelper.CLOSURE_TYPE), null, memoizeClosureCallExpression);
ownerClassNode.addField(memoizedClosureField);
BlockStatement newCode = new BlockStatement();
MethodCallExpression closureCallExpression = callX(
fieldX(memoizedClosureField), CLOSURE_CALL_METHOD_NAME, args(methodNode.getParameters()));
closureCallExpression.setImplicitThis(false);
newCode.addStatement(returnS(closureCallExpression));
methodNode.setCode(newCode);
VariableScopeVisitor visitor = new VariableScopeVisitor(source);
visitor.visitClass(ownerClassNode);
}
}
private static MethodNode buildDelegatingMethod(final MethodNode annotatedMethod, final ClassNode ownerClassNode) {
Statement code = annotatedMethod.getCode();
int access = ACC_PROTECTED;
if (annotatedMethod.isStatic()) {
access = ACC_PRIVATE | ACC_STATIC;
}
MethodNode method = new MethodNode(
buildUniqueName(ownerClassNode, METHOD_LABEL, annotatedMethod),
access,
annotatedMethod.getReturnType(),
cloneParams(annotatedMethod.getParameters()),
annotatedMethod.getExceptions(),
code
);
List<AnnotationNode> sourceAnnotations = annotatedMethod.getAnnotations();
method.addAnnotations(new ArrayList<AnnotationNode>(sourceAnnotations));
return method;
}
private static final String MEMOIZE_METHOD_NAME = "memoize";
private static final String MEMOIZE_AT_MOST_METHOD_NAME = "memoizeAtMost";
private static final String MEMOIZE_AT_LEAST_METHOD_NAME = "memoizeAtLeast";
private static final String MEMOIZE_BETWEEN_METHOD_NAME = "memoizeBetween";
private static MethodCallExpression buildMemoizeClosureCallExpression(MethodNode privateMethod,
int protectedCacheSize, int maxCacheSize) {
Parameter[] srcParams = privateMethod.getParameters();
Parameter[] newParams = cloneParams(srcParams);
List<Expression> argList = new ArrayList<Expression>(newParams.length);
for (int i = 0; i < srcParams.length; i++) {
argList.add(varX(newParams[i]));
}
ClosureExpression expression = new ClosureExpression(
newParams,
stmt(callThisX(privateMethod.getName(), args(argList)))
);
MethodCallExpression mce;
if (protectedCacheSize == 0 && maxCacheSize == 0) {
mce = callX(expression, MEMOIZE_METHOD_NAME);
} else if (protectedCacheSize == 0) {
mce = callX(expression, MEMOIZE_AT_MOST_METHOD_NAME, args(constX(maxCacheSize)));
} else if (maxCacheSize == 0) {
mce = callX(expression, MEMOIZE_AT_LEAST_METHOD_NAME, args(constX(protectedCacheSize)));
} else {
mce = callX(expression, MEMOIZE_BETWEEN_METHOD_NAME, args(constX(protectedCacheSize), constX(maxCacheSize)));
}
mce.setImplicitThis(false);
return mce;
}
private static String buildUniqueName(ClassNode owner, String ident, MethodNode methodNode) {
StringBuilder nameBuilder = new StringBuilder("memoizedMethod" + ident + "$").append(methodNode.getName());
if (methodNode.getParameters() != null) {
for (Parameter parameter : methodNode.getParameters()) {
nameBuilder.append(buildTypeName(parameter.getType()));
}
}
while (owner.getField(nameBuilder.toString()) != null) {
nameBuilder.insert(0, "_");
}
return nameBuilder.toString();
}
private static String buildTypeName(ClassNode type) {
if (type.isArray()) {
return String.format("%sArray", buildTypeName(type.getComponentType()));
}
return type.getNameWithoutPackage();
}
}
| apache-2.0 |
joprice/factorie | src/main/scala/cc/factorie/optimize/ConjugateGradient.scala | 4649 | /* Copyright (C) 2008-2014 University of Massachusetts Amherst.
This file is part of "FACTORIE" (Factor graphs, Imperative, Extensible)
http://factorie.cs.umass.edu, http://github.com/factorie
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 cc.factorie.optimize
import cc.factorie._
import cc.factorie.la._
import cc.factorie.util.FastLogging
import cc.factorie.model.{WeightsMap, WeightsSet}
/**
* A conjugate gradient optimizer. Should not be used unless you know you want it because LBFGS is often better.
* @param initialStepSize The initial step size. Not too important because line search is performed.
* @author Andrew McCallum, Alexandre Passos
*/
class ConjugateGradient(val initialStepSize: Double = 1.0) extends GradientOptimizer with FastLogging {
private var _isConverged = false
def isConverged = _isConverged
var tolerance = 0.0001
var gradientTolerance = 0.001
var maxIterations = 1000
val eps = 1.0e-10 // a small number to rectify the special case of converging to exactly zero function value
// The state of a conjugate gradient search
//var fp = 0.0
var oldValue = 0.0
var gg = 0.0
var gam = 0.0
var dgg = 0.0
var stepSize = 0.0
var xi: WeightsMap = null
var g: WeightsMap = null
var h: WeightsMap = null
var iterations = 0
var lineOptimizer: BackTrackLineOptimizer = null
def reset(): Unit = {
xi = null
_isConverged = false
}
def initializeWeights(weights: WeightsSet): Unit = { }
def finalizeWeights(weights: WeightsSet): Unit = { }
def step(weights:WeightsSet, gradient:WeightsMap, value:Double): Unit = {
if (_isConverged) return
// If this is our first time in, then initialize
if (xi eq null) {
xi = gradient.copy
g = xi.copy
h = xi.copy
stepSize = initialStepSize
}
// Take a step in the current search direction, xi
if (lineOptimizer eq null) lineOptimizer = new BackTrackLineOptimizer(gradient, xi.copy, stepSize)
lineOptimizer.step(weights, xi, value)
// If the lineOptimizer has not yet converged, then don't yet do any of the ConjugateGradient-specific things below
if (lineOptimizer.isConverged){
lineOptimizer = null // So we create a new one next time around
xi = gradient.copy
// This termination provided by "Numeric Recipes in C".
if (2.0 * math.abs(value - oldValue) <= tolerance * (math.abs(value) + math.abs(oldValue) + eps)) {
logger.info("ConjugateGradient converged: old value="+oldValue+" new value="+value+" tolerance="+tolerance)
_isConverged = true
return
}
// This termination provided by McCallum
if (xi.twoNorm < gradientTolerance) {
logger.info("ConjugateGradient converged: maximum gradient component: "+xi.twoNorm+" less than "+tolerance)
_isConverged = true
return
}
oldValue = value
// compute gamma, new g and new h
{
dgg = 0.0
gg = 0.0
val xia = xi.toArray
val ga = g.toArray
var i = 0
while (i < ga.length) {
gg += ga(i) * ga(i) // previous gradient
dgg += xia(i) * (xia(i) - ga(i)) // current gradient
i += 1
}
gam = dgg / gg
g.keys.foreach(k => g(k) := xi(k))
h.keys.foreach(k => h(k) *= gam)
h += g
assert(!h.containsNaN())
}
/* gdruck: If using the BackTrackLineSearch, then the search stops whenever
a step is found that increases the value significantly (according
to a threshold from Numerical Recipes). ConjugateGradient
assumes that line maximization finds something close
to the maximum in that direction. In tests, sometimes the
direction suggested by CG points downhill. Consequently, here I am
setting the search direction to the gradient if the slope is
negative or 0. */
// TODO Implement GradientBracketLineMaximizer (used in Numerical Recipes) which should avoid this problem!
if (xi.dot(h) > 0) xi := h else h := xi
iterations += 1
lineOptimizer = new BackTrackLineOptimizer(gradient, xi.copy, stepSize)
lineOptimizer.step(weights, xi, value)
}
}
} | apache-2.0 |
RReverser/react | src/browser/ui/dom/components/createFullPageComponent.js | 2124 | /**
* Copyright 2013-2014 Facebook, 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.
*
* @providesModule createFullPageComponent
* @typechecks
*/
"use strict";
// Defeat circular references by requiring this directly.
var ReactCompositeComponent = require('ReactCompositeComponent');
var invariant = require('invariant');
/**
* Create a component that will throw an exception when unmounted.
*
* Components like <html> <head> and <body> can't be removed or added
* easily in a cross-browser way, however it's valuable to be able to
* take advantage of React's reconciliation for styling and <title>
* management. So we just document it and throw in dangerous cases.
*
* @param {function} componentClass convenience constructor to wrap
* @return {function} convenience constructor of new component
*/
function createFullPageComponent(componentClass) {
var FullPageComponent = ReactCompositeComponent.createClass({
displayName: 'ReactFullPageComponent' + (
componentClass.type.displayName || ''
),
componentWillUnmount: function() {
invariant(
false,
'%s tried to unmount. Because of cross-browser quirks it is ' +
'impossible to unmount some top-level components (eg <html>, <head>, ' +
'and <body>) reliably and efficiently. To fix this, have a single ' +
'top-level component that never unmounts render these elements.',
this.constructor.displayName
);
},
render: function() {
return componentClass(this.props);
}
});
return FullPageComponent;
}
module.exports = createFullPageComponent;
| apache-2.0 |
dinfuehr/rust | src/test/compile-fail/empty-impl-semicolon.rs | 537 | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
impl Foo; //~ ERROR expected one of `(`, `+`, `::`, or `{`, found `;`
| apache-2.0 |
izpack/izpack | izpack-api/src/main/java/com/izforge/izpack/api/config/BasicRegistryKey.java | 2531 | /*
* IzPack - Copyright 2001-2010 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2005,2009 Ivan SZKIBA
* Copyright 2010,2011 Rene Krell
*
* 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.izforge.izpack.api.config;
import com.izforge.izpack.api.config.Registry.Key;
class BasicRegistryKey extends BasicProfileSection implements Registry.Key
{
private static final long serialVersionUID = -1390060044244350928L;
private static final String META_TYPE = "type";
public BasicRegistryKey(BasicRegistry registry, String name)
{
super(registry, name);
}
@Override
public String toString() {
String name = getName();
String[] children = childrenNames();
StringBuilder str = new StringBuilder(name + ":[");
for(String childName : children) {
str.append(childName).append(":").append(getChild(childName)).append(",");
}
str.setCharAt(str.length() - 1, ']');
return str.toString();
}
@Override public Key getChild(String key)
{
return (Key) super.getChild(key);
}
@Override public Key getParent()
{
return (Key) super.getParent();
}
@Override public Registry.Type getType(Object key)
{
return (Registry.Type) getMeta(META_TYPE, key);
}
@Override public Registry.Type getType(Object key, Registry.Type defaultType)
{
Registry.Type type = getType(key);
return (type == null) ? defaultType : type;
}
@Override public Key addChild(String key)
{
return (Key) super.addChild(key);
}
@Override public Key lookup(String... path)
{
return (Key) super.lookup(path);
}
@Override public Registry.Type putType(String key, Registry.Type type)
{
return (Registry.Type) putMeta(META_TYPE, key, type);
}
@Override public Registry.Type removeType(Object key)
{
return (Registry.Type) removeMeta(META_TYPE, key);
}
}
| apache-2.0 |
jcamachor/hive | standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/common/ZooKeeperHiveHelper.java | 15109 | /*
* 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.hive.common;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.List;
import org.apache.curator.framework.api.ACLProvider;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.nodes.PersistentNode;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryOneTime;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// The class serves three purposes (for HiveServer2 and HiveMetaStore)
// 1. An instance of this class holds ZooKeeper related configuration parameter values from Hive
// configuration and metastore configuration.
// 2. For a server which is added to ZooKeeper specified by the configuration, an instance of
// this class holds the znode corresponding to that server, zookeeper client used to watch the
// znode.
// 3. For a metastore client it provides API to find server URIs from specified ZooKeeper.
//
// We could have differentiated these three functionality into three different classes by
// including an instance of first class in the second and the third, but there's isn't much stuff
// in the first and the third.. Also note that the third functionality overlaps with
// ZooKeeperHiveClientHelper class, but that overlap is very small. So for now all the three
// functionality are bundled in a single class.
/**
* ZooKeeperHiveHelper. A helper class to hold ZooKeeper related configuration, to register and
* deregister ZooKeeper node for a given server and to fetch registered server URIs for clients.
*/
public class ZooKeeperHiveHelper {
public static final Logger LOG = LoggerFactory.getLogger(ZooKeeperHiveHelper.class.getName());
public static final String ZOOKEEPER_PATH_SEPARATOR = "/";
/**
* ZooKeeperHiveHelperBuilder. A builder class to initialize ZooKeeperHiveHelper.
*/
public static class ZooKeeperHiveHelperBuilder {
private String quorum = null;
private String clientPort = null;
private String serverRegistryNameSpace = null;
private int connectionTimeout;
private int sessionTimeout;
private int baseSleepTime;
private int maxRetries;
private boolean sslEnabled = false;
private String keyStoreLocation = null;
private String keyStorePassword = null;
private String trustStoreLocation = null;
private String trustStorePassword = null;
public ZooKeeperHiveHelper build() {
return new ZooKeeperHiveHelper(this);
}
public ZooKeeperHiveHelperBuilder quorum(String quorum) {
this.quorum = quorum;
return this;
}
public ZooKeeperHiveHelperBuilder clientPort(String clientPort) {
this.clientPort = clientPort;
return this;
}
public ZooKeeperHiveHelperBuilder serverRegistryNameSpace(String serverRegistryNameSpace) {
this.serverRegistryNameSpace = serverRegistryNameSpace;
return this;
}
public ZooKeeperHiveHelperBuilder connectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
return this;
}
public ZooKeeperHiveHelperBuilder sessionTimeout(int sessionTimeout) {
this.sessionTimeout = sessionTimeout;
return this;
}
public ZooKeeperHiveHelperBuilder baseSleepTime(int baseSleepTime) {
this.baseSleepTime = baseSleepTime;
return this;
}
public ZooKeeperHiveHelperBuilder maxRetries(int maxRetries) {
this.maxRetries = maxRetries;
return this;
}
public ZooKeeperHiveHelperBuilder sslEnabled(boolean sslEnabled) {
this.sslEnabled = sslEnabled;
return this;
}
public ZooKeeperHiveHelperBuilder keyStoreLocation(String keyStoreLocation) {
this.keyStoreLocation = keyStoreLocation;
return this;
}
public ZooKeeperHiveHelperBuilder keyStorePassword(String keyStorePassword) {
this.keyStorePassword = keyStorePassword;
return this;
}
public ZooKeeperHiveHelperBuilder trustStoreLocation(String trustStoreLocation) {
this.trustStoreLocation = trustStoreLocation;
return this;
}
public ZooKeeperHiveHelperBuilder trustStorePassword(String trustStorePassword) {
this.trustStorePassword = trustStorePassword;
return this;
}
public String getQuorum() {
return quorum;
}
public String getClientPort() {
return clientPort;
}
public String getServerRegistryNameSpace() {
return serverRegistryNameSpace;
}
public int getConnectionTimeout() {
return connectionTimeout;
}
public int getSessionTimeout() {
return sessionTimeout;
}
public int getBaseSleepTime() {
return baseSleepTime;
}
public int getMaxRetries() {
return maxRetries;
}
public boolean isSslEnabled() {
return sslEnabled;
}
public String getKeyStoreLocation() {
return keyStoreLocation;
}
public String getKeyStorePassword() {
return keyStorePassword;
}
public String getTrustStoreLocation() {
return trustStoreLocation;
}
public String getTrustStorePassword() {
return trustStorePassword;
}
}
public static ZooKeeperHiveHelper.ZooKeeperHiveHelperBuilder builder() {
return new ZooKeeperHiveHelper.ZooKeeperHiveHelperBuilder();
}
private String quorum;
private String rootNamespace;
private int connectionTimeout;
private int sessionTimeout;
private int baseSleepTime;
private int maxRetries;
private boolean sslEnabled;
private SSLZookeeperFactory sslZookeeperFactory;
private CuratorFramework zooKeeperClient;
private boolean deregisteredWithZooKeeper = false; // Set to true only when deregistration happens
private PersistentNode znode;
public ZooKeeperHiveHelper(ZooKeeperHiveHelperBuilder builder) {
// Get the ensemble server addresses in the format host1:port1, host2:port2, ... . Append
// the configured port to hostname if the hostname doesn't contain a port.
String[] hosts = builder.getQuorum().split(",");
StringBuilder quorumServers = new StringBuilder();
for (int i = 0; i < hosts.length; i++) {
quorumServers.append(hosts[i].trim());
if (!hosts[i].contains(":")) {
quorumServers.append(":");
quorumServers.append(builder.getClientPort());
}
if (i != hosts.length - 1) {
quorumServers.append(",");
}
}
this.quorum = quorumServers.toString();
this.rootNamespace = builder.getServerRegistryNameSpace();
this.connectionTimeout = builder.getConnectionTimeout();
this.sessionTimeout = builder.getSessionTimeout();
this.baseSleepTime = builder.getBaseSleepTime();
this.maxRetries = builder.getMaxRetries();
this.sslEnabled = builder.isSslEnabled();
this.sslZookeeperFactory =
new SSLZookeeperFactory(sslEnabled,
builder.getKeyStoreLocation(),
builder.getKeyStorePassword(),
builder.getTrustStoreLocation(),
builder.getTrustStorePassword());
}
/**
* Get the ensemble server addresses. The format is: host1:port, host2:port..
**/
public String getQuorumServers() {
return quorum;
}
/**
* Adds a server instance to ZooKeeper as a znode.
*
* @throws Exception
*/
public void addServerInstanceToZooKeeper(String znodePathPrefix, String znodeData,
ACLProvider zooKeeperAclProvider,
ZKDeRegisterWatcher watcher) throws Exception {
// This might be the first server getting added to the ZooKeeper, so the parent node may need
// to be created.
zooKeeperClient = startZookeeperClient(zooKeeperAclProvider, true);
// Create a znode under the rootNamespace parent for the given path prefix for a server. Also
// add a watcher to watch the znode.
try {
String pathPrefix = ZOOKEEPER_PATH_SEPARATOR + rootNamespace
+ ZOOKEEPER_PATH_SEPARATOR + znodePathPrefix;
byte[] znodeDataUTF8 = znodeData.getBytes(StandardCharsets.UTF_8);
znode =
new PersistentNode(zooKeeperClient, CreateMode.EPHEMERAL_SEQUENTIAL, false, pathPrefix, znodeDataUTF8);
znode.start();
// We'll wait for 120s for node creation
long znodeCreationTimeout = 120;
if (!znode.waitForInitialCreate(znodeCreationTimeout, TimeUnit.SECONDS)) {
throw new Exception("Max znode creation wait time: " + znodeCreationTimeout + "s exhausted");
}
setDeregisteredWithZooKeeper(false);
final String znodePath = znode.getActualPath();
if (zooKeeperClient.checkExists().usingWatcher(watcher).forPath(znodePath) == null) {
// No node exists, throw exception
throw new Exception("Unable to create znode with path prefix " + znodePathPrefix +
" and data " + znodeData + " on ZooKeeper.");
}
LOG.info("Created a znode (actual path " + znodePath + ") on ZooKeeper with path prefix " +
znodePathPrefix + " and data " + znodeData);
} catch (Exception e) {
LOG.error("Unable to create znode with path prefix " + znodePathPrefix + " and data " +
znodeData + " on ZooKeeper.", e);
if (znode != null) {
znode.close();
}
throw (e);
}
}
public CuratorFramework startZookeeperClient(ACLProvider zooKeeperAclProvider,
boolean addParentNode) throws Exception {
CuratorFramework zkClient = getNewZookeeperClient(zooKeeperAclProvider);
zkClient.start();
// Create the parent znodes recursively; ignore if the parent already exists.
if (addParentNode) {
try {
zkClient.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.PERSISTENT)
.forPath(ZooKeeperHiveHelper.ZOOKEEPER_PATH_SEPARATOR + rootNamespace);
LOG.info("Created the root name space: " + rootNamespace + " on ZooKeeper");
} catch (KeeperException e) {
if (e.code() != KeeperException.Code.NODEEXISTS) {
LOG.error("Unable to create namespace: " + rootNamespace + " on ZooKeeper", e);
throw e;
}
}
}
return zkClient;
}
public CuratorFramework getNewZookeeperClient() {
return getNewZookeeperClient(null, null);
}
public CuratorFramework getNewZookeeperClient(ACLProvider zooKeeperAclProvider) {
return getNewZookeeperClient(zooKeeperAclProvider, null);
}
public CuratorFramework getNewZookeeperClient(ACLProvider zooKeeperAclProvider, String nameSpace) {
LOG.info("Creating curator client with connectString: {} namespace: {} sessionTimeoutMs: {}" +
" connectionTimeoutMs: {} exponentialBackoff - sleepTime: {} maxRetries: {} sslEnabled: {}",
quorum, nameSpace, sessionTimeout,
connectionTimeout, baseSleepTime, maxRetries, sslEnabled);
// Create a CuratorFramework instance to be used as the ZooKeeper client.
// Use the zooKeeperAclProvider, when specified, to create appropriate ACLs.
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
.connectString(quorum)
.namespace(nameSpace)
.zookeeperFactory(this.sslZookeeperFactory);
if (connectionTimeout > 0) {
builder = builder.connectionTimeoutMs(connectionTimeout);
}
if (sessionTimeout > 0) {
builder = builder.sessionTimeoutMs(sessionTimeout);
}
if (maxRetries > 0) {
builder = builder.retryPolicy(new ExponentialBackoffRetry(baseSleepTime, maxRetries));
} else {
// Retry policy is mandatory
builder = builder.retryPolicy(new RetryOneTime(1000));
}
if (zooKeeperAclProvider != null) {
builder = builder.aclProvider(zooKeeperAclProvider);
}
return builder.build();
}
public void removeServerInstanceFromZooKeeper() throws Exception {
setDeregisteredWithZooKeeper(true);
if (znode != null) {
znode.close();
znode = null;
}
if (zooKeeperClient != null) {
zooKeeperClient.close();
}
LOG.info("Server instance removed from ZooKeeper.");
}
public void deregisterZnode() {
if (znode != null) {
try {
znode.close();
LOG.warn("This server instance with path " + znode.getActualPath() +
" is now de-registered from ZooKeeper. ");
} catch (IOException e) {
LOG.error("Failed to close the persistent ephemeral znode", e);
} finally {
setDeregisteredWithZooKeeper(true);
znode = null;
}
}
}
public synchronized boolean isDeregisteredWithZooKeeper() {
return deregisteredWithZooKeeper;
}
private synchronized void setDeregisteredWithZooKeeper(boolean deregisteredWithZooKeeper) {
this.deregisteredWithZooKeeper = deregisteredWithZooKeeper;
}
/**
* This method is supposed to be called from client code connecting to one of the servers
* managed by the configured ZooKeeper. It starts and closes its own ZooKeeper client instead
* of using the class member.
* @return list of server URIs stored under the configured zookeeper namespace
* @throws Exception
*/
public List<String> getServerUris() throws Exception {
CuratorFramework zkClient = null;
List<String> serverUris;
try {
zkClient = startZookeeperClient(null, false);
List<String> serverNodes =
zkClient.getChildren().forPath(ZOOKEEPER_PATH_SEPARATOR + rootNamespace);
serverUris = new ArrayList<String>(serverNodes.size());
for (String serverNode : serverNodes) {
byte[] serverUriBytes = zkClient.getData()
.forPath(ZOOKEEPER_PATH_SEPARATOR + rootNamespace +
ZOOKEEPER_PATH_SEPARATOR + serverNode);
serverUris.add(new String(serverUriBytes, StandardCharsets.UTF_8));
}
zkClient.close();
return serverUris;
} catch (Exception e) {
if (zkClient != null) {
zkClient.close();
}
throw e;
}
}
}
| apache-2.0 |
GunoH/intellij-community | java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ExtendsListFix.java | 7880 | /*
* Copyright 2000-2013 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.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.intention.impl.BaseIntentionAction;
import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement;
import com.intellij.codeInspection.util.IntentionName;
import com.intellij.openapi.command.undo.UndoUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class ExtendsListFix extends LocalQuickFixAndIntentionActionOnPsiElement {
private static final Logger LOG = Logger.getInstance(ExtendsListFix.class);
@Nullable
@SafeFieldForPreview // we don't modify this class
protected final SmartPsiElementPointer<PsiClass> myClassToExtendFromPointer;
private final boolean myToAdd;
@SafeFieldForPreview // we don't mo
private final PsiClassType myTypeToExtendFrom;
private final @IntentionName String myName;
public ExtendsListFix(@NotNull PsiClass aClass, @NotNull PsiClassType typeToExtendFrom, boolean toAdd) {
this(aClass, typeToExtendFrom.resolve(), typeToExtendFrom, toAdd);
}
public ExtendsListFix(@NotNull PsiClass aClass, @NotNull PsiClass classToExtendFrom, boolean toAdd) {
this(aClass, classToExtendFrom, JavaPsiFacade.getElementFactory(aClass.getProject()).createType(classToExtendFrom), toAdd);
}
private ExtendsListFix(@NotNull PsiClass aClass,
@Nullable PsiClass classToExtendFrom,
@NotNull PsiClassType typeToExtendFrom,
boolean toAdd) {
super(aClass);
myClassToExtendFromPointer = classToExtendFrom == null ? null : SmartPointerManager.createPointer(classToExtendFrom);
myToAdd = toAdd;
myTypeToExtendFrom = aClass instanceof PsiTypeParameter ? typeToExtendFrom : (PsiClassType)GenericsUtil.eliminateWildcards(typeToExtendFrom);
@NonNls final String messageKey;
if (classToExtendFrom != null && aClass.isInterface() == classToExtendFrom.isInterface()) {
messageKey = toAdd ? "add.class.to.extends.list" : "remove.class.from.extends.list";
}
else {
messageKey = toAdd ? "add.interface.to.implements.list" : "remove.interface.from.implements.list";
}
myName = QuickFixBundle.message(messageKey, aClass.getName(), classToExtendFrom == null ? "" : classToExtendFrom instanceof PsiTypeParameter ? classToExtendFrom.getName()
: classToExtendFrom.getQualifiedName());
}
@Override
@NotNull
public String getText() {
return myName;
}
@Override
@NotNull
public String getFamilyName() {
return QuickFixBundle.message("change.extends.list.family");
}
@Override
public boolean isAvailable(@NotNull Project project,
@NotNull PsiFile file,
@NotNull PsiElement startElement,
@NotNull PsiElement endElement) {
if (!myTypeToExtendFrom.isValid()) return false;
final PsiClass myClass = (PsiClass)startElement;
PsiClass classToExtendFrom = myClassToExtendFromPointer != null ? myClassToExtendFromPointer.getElement() : null;
return
BaseIntentionAction.canModify(myClass)
&& classToExtendFrom != null
&& classToExtendFrom.isValid()
&& !classToExtendFrom.hasModifierProperty(PsiModifier.FINAL)
&& (classToExtendFrom.isInterface()
|| !myClass.isInterface()
&& myClass.getExtendsList() != null
&& (myClass.getExtendsList().getReferencedTypes().length == 0) == myToAdd);
}
@Override
public void invoke(@NotNull Project project,
@NotNull PsiFile file,
@Nullable Editor editor,
@NotNull PsiElement startElement,
@NotNull PsiElement endElement) {
final PsiClass myClass = (PsiClass)startElement;
invokeImpl(myClass);
UndoUtil.markPsiFileForUndo(file);
}
protected void invokeImpl(PsiClass myClass) {
PsiClass classToExtendFrom = myClassToExtendFromPointer != null ? myClassToExtendFromPointer.getElement() : null;
PsiReferenceList extendsList = !(myClass instanceof PsiTypeParameter) && classToExtendFrom != null &&
myClass.isInterface() != classToExtendFrom.isInterface() ?
myClass.getImplementsList() : myClass.getExtendsList();
PsiReferenceList otherList = extendsList == myClass.getImplementsList() ?
myClass.getExtendsList() : myClass.getImplementsList();
try {
if (extendsList != null) {
modifyList(extendsList, myToAdd, -1);
}
if (otherList != null) {
modifyList(otherList, false, -1);
}
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
/**
* @param position to add new class to or -1 if add to the end
*/
void modifyList(@NotNull PsiReferenceList extendsList, boolean add, int position) throws IncorrectOperationException {
PsiJavaCodeReferenceElement[] referenceElements = extendsList.getReferenceElements();
boolean alreadyExtends = false;
PsiClass classToExtendFrom = myClassToExtendFromPointer != null ? myClassToExtendFromPointer.getElement() : null;
for (PsiJavaCodeReferenceElement referenceElement : referenceElements) {
if (referenceElement.getManager().areElementsEquivalent(classToExtendFrom, referenceElement.resolve())) {
alreadyExtends = true;
if (!add) {
referenceElement.delete();
}
}
}
PsiReferenceList list = extendsList;
Project project = extendsList.getProject();
if (add && !alreadyExtends) {
PsiElement anchor;
if (position == -1) {
anchor = referenceElements.length ==0 ? null : referenceElements[referenceElements.length-1];
}
else if (position == 0) {
anchor = null;
}
else {
anchor = referenceElements[position - 1];
}
PsiJavaCodeReferenceElement classReferenceElement = JavaPsiFacade.getElementFactory(project).createReferenceElementByType(myTypeToExtendFrom);
PsiElement element;
if (anchor == null) {
if (referenceElements.length == 0) {
element = extendsList.add(classReferenceElement);
}
else {
element = extendsList.addBefore(classReferenceElement, referenceElements[0]);
}
}
else {
element = extendsList.addAfter(classReferenceElement, anchor);
}
list = (PsiReferenceList) element.getParent();
}
//nothing was changed
if (!add && !alreadyExtends) {
return;
}
CodeStyleManager.getInstance(project).reformat(JavaCodeStyleManager.getInstance(project).shortenClassReferences(list));
}
}
| apache-2.0 |
calvinjia/tachyon | core/client/fs/src/main/java/alluxio/client/block/stream/StreamSerializationClientInterceptor.java | 1333 | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.client.block.stream;
import alluxio.grpc.GrpcSerializationUtils;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.MethodDescriptor;
/**
* Serialization interceptor for client.
*/
public class StreamSerializationClientInterceptor implements ClientInterceptor {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel channel) {
MethodDescriptor<ReqT, RespT> overriddenMethodDescriptor =
callOptions.getOption(GrpcSerializationUtils.OVERRIDDEN_METHOD_DESCRIPTOR);
if (overriddenMethodDescriptor != null) {
method = overriddenMethodDescriptor;
}
return channel.newCall(method, callOptions);
}
}
| apache-2.0 |
mbiarnes/kie-wb-common | kie-wb-common-dmn/kie-wb-common-dmn-client/src/main/java/org/kie/workbench/common/dmn/client/editors/expressions/types/context/NameColumn.java | 2701 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.dmn.client.editors.expressions.types.context;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
import org.jboss.errai.ui.client.local.spi.TranslationService;
import org.kie.workbench.common.dmn.api.definition.HasName;
import org.kie.workbench.common.dmn.api.definition.HasTypeRef;
import org.kie.workbench.common.dmn.api.property.dmn.Name;
import org.kie.workbench.common.dmn.api.property.dmn.QName;
import org.kie.workbench.common.dmn.client.editors.types.ValueAndDataTypePopoverView;
import org.kie.workbench.common.dmn.client.resources.i18n.DMNEditorConstants;
import org.kie.workbench.common.dmn.client.widgets.grid.columns.EditableNameAndDataTypeColumn;
import org.kie.workbench.common.dmn.client.widgets.grid.controls.container.CellEditorControlsView;
public class NameColumn extends EditableNameAndDataTypeColumn<ContextGrid> {
public NameColumn(final List<HeaderMetaData> headerMetaData,
final double width,
final ContextGrid gridWidget,
final Predicate<Integer> isEditable,
final Consumer<HasName> clearValueConsumer,
final BiConsumer<HasName, Name> setValueConsumer,
final BiConsumer<HasTypeRef, QName> setTypeRefConsumer,
final TranslationService translationService,
final CellEditorControlsView.Presenter cellEditorControls,
final ValueAndDataTypePopoverView.Presenter editor) {
super(headerMetaData,
width,
gridWidget,
isEditable,
clearValueConsumer,
setValueConsumer,
setTypeRefConsumer,
translationService,
cellEditorControls,
editor);
}
@Override
protected String getPopoverTitle() {
return translationService.getTranslation(DMNEditorConstants.ContextEditor_EditContextEntry);
}
}
| apache-2.0 |
siosio/intellij-community | platform/platform-impl/src/com/intellij/openapi/options/ex/ConfigurableExtensionPointUtil.java | 20436 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.options.ex;
import com.intellij.BundleBase;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.*;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectUtil;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.SmartList;
import org.jetbrains.annotations.*;
import java.text.MessageFormat;
import java.util.*;
public final class ConfigurableExtensionPointUtil {
private static final Logger LOG = Logger.getInstance(ConfigurableExtensionPointUtil.class);
private ConfigurableExtensionPointUtil() {
}
public static @NotNull List<Configurable> buildConfigurablesList(@NotNull List<? extends ConfigurableEP<Configurable>> extensions, @Nullable ConfigurableFilter filter) {
final List<Configurable> result = new ArrayList<>();
final Map<String, ConfigurableWrapper> idToConfigurable = new HashMap<>();
List<String> idsInEpOrder = new ArrayList<>();
for (ConfigurableEP<Configurable> ep : extensions) {
Configurable configurable = ConfigurableWrapper.wrapConfigurable(ep);
if (isSuppressed(configurable, filter)) {
continue;
}
if (configurable instanceof ConfigurableWrapper) {
ConfigurableWrapper wrapper = (ConfigurableWrapper)configurable;
idToConfigurable.put(wrapper.getId(), wrapper);
idsInEpOrder.add(wrapper.getId());
}
else {
//dumpConfigurable(configurablesExtensionPoint, ep, configurable);
if (configurable != null) {
result.add(configurable);
}
}
}
Set<String> visited = new HashSet<>();
Map<String, List<String>> idTree = buildIdTree(idToConfigurable, idsInEpOrder);
// modify configurables (append children)
// Before adding a child to a parent, all children of the child should be already added to the child,
// because ConfigurableWrapper#addChild may return a new instance.
for (final String id : idsInEpOrder) {
addChildrenRec(id, idToConfigurable, visited, idTree);
}
// add roots only (i.e. configurables without parents)
for (String id : idsInEpOrder) {
ConfigurableWrapper wrapper = idToConfigurable.get(id);
String parentId = wrapper.getParentId();
if (parentId == null || !idToConfigurable.containsKey(parentId)) {
result.add(wrapper);
}
}
return result;
}
private static @NotNull ConfigurableWrapper addChildrenRec(@NotNull String id,
@NotNull Map<String, ConfigurableWrapper> idToConfigurable,
@NotNull Set<? super String> visited,
@NotNull Map<String, List<String>> idTree) {
ConfigurableWrapper wrapper = idToConfigurable.get(id);
if (visited.contains(id)) {
return wrapper;
}
visited.add(id);
List<String> childIds = idTree.get(id);
if (childIds != null) {
for (String childId : childIds) {
ConfigurableWrapper childWrapper = addChildrenRec(childId, idToConfigurable, visited, idTree);
wrapper = wrapper.addChild(childWrapper);
}
idToConfigurable.put(id, wrapper);
}
return wrapper;
}
private static @NotNull Map<String, List<String>> buildIdTree(@NotNull Map<String, ConfigurableWrapper> idToConfigurable,
@NotNull List<String> idsInEpOrder) {
Map<String, List<String>> tree = new HashMap<>();
for (String id : idsInEpOrder) {
ConfigurableWrapper wrapper = idToConfigurable.get(id);
String parentId = wrapper.getParentId();
if (parentId != null) {
ConfigurableWrapper parent = idToConfigurable.get(parentId);
if (parent == null) {
LOG.warn("Can't find parent for " + parentId + " (" + wrapper + ")");
continue;
}
tree.computeIfAbsent(parentId, k -> new ArrayList<>(5)).add(id);
}
}
return tree;
}
/**
* @param project a project used to load project settings or {@code null}
* @param withIdeSettings specifies whether to load application settings or not
* @return the root configurable group that represents a tree of settings
*/
public static @NotNull ConfigurableGroup getConfigurableGroup(@Nullable Project project, boolean withIdeSettings) {
Project targetProject = withIdeSettings ? project : ProjectUtil.currentOrDefaultProject(project);
return new EpBasedConfigurableGroup(
targetProject,
() -> getConfigurableGroup(getConfigurables(targetProject, withIdeSettings), targetProject)
);
}
/**
* @param configurables a list of settings to process
* @param project a project used to create a project settings group or {@code null}
* @return the root configurable group that represents a tree of settings
*/
public static @Nullable ConfigurableGroup getConfigurableGroup(@NotNull List<? extends Configurable> configurables, @Nullable Project project) {
Map<String, List<Configurable>> map = groupConfigurables(configurables);
Map<String, Node<SortedConfigurableGroup>> tree = new HashMap<>();
for (Map.Entry<String, List<Configurable>> entry : map.entrySet()) {
addGroup(tree, project, entry.getKey(), entry.getValue(), null);
}
SortedConfigurableGroup root = getGroup(tree, "root");
if (!tree.isEmpty()) {
LOG.warn("ignore groups: " + tree.keySet());
}
if (root != null && root.myList != null && Registry.is("ide.settings.replace.group.with.single.configurable")) {
replaceGroupWithSingleConfigurable(root.myList);
}
return root;
}
private static void replaceGroupWithSingleConfigurable(List<Configurable> list) {
for (int i = 0; i < list.size(); i++) {
Configurable configurable = list.get(i);
if (configurable instanceof SortedConfigurableGroup) {
SortedConfigurableGroup group = (SortedConfigurableGroup)configurable;
configurable = getConfigurableToReplace(group.myList, group.getWeight());
if (configurable != null) {
list.set(i, configurable);
}
}
}
}
private static Configurable getConfigurableToReplace(List<Configurable> list, int weight) {
if (list != null) {
replaceGroupWithSingleConfigurable(list);
if (1 == list.size()) {
Configurable configurable = list.get(0);
if (configurable instanceof SortedConfigurableGroup) {
SortedConfigurableGroup group = (SortedConfigurableGroup)configurable;
group.myWeight = weight; // modify weight according to the replacing group
return group;
}
if (configurable instanceof ConfigurableWrapper) {
ConfigurableWrapper wrapper = (ConfigurableWrapper)configurable;
wrapper.myWeight = weight; // modify weight according to the replacing group
return wrapper;
}
}
}
return null;
}
/**
* @param tree a map that represents a tree of nodes
* @param groupId an identifier of a group to process children recursively
* @return the tree of groups starting from the specified one
*/
private static SortedConfigurableGroup getGroup(Map<String, Node<SortedConfigurableGroup>> tree, String groupId) {
Node<SortedConfigurableGroup> node = tree.remove(groupId);
if (node.myChildren != null) {
for (Iterator<Object> iterator = node.myChildren.iterator(); iterator.hasNext(); iterator.remove()) {
// expected type
String childId = (String)iterator.next();
node.myValue.myList.add(getGroup(tree, childId));
}
}
return node.myValue;
}
private static void addGroup(@NotNull Map<String, Node<SortedConfigurableGroup>> tree, Project project,
String groupId, List<? extends Configurable> configurables, ResourceBundle alternative) {
boolean root = "root".equals(groupId);
String id = "configurable.group." + groupId;
ResourceBundle bundle = getBundle(id + ".settings.display.name", configurables, alternative);
if (bundle == null) {
bundle = OptionsBundle.INSTANCE.getResourceBundle();
if (!root) {
LOG.warn("use other group instead of unexpected one: " + groupId);
groupId = "other";
id = "configurable.group." + groupId;
}
}
ConfigurableGroupEP ep = root ? null : ConfigurableGroupEP.find(groupId);
Node<SortedConfigurableGroup> node = Node.get(tree, groupId);
if (node.myValue == null) {
if (ep != null) {
String name = project == null || project.isDefault() || !"project".equals(groupId)
? ep.getDisplayName()
: StringUtil.first(MessageFormat.format(
ep.getResourceValue("configurable.group.project.named.settings.display.name"),
project.getName()), 30, true);
node.myValue = new SortedConfigurableGroup(id, name, ep.getDescription(), ep.helpTopic, ep.weight);
}
else if (root) {
node.myValue = new SortedConfigurableGroup(id, "ROOT GROUP", null, null, 0); //NON-NLS
}
else {
LOG.warn("Use <groupConfigurable> to specify custom configurable group: " + groupId);
int weight = getInt(bundle, id + ".settings.weight");
String help = getString(bundle, id + ".settings.help.topic");
String name = getName(bundle, id + ".settings.display.name");
String desc = getString(bundle, id + ".settings.description");
if (name != null && project != null) {
if (!project.isDefault() && !name.contains("{")) {
String named = getString(bundle, id + ".named.settings.display.name");
name = named != null ? named : name;
}
if (name.contains("{")) {
name = StringUtil.first(MessageFormat.format(name, project.getName()), 30, true);
}
}
node.myValue = new SortedConfigurableGroup(id, name, desc, help, weight);
}
}
if (configurables != null) {
node.myValue.myList.addAll(configurables);
}
if (!root && node.myParent == null) {
String parentId = ep != null ? ep.parentId : getString(bundle, id + ".settings.parent");
parentId = Node.cyclic(tree, parentId, "root", groupId, node);
node.myParent = Node.add(tree, parentId, groupId);
addGroup(tree, project, parentId, null, bundle);
}
}
/**
* @param configurables a list of settings to process
* @return the map of different groups of settings
*/
public static @NotNull Map<String, List<Configurable>> groupConfigurables(@NotNull List<? extends Configurable> configurables) {
Map<String, Node<ConfigurableWrapper>> tree = new HashMap<>();
for (Configurable configurable : configurables) {
if (!(configurable instanceof ConfigurableWrapper)) {
Node.add(tree, "other", configurable);
continue;
}
ConfigurableWrapper wrapper = (ConfigurableWrapper)configurable;
String id;
try {
id = wrapper.getId();
}
catch (ProcessCanceledException e) {
throw e;
}
catch (Throwable e) {
LOG.error("Cannot create configurable", e);
continue;
}
Node<ConfigurableWrapper> node = Node.get(tree, id);
if (node.myValue != null) {
LOG.warn("ignore configurable with duplicated id: " + id);
continue;
}
String parentId = wrapper.getParentId();
String groupId = wrapper.getExtensionPoint().groupId;
if (groupId != null) {
if (parentId != null) {
LOG.warn("ignore deprecated groupId: " + groupId + " for id: " + id);
}
else {
//TODO:LOG.warn("use deprecated groupId: " + groupId + " for id: " + id);
parentId = groupId;
}
}
parentId = Node.cyclic(tree, parentId, "other", id, node);
node.myParent = Node.add(tree, parentId, node);
node.myValue = wrapper;
}
Map<String, List<Configurable>> map = new HashMap<>();
for (String id : ArrayUtilRt.toStringArray(tree.keySet())) {
Node<ConfigurableWrapper> node = tree.get(id);
if (node != null) {
List<Configurable> list = getConfigurables(tree, node);
if (list != null) {
map.put(id, list);
tree.remove(id);
}
}
}
return map;
}
/**
* @param tree a map that represents a tree of nodes
* @param node a current node to process children recursively
* @return the list of settings for a group or {@code null} for internal node
*/
private static List<Configurable> getConfigurables(Map<String, Node<ConfigurableWrapper>> tree, Node<ConfigurableWrapper> node) {
if (node.myChildren == null) {
if (node.myValue == null) {
// for group only
return new ArrayList<>();
}
return null;
}
List<Configurable> list = new ArrayList<>(node.myChildren.size());
for (Iterator<Object> iterator = node.myChildren.iterator(); iterator.hasNext(); iterator.remove()) {
Object child = iterator.next();
if (child instanceof Configurable) {
list.add((Configurable)child);
}
else {
@SuppressWarnings("unchecked") // expected type
Node<ConfigurableWrapper> value = (Node<ConfigurableWrapper>)child;
if (getConfigurables(tree, value) != null) {
throw new IllegalStateException("unexpected algorithm state");
}
list.add(value.myValue);
tree.remove(value.myValue.getId());
}
}
if (node.myValue == null) {
return list; // for group only
}
for (Configurable configurable : list) {
node.myValue = node.myValue.addChild(configurable);
}
return null;
}
/**
* @param project a project used to load project settings for or {@code null}
* @param withIdeSettings specifies whether to load application settings or not
* @return the list of all valid settings according to parameters
*/
@ApiStatus.Internal
public static @NotNull List<Configurable> getConfigurables(@Nullable Project project, boolean withIdeSettings) {
List<Configurable> list = new ArrayList<>();
if (withIdeSettings) {
Application application = ApplicationManager.getApplication();
if (application != null) {
for (ConfigurableEP<Configurable> extension : Configurable.APPLICATION_CONFIGURABLE.getExtensionList()) {
addValid(list, ConfigurableWrapper.wrapConfigurable(extension, true), null);
}
}
}
if (project != null && !project.isDisposed()) {
for (ConfigurableEP<Configurable> extension : Configurable.PROJECT_CONFIGURABLE.getExtensions(project)) {
addValid(list, ConfigurableWrapper.wrapConfigurable(extension, true), project);
}
}
return list;
}
private static void addValid(@NotNull List<? super Configurable> list, Configurable configurable, Project project) {
if (isValid(configurable, project)) {
list.add(configurable);
}
}
/**
* @param configurable settings component to validate
* @param project current project, default template project or {@code null} for IDE settings
* @return {@code true} if the specified configurable must be shown in the settings dialog
*/
private static boolean isValid(Configurable configurable, Project project) {
if (configurable == null) {
return false;
}
return project == null || !project.isDefault() || !ConfigurableWrapper.isNonDefaultProject(configurable);
}
public static @Nullable ResourceBundle getBundle(@NonNls @NotNull String resource,
@Nullable Iterable<? extends Configurable> configurables,
@Nullable ResourceBundle alternative) {
ResourceBundle bundle = OptionsBundle.INSTANCE.getResourceBundle();
if (getString(bundle, resource) != null) {
return bundle;
}
if (configurables != null) {
for (Configurable configurable : configurables) {
if (configurable instanceof ConfigurableWrapper) {
ConfigurableWrapper wrapper = (ConfigurableWrapper)configurable;
bundle = wrapper.getExtensionPoint().findBundle();
if (getString(bundle, resource) != null) {
return bundle;
}
}
}
}
if (getString(alternative, resource) != null) {
return alternative;
}
return null;
}
private static @Nls String getString(ResourceBundle bundle, @NonNls String resource) {
if (bundle == null) return null;
try {
return bundle.getString(resource);
}
catch (MissingResourceException ignored) {
return null;
}
}
private static @Nls String getName(ResourceBundle bundle, @NonNls String resource) {
if (bundle == null) return null;
try {
return BundleBase.messageOrDefault(bundle, resource, null);
}
catch (MissingResourceException ignored) {
return null;
}
}
private static int getInt(ResourceBundle bundle, @NonNls String resource) {
try {
String value = getString(bundle, resource);
return value == null ? 0 : Integer.parseInt(value);
}
catch (NumberFormatException ignored) {
return 0;
}
}
private static boolean isSuppressed(Configurable each, ConfigurableFilter filter) {
return !isValid(each, null) || (filter != null && !filter.isIncluded(each));
}
public static @Nullable Configurable createProjectConfigurableForProvider(@NotNull Project project, Class<? extends ConfigurableProvider> providerClass) {
return createConfigurableForProvider(Configurable.PROJECT_CONFIGURABLE.getIterable(project), providerClass);
}
public static @Nullable Configurable createApplicationConfigurableForProvider(Class<? extends ConfigurableProvider> providerClass) {
return createConfigurableForProvider(Configurable.APPLICATION_CONFIGURABLE.getIterable(), providerClass);
}
private static @Nullable Configurable createConfigurableForProvider(@NotNull Iterable<? extends ConfigurableEP<Configurable>> extensions, Class<? extends ConfigurableProvider> providerClass) {
for (ConfigurableEP<Configurable> extension : extensions) {
if (extension.providerClass != null) {
Class<?> aClass = extension.findClassOrNull(extension.providerClass);
if (aClass != null && providerClass.isAssignableFrom(aClass)) {
return extension.createConfigurable();
}
}
}
return null;
}
/**
* Utility class that helps to build a tree.
*/
private static final class Node<V> {
List<Object> myChildren;
Node<V> myParent;
V myValue;
private static <I, V> Node<V> get(@NotNull Map<I, Node<V>> tree, @NotNull I id) {
Node<V> node = tree.get(id);
if (node == null) {
node = new Node<>();
tree.put(id, node);
}
return node;
}
private static <I, V> Node<V> add(@NotNull Map<I, Node<V>> tree, @NotNull I id, Object child) {
Node<V> node = get(tree, id);
if (node.myChildren == null) {
node.myChildren = new SmartList<>();
}
node.myChildren.add(child);
return node;
}
private static <I, V> boolean cyclic(@NotNull Map<I, Node<V>> tree, @NotNull I id, Node<V> parent) {
for (Node<V> node = tree.get(id); node != null; node = node.myParent) {
if (node == parent) {
return true;
}
}
return false;
}
private static <I, V> I cyclic(@NotNull Map<I, Node<V>> tree, @Nullable I id, I idDefault, I idNode, Node<V> parent) {
if (id == null) {
id = idDefault;
}
if (cyclic(tree, id, parent)) {
LOG.warn("ignore cyclic dependency: " + id + " cannot contain " + idNode);
id = idDefault;
}
return id;
}
}
}
| apache-2.0 |
maheshika/carbon-data | components/ndata-services/org.wso2.carbon.ndataservices.core/src/main/java/org/wso2/carbon/ndataservices/core/DataServiceDeployer.java | 1629 | /*
* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.ndataservices.core;
import org.wso2.carbon.utils.CarbonUtils;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class DataServiceDeployer {
private DataServiceXMLConfiguration loadDataServiceConfig(String path) throws Exception {
File file = new File(path);
if (!file.exists()) {
return null;
}
JAXBContext ctx;
try {
ctx = JAXBContext.newInstance(DataServiceXMLConfiguration.class);
return (DataServiceXMLConfiguration) ctx
.createUnmarshaller().unmarshal(new FileInputStream(file));
} catch (JAXBException e) {
throw new Exception(e.getMessage(),e);
} catch (FileNotFoundException e) {
throw new Exception(e.getMessage(),e);
}
}
}
| apache-2.0 |