code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
/*****************************************************************************
1 Í·Îļþ°üº¬
*****************************************************************************/
#include "product_config.h"
#include "vos.h"
#include "Taf_Tafm_Remote.h"
#include "UsimPsInterface.h"
#include "Ssa_Define.h"
#include "MnCall.h"
#include "Taf_Aps.h"
/* ɾ³ýExtAppMmcInterface.h*/
#include "TafMmcInterface.h"
#include "MnMsgExt.h"
#include "UsimPsInterface.h"
#include "MnComm.h"
#include "siapppih.h"
#include "MnCallTimer.h"
#include "RabmTafInterface.h"
#include "MmaAppLocal.h"
#include "TafDrvAgentMain.h"
#include "MnCallReqProc.h"
#include "TafApsMain.h"
#include "MnCallCtx.h"
#include "MnCallProcNvim.h"
#include "NasUtranCtrlCommFunc.h"
#include "NasUtranCtrlInterface.h"
#include "TafMtaMain.h"
#include "TafSdcCtx.h"
#include "TafSpmMain.h"
#include "MnMsgSmCommProc.h"
#include "NasUsimmApi.h"
#include "TafCbaProcUsim.h"
#include "MnCallImsaProc.h"
#include "TafMntn.h"
#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif
extern VOS_VOID R_ITF_InitFlowCtrl(VOS_VOID);
#define THIS_FILE_ID PS_FILE_ID_MNCALL_TASK_C
VOS_VOID MN_MSG_RecurDataRestore(
struct MsgCB *pstAppMsg
);
VOS_UINT8 g_ucMnOmConnectFlg = VOS_FALSE; /* UEÓëPC¹¤¾ßµÄÁ¬½Ó±êÖ¾, VOS_TRUE: ÒÑÁ¬½Ó; VOS_FALSE: δÁ¬½Ó */
VOS_UINT8 g_ucMnOmPcRecurEnableFlg = VOS_FALSE; /* PC¹¤¾ßÅäÖõķ¢ËÍNAS PC»Ø·ÅÏûÏ¢µÄʹÄܱêÖ¾ */
MN_STK_MSG_FUNC_MAP_STRU g_astTafStkMsgFuncMap[] =
{
{STK_MSG_SEND_REQ, MN_MSG_MSGTYPE_SEND_RPDATA_DIRECT, MN_MSG_ProcAppSend},
{STK_CALL_START_DTMF_REQ, MN_CALL_APP_START_DTMF_REQ, TAF_CALL_RcvStartDtmfReq},
{STK_CALL_STOP_DTMF_REQ, MN_CALL_APP_STOP_DTMF_REQ, TAF_CALL_RcvStopDtmfReq},
{STK_CALL_CALLORIG_REQ, MN_CALL_APP_ORIG_REQ, MN_CALL_StkCallOrigReqProc},
{STK_CALL_SUPS_CMD_REQ, MN_CALL_APP_SUPS_CMD_REQ, MN_CALL_CallSupsCmdReqProc},
{STK_SS_REGISTERSS_REQ, TAF_MSG_REGISTERSS_MSG, MN_SndAppMsgToSs},
{STK_SS_ERASESS_REQ, TAF_MSG_ERASESS_MSG, MN_SndAppMsgToSs},
{STK_SS_ACTIVATESS_REQ, TAF_MSG_ACTIVATESS_MSG, MN_SndAppMsgToSs},
{STK_SS_DEACTIVATESS_REQ, TAF_MSG_DEACTIVATESS_MSG, MN_SndAppMsgToSs},
{STK_SS_INTERROGATESS_REQ, TAF_MSG_INTERROGATESS_MSG, MN_SndAppMsgToSs},
{STK_SS_REGPWD_REQ, TAF_MSG_REGPWD_MSG, MN_SndAppMsgToSs},
{STK_SS_USSD_REQ, TAF_MSG_PROCESS_USS_MSG, MN_SndAppMsgToSs},
{PS_USIM_ENVELOPE_CNF, PS_USIM_ENVELOPE_CNF, TAF_ProcStkEnvelopeCnf}
};
/*****************************************************************************
2 º¯ÊýʵÏÖ
*****************************************************************************/
VOS_UINT32 MN_Init(enum VOS_INIT_PHASE_DEFINE ip)
{
TAF_SDC_CTX_STRU *pstSdcCtx = VOS_NULL_PTR;
switch( ip )
{
case VOS_IP_INITIAL:
NAS_PIHAPI_RegCardRefreshIndMsg(WUEPS_PID_TAF);
pstSdcCtx = TAF_SDC_GetSdcCtx();
TAF_SDC_InitCtx(TAF_SDC_INIT_CTX_STARTUP, pstSdcCtx);
/* ³õʼ»¯CCA */
MN_CALL_Init(MN_CALL_POWER_STATE_ON);
/* ³õʼ»¯SMA */
MN_MSG_Init();
/* ³õʼ»¯APS */
Aps_Init();
TAF_SPM_Init();
/* ³õʼ»¯SSA */
SSA_Init();
/* ³õʼ»¯GNA */
/* ÒѾÓëlijun,hefeng,xiamiaofangÈ·ÈÏ£¬¿ÉÒÔɾ³ýÁ÷¿Ø³õʼ»¯ */
break;
default:
break;
}
return VOS_OK;
}
VOS_VOID Taf_ProcCallCtrlAllowNoModification(struct MsgCB * pstMsg)
{
/*
switch ²Ù×÷ÀàÐÍ
case ºô½Ð:
if (ÕÒµ½´¦ÓÚCCA_CALL_CTRL_PROCEEDING״̬µÄºô½ÐʵÌå)
{
½«Call Control״̬¸üÐÂΪCCA_CALL_CTRL_END
µ÷ÓÃCca_CallOrigReqProc
}
break;
#if 0
case ²¹³äÒµÎñ:
ÔÝÂÔ
break;
case Êý´«:
ÔÝÂÔ
break;
#endif
default:
break;
*/
}
VOS_VOID Taf_ProcCallCtrlNotAllow(struct MsgCB * pstMsg)
{
/*
switch ²Ù×÷ÀàÐÍ
case ºô½Ð:
Çå³ý¶ÔÓ¦µÄCCA״̬»ú:
Éϱ¨Ê¼þ£¬´íÎóֵΪTAF_ERR_CALL_CONTROL_REJECTED
break;
case ²¹³äÒµÎñ:
case USSDÒµÎñ:
Çå³ý¶ÔÓ¦µÄSSA״̬»ú
Éϱ¨Ê¼þ£¬´íÎóֵΪTAF_ERR_CALL_CONTROL_REJECTED
break;
case Êý´«:
Çå³ý¶ÔÓ¦µÄAPS״̬»ú
Éϱ¨Ê¼þ£¬´íÎóֵΪTAF_ERR_CALL_CONTROL_REJECTED
break;
default:
break;
*/
}
VOS_VOID Taf_ProcCallCtrlAllowWithModification(struct MsgCB * pstMsg)
{
/*
µ÷ÓÃÊý¾Ýת»»º¯Êý
switch ²Ù×÷ÀàÐÍ
case ºô½Ð:
if (ÕÒµ½´¦ÓÚCCA_CALL_CTRL_PROCEEDING״̬µÄºô½ÐʵÌå)
{
¸üжÔӦʵÌåµÄ״̬ÐÅÏ¢
µ÷ÓÃCca_CallOrigReqProc
}
break;
case ²¹³äÒµÎñ:
case USSDÒµÎñ:
if (֮ǰµÄ²Ù×÷ÊDz¢²»ÊÇSSA·¢ÆðµÄCall control²Ù×÷)
{
Çå¿Õ¶ÔÓ¦·¢Æð²Ù×÷ʵÌåµÄ״̬(CCA»òÕßAPS)
}
µ÷Óù«¹²´¦Àíº¯Êý(MMI×Ö´®½âÎöº¯Êý£¬¸Ãº¯ÊýµÄʵÏÖ·½Ê½´ý¶¨,
µÈCCA±àÂëÍê³Éºó£¬ÔÙÐÐÈ·¶¨)
µ÷ÓÃSSAµÄ½Ó¿Ú(´Ë´¦»¹ÐèÒªÒÀ¾ÝаæµÄSSAµÄʵÏÖ·½Ê½À´È·¶¨)
break;
case Êý´«:
µ÷ÓÃAPSµÄPDP¼¤»î½Ó¿Ú(´Ë´¦»¹ÐèÒªÒÀ¾ÝаæµÄAPSµÄʵÏÖ·½Ê½À´È·¶¨)
break;
default:
break;
Éϱ¨Ê¼þ£¬¸æÖªÓ¦ÓÃÓÉÓÚcall controlµÄÔÒò£¬ºô½Ð·¢ÉúÁ˸ıä
*/
}
/*****************************************************************************
º¯ Êý Ãû : Taf_ProcSimaMsg
¹¦ÄÜÃèÊö : ´¦ÀíÀ´×ÔSimaµÄÏûÏ¢
ÊäÈë²ÎÊý : pstMsg - ÊÕµ½µÄÏûÏ¢
·µ »Ø Öµ : ÎÞ
µ÷Óú¯Êý :
±»µ÷º¯Êý :
ÐÞ¸ÄÀúÊ· :
1.ÈÕ ÆÚ : 2008Äê1ÔÂ10ÈÕ
×÷ Õß : ¶¡Çì 49431
ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý
*****************************************************************************/
VOS_VOID Taf_ProcSimaMsg (struct MsgCB * pstMsg)
{
/*
switch (ÃüÁîÀàÐÍ)
#ifdef hw_feature_call_control
case ÀàÐÍΪcall control:
{
switch (result)
{
case ÔÊÐíÎÞÐÞ¸Ä:
µ÷ÓÃTaf_ProcCallCtrlAllowNoModification
break;
case ²»ÔÊÐí:
µ÷ÓÃTaf_ProcCallCtrlNotAllow
break;
case ÔÊÐíµ«ÐÞ¸Ä:
µ÷ÓÃTaf_ProcCallCtrlAllowWithModification
break;
default:
break;
}
}
break;
#endif
default:
break;
*/
}
VOS_VOID MN_ProcTimerMsg (struct MsgCB * pstMsg)
{
REL_TIMER_MSG * pstTmrMsg = (REL_TIMER_MSG *)pstMsg;
switch (pstTmrMsg->ulName & MN_TIMER_CLASS_MASK)
{
case MN_TIMER_CLASS_CCA:
/* µ÷ÓÃCCAµÄ¶¨Ê±Æ÷ÏûÏ¢´¦Àíº¯Êý */
MN_CALL_ProcTimeoutMsg((REL_TIMER_MSG *)pstMsg);
break;
case MN_TIMER_CLASS_MSG:
/* µ÷ÓÃSMAµÄ¶¨Ê±Æ÷ÏûÏ¢´¦Àíº¯Êý */
MN_MSG_ProcTimeoutMsg((REL_TIMER_MSG *)pstMsg);
break;
case MN_TIMER_CLASS_SSA:
/* µ÷ÓÃSSAµÄ¶¨Ê±Æ÷ÏûÏ¢´¦Àíº¯Êý */
break;
case MN_TIMER_CLASS_MMA:
/* µ÷ÓÃMMAµÄ¶¨Ê±Æ÷ÏûÏ¢´¦Àíº¯Êý */
break;
case MN_TIMER_CLASS_APS:
TAF_APS_ProcMsg(pstMsg);
break;
default:
MN_ERR_LOG("MN_ProcTimerMsg: Unknown timer class.");
break;
}
}
/* ɾ³ýÔ MN_GetUsimMsgClient½Ó¿Úº¯Êý */
VOS_UINT32 MN_GetUsimMsgServerType(struct MsgCB * pstMsg)
{
VOS_UINT32 ulServerType;
PS_USIM_ENVELOPE_CNF_STRU *pstEnvelope;
/*´ÓUSIM¹ýÀ´µÄÏûÏ¢ÖгéȡҵÎñÀàÐÍ,ÆäÖÐFDN INDÏûÏ¢ÐèÒª MSG ºÍ CALLÄ£¿é´¦Àí*/
switch (((MSG_HEADER_STRU *)pstMsg)->ulMsgName)
{
/* ÐÞ¸ÄÁËFDN¼ì²é»Ø¸´µÄ½á¹¹,SSʹÓÃclient ID,CALL/MSGÐèҪʹÓÃclient IDÅÐ¶Ï */
case PS_USIM_FDN_CHECK_CNF:
ulServerType = TAF_SERVICE_TYPE_UNASSIGNED;
break;
case PS_USIM_ENVELOPE_CNF:
pstEnvelope = (PS_USIM_ENVELOPE_CNF_STRU *)pstMsg;
if (SI_STK_ENVELOPE_CALLCRTL == pstEnvelope->ucDataType)
{
ulServerType = TAF_SERVICE_TYPE_CALL;
}
else
{
ulServerType = TAF_SERVICE_TYPE_MSG;
}
break;
default:
ulServerType = TAF_SERVICE_TYPE_MSG;
break;
}
return ulServerType;
}
VOS_VOID MN_ProcUsimMsg (struct MsgCB * pstMsg)
{
VOS_UINT32 ulServerType;
ulServerType = MN_GetUsimMsgServerType(pstMsg);
/* ¸ù¾ÝulClient½«USIMÏûÏ¢·Ö·¢µ½¸÷ÒµÎñ´¦Àí£¬Ä¿Ç°ÓÐÁ½¸öÒµÎñ´¦ÀíÄ£¿é */
switch(ulServerType)
{
case TAF_SERVICE_TYPE_MSG:
MN_MSG_DispatchUsimMsg(pstMsg);
break;
case TAF_SERVICE_TYPE_CALL:
MN_CALL_DispatchUsimMsg(pstMsg);
break;
case TAF_SERVICE_TYPE_UNASSIGNED:
MN_MSG_DispatchUsimMsg(pstMsg);
MN_CALL_DispatchUsimMsg(pstMsg);
break;
default:
MN_WARN_LOG("MN_ProcUsimMsg: Rcv Invalid ulClient.");
break;
}
return;
}
VOS_VOID MN_ProcPihMsg (struct MsgCB * pstMsg)
{
MSG_HEADER_STRU *pstMsgHeader = VOS_NULL_PTR;
pstMsgHeader = (MSG_HEADER_STRU *)pstMsg;
if (PS_USIM_REFRESH_IND == pstMsgHeader->ulMsgName)
{
TAF_CBA_ProcRefreshInd((PS_USIM_REFRESH_IND_STRU *)pstMsgHeader);
MN_MSG_RcvUsimRefreshInd((PS_USIM_REFRESH_IND_STRU *)pstMsgHeader);
}
return;
}
VOS_VOID MN_ProcMmcMsg (struct MsgCB * pstMsg)
{
switch (((MSG_HEADER_STRU *)pstMsg)->ulMsgName)
{
#if ((FEATURE_ON == FEATURE_GCBS) || (FEATURE_ON == FEATURE_WCBS))
case TAFMMC_CBS_NO_NETWORK_IND:
case TAFMMC_CBS_CURR_NET_MODE_IND:
TAF_CBA_MsgProc(pstMsg);
break;
#endif
case TAFMMC_APS_SERVICE_STATE_IND:
TAF_APS_ProcMsg(pstMsg);
break;
default:
MN_WARN_LOG("MN_ProcMmcMsg:Rcv Invalid Msg Type");
break;
}
}
VOS_VOID MN_ProcOmMsg (struct MsgCB * pstMsg)
{
ID_NAS_OM_INQUIRE_STRU *pstOmInquire;
pstOmInquire = (ID_NAS_OM_INQUIRE_STRU *)pstMsg;
switch ( pstOmInquire->usPrimId )
{
case ID_NAS_OM_SET_CODEC_TYPE_REQUIRE :
case ID_NAS_OM_CODEC_TYPE_INQUIRE :
MN_CALL_ProcOmMsg(pstMsg);
break;
case ID_NAS_OM_SET_DSFLOW_RPT_REQ :
TAF_APS_ProcMsg(pstMsg);
break;
default:
MN_NORM_LOG("MN_CALL_ProcOmMsg:wrong PrimId!");
break;
}
return;
}
/* begin V7R1 PhaseI Modify */
VOS_VOID MN_ProcUsimStatus(
struct MsgCB * pstMsg
)
{
MNPH_USIM_STATUS_IND_STRU *pstUsimStatus;
MN_CALL_CUSTOM_CFG_INFO_STRU *pstCustomCfgAddr;
/* »ñÈ¡ÌØÐÔ¿ØÖÆNVµØÖ· */
pstCustomCfgAddr = MN_CALL_GetCustomCfgInfo();
MN_MSG_SetSmsFileRefreshFlag(EF_SMS_SMSS_ID, VOS_TRUE);
MN_MSG_SetSmsFileRefreshFlag(EF_SMS_SMS_ID, VOS_TRUE);
MN_MSG_SetSmsFileRefreshFlag(EF_SMS_SMSP_ID, VOS_TRUE);
MN_MSG_SetSmsFileRefreshFlag(EF_SMS_SMSR_ID, VOS_TRUE);
pstUsimStatus = (MNPH_USIM_STATUS_IND_STRU *)pstMsg;
MN_MSG_CfgDataInit(pstUsimStatus->enUsimStatus);
#if ((FEATURE_ON == FEATURE_GCBS) || (FEATURE_ON == FEATURE_WCBS))
TAF_CBA_MsgProc(pstMsg);
#endif
if (MN_CALL_NV_ITEM_ACTIVE == pstCustomCfgAddr->ucAlsSupportFlg )
{
MN_CALL_LineInfo(pstUsimStatus->enUsimStatus);
}
/* ÔÚPID init¶ÁÈ¡ºô½ÐÖØ½¨nvµÄʱºòÅжÏÊÇ·ñÊDzâÊÔ¿¨£¬µ«¿ÉÄÜÓÉÓÚʱÐòÎÊÌâµ¼ÖÂÅжϽá¹û´íÎó£¬
Òò´ËÔÚÔËÐÐʱÔÙ¶Áµ÷ÓÃÒ»´Î¶ÁÈ¡NVµÄº¯Êý£¬ÔÚº¯ÊýÖÐÅжÏÊÇ·ñÊDzâÊÔ¿¨ */
MN_CALL_ReadCallRedialCfgNvim();
/* ÔÚPID init¶ÁÈ¡ssÖØ½¨nvµÄʱºòÅжÏÊÇ·ñÊDzâÊÔ¿¨£¬µ«¿ÉÄÜÓÉÓÚʱÐòÎÊÌâusimδ³õʼ»¯½áÊøµ÷ÓÃusim½Ó¿Ú
»ñÈ¡ÊÇ·ñÊDzâÊÔ¿¨·µ»Ø²»×¼µ¼ÖÂÅжϽá¹û´íÎó£¬Òò´ËÔÚÔËÐÐʱÔÙ¶Áµ÷ÓÃÒ»´Î¶ÁÈ¡NVµÄº¯Êý£¬
ÔÚº¯ÊýÖÐÅжÏÊÇ·ñÊDzâÊÔ¿¨ */
TAF_SSA_ReadSsRetryCfgNvim();
}
/* end V7R1 PhaseI Modify */
#ifndef __PS_WIN32_RECUR__
VOS_VOID TAF_RcvMmaOmMaintainInfoInd(
struct MsgCB *pstMsg
)
{
MMCM_OM_MAINTAIN_INFO_IND_STRU *pstOmMaintainInfo;
pstOmMaintainInfo = (MMCM_OM_MAINTAIN_INFO_IND_STRU*)pstMsg;
/* ±£´æÈ«¾Ö±äÁ¿µÄÖµ */
g_ucMnOmConnectFlg = pstOmMaintainInfo->ucOmConnectFlg;
g_ucMnOmPcRecurEnableFlg = pstOmMaintainInfo->ucOmPcRecurEnableFlg;
if ( (VOS_TRUE == g_ucMnOmConnectFlg)
&& (VOS_TRUE == g_ucMnOmPcRecurEnableFlg) )
{
NAS_MSG_SndOutsideContextData_Part1();
NAS_MSG_SndOutsideContextData_Part2();
NAS_MSG_SndOutsideContextData_Part3();
}
}
#endif
VOS_VOID MN_ProcMmaMsg (
struct MsgCB *pstMsg
)
{
switch (((MSG_HEADER_STRU *)pstMsg)->ulMsgName)
{
/* begin V7R1 PhaseI Modify */
case MN_USIM_STATUS_IND:
MN_ProcUsimStatus(pstMsg);
break;
#ifndef __PS_WIN32_RECUR__
case MMCM_OM_MAINTAIN_INFO_IND:
TAF_RcvMmaOmMaintainInfoInd(pstMsg);
break;
#endif
/* end V7R1 PhaseI Modify */
case ID_MMA_MSG_CS_SERVICE_CHANGE_NOTIFY:
TAF_MSG_RcvMmaCsServiceChangeNotify(pstMsg);
break;
case MMA_TAF_POWER_OFF_IND:
Aps_PowerOff();
break;
default:
MN_WARN_LOG("MN_ProcMmaMsg:Rcv Invalid Msg Type");
break;
}
}
VOS_VOID MN_SndAppMsgToSs (struct MsgCB *pstMsg)
{
MN_APP_REQ_MSG_STRU *pstSsMsg = VOS_NULL_PTR;
VOS_UINT32 ulRet;
VOS_UINT32 ulMsgLen;
MN_APP_REQ_MSG_STRU *pstAppMsg = VOS_NULL_PTR;
pstAppMsg = (MN_APP_REQ_MSG_STRU *)pstMsg;
ulMsgLen = pstAppMsg->ulLength;
/* ÉêÇëÏûÏ¢ */
pstSsMsg = (MN_APP_REQ_MSG_STRU *)PS_ALLOC_MSG(WUEPS_PID_TAF, ulMsgLen);
if (VOS_NULL_PTR == pstSsMsg)
{
MN_WARN_LOG("MN_SndAppMsgToSs: alloc msg fail!");
return;
}
PS_MEM_CPY( ((VOS_UINT8 *)pstSsMsg + VOS_MSG_HEAD_LENGTH), ((VOS_UINT8 *)pstAppMsg+ VOS_MSG_HEAD_LENGTH), ulMsgLen);
/* Ìî³äÏûϢͷ */
pstSsMsg->ulReceiverPid = WUEPS_PID_SS;
ulRet = PS_SEND_MSG(WUEPS_PID_TAF, pstSsMsg);
if (VOS_OK != ulRet)
{
MN_WARN_LOG("MN_SndAppMsgToSs: send msg fail!");
return;
}
return;
}
VOS_VOID TAF_ProcStkEnvelopeCnf(struct MsgCB * pstMsg)
{
PS_USIM_ENVELOPE_CNF_STRU *pstEnvelope = VOS_NULL_PTR;
pstEnvelope = (PS_USIM_ENVELOPE_CNF_STRU *)pstMsg;
if (SI_STK_ENVELOPE_CALLCRTL != pstEnvelope->ucDataType)
{
MN_MSG_RcvUsimEnvelopeCnf(pstMsg);
}
return;
}
VOS_VOID MN_DispatchStkMsg(struct MsgCB * pstMsg)
{
VOS_UINT32 ulLoop;
VOS_UINT32 ulFuncNum;
MSG_HEADER_STRU *pstMsgHeader = VOS_NULL_PTR;
TAF_STK_MSG_FUNC_MAP pStkMsgFunc = VOS_NULL_PTR;
pstMsgHeader = (MSG_HEADER_STRU *)pstMsg;
ulFuncNum = sizeof(g_astTafStkMsgFuncMap) / sizeof(g_astTafStkMsgFuncMap[0]);
for (ulLoop = 0; ulLoop < ulFuncNum; ulLoop ++ )
{
if (pstMsgHeader->ulMsgName == g_astTafStkMsgFuncMap[ulLoop].ulMsgName)
{
pStkMsgFunc = g_astTafStkMsgFuncMap[ulLoop].pStkMsgFunc;
/*
´¦Àíº¯Êý²»Çø·ÖÇëÇóµÄÔ´PID£¬¶øSTKµÄÒµÎñÇëÇó½á¹¹ÓëATµÄÒ»Ö£¬ÏûÏ¢Ãû²»Ò»Ö£¬
ÒòΪ´¦Àíº¯ÊýÅжϵÄÏûÏ¢Ãû¶¼ÊÇATµÄÏûÏ¢Ãû£¬ÕâÀォSTKµÄÏûÏ¢Ãû¸üÐÂΪAPPµÄÏûÏ¢Ãû
*/
pstMsgHeader->ulMsgName = g_astTafStkMsgFuncMap[ulLoop].ulAppMsgName;
break;
}
}
if (VOS_NULL_PTR == pStkMsgFunc)
{
MN_WARN_LOG("MN_DispatchStkMsg: Invalid Msg Name");
return;
}
pStkMsgFunc(pstMsg);
return;
}
VOS_VOID MN_DispatchTafMsg (struct MsgCB * pstMsg)
{
/* TAF->TAFµÄÏûÏ¢¶¨ÒåÒ»¸öͳһµÄ½á¹¹Ìå,È¡³öÏûÏ¢·Ö¶Î */
TAF_INTERNAL_MSG_STRU *pstTafMsg = VOS_NULL_PTR;
pstTafMsg = (TAF_INTERNAL_MSG_STRU *)pstMsg;
switch (pstTafMsg->ulMsgId & ID_TAF_MNTN_MSG_MASK)
{
/* À´×ÔAPS APIµÄÏûÏ¢½»¸øAPS´¦Àí */
case ID_TAF_APS_INTERNAL_BASE:
TAF_APS_ProcMsg(pstMsg);
break;
/* ·¢Ë͸øMSGµÄÏûÏ¢µ½MSG´¦Àí */
/* ĿǰֻÓÐID_TAF_SPM_SMMA_REQ,MSGÏÈ·¢Ë͵½SPM½øÐÐÓòÑ¡Ôñ,ÓòÑ¡ÔñÖ®ºóÔÙµ½MSG´¦Àí */
case ID_TAF_MSG_INTERNAL_BASE:
TAF_MSG_ProcTafMsg(pstMsg);
break;
/* ÆäËûÏûÏ¢²»ÐèÒª´¦Àí */
default:
MN_NORM_LOG("MN_DispatchTafMsg: Unknown message type.");
break;
}
return;
}
VOS_VOID MN_DispatchAppMsg (struct MsgCB * pstMsg)
{
MN_APP_REQ_MSG_STRU * pstAppMsg = (MN_APP_REQ_MSG_STRU *)pstMsg;
switch (pstAppMsg->usMsgName & MN_APP_MSG_CLASS_MASK)
{
case MN_APP_MSG_CLASS_CALL:
/* À´×ÔCCA APIµÄÏûÏ¢£¬½»¸øCCA´¦Àí */
MN_CALL_ProcAppReqMsg(pstAppMsg);
break;
case MN_APP_MSG_CLASS_MSG:
/* À´×ÔSMA APIµÄÏûÏ¢£¬½»¸øSMA´¦Àí */
MN_MSG_ProcAppReqMsg(pstAppMsg);
break;
case MN_APP_MSG_CLASS_SSA:
/* À´×ÔSSA APIµÄÏûÏ¢£¬½»¸øSSA´¦Àí */
MN_SndAppMsgToSs(pstMsg);
break;
case MN_APP_MSG_CLASS_MMA:
/* À´×ÔMMA APIµÄÏûÏ¢£¬½»¸øMMA´¦Àí */
break;
/* ÒÆµ½MN_DispatchTafMsgÖд¦Àí */
case MN_APP_MSG_CLASS_QRY:
/* ATÓëMNÄ£¿é¼ä²éѯ²Ù×÷Ïà¹ØÏûÏ¢ */
break;
default:
MN_ERR_LOG("MN_DispatchAppMsg: Unknown message type.");
break;
}
}
VOS_VOID MN_DispatchRabmMsg (
VOS_VOID *pstMsg
)
{
MN_RABM_IND_MSG_STRU *pstRabmMsg;
pstRabmMsg = (MN_RABM_IND_MSG_STRU *)pstMsg;
/* ÓÉÓÚRABM·¢µÄÏûÏ¢¸øAPSºÍCALLÁ½¸öÄ£¿é½øÐд¦Àí£¬µ±MsgNameµÄȡֵ·¶Î§
ÔÚRABMºÍCALLÖ®¼äµÄ¶¨ÒåµÄʱºò£¬ÓÉÐÂÔöº¯Êý´¦Àí£¬·ñÔòÓÉÔÓк¯Êý´¦Àí */
if (pstRabmMsg->usMsgName > RABM_CALL_MSG_CLASS_BASE)
{
MN_CALL_ProcRabmCallPrimitive(pstRabmMsg);
return;
}
TAF_APS_ProcMsg((struct MsgCB *)pstMsg);
}
#if (FEATURE_IMS == FEATURE_ON)
VOS_VOID MN_DispatchImsaMsg (
VOS_VOID *pMsg
)
{
MSG_HEADER_STRU *pstImsaMsg = VOS_NULL_PTR;
pstImsaMsg = (MSG_HEADER_STRU *)pMsg;
switch (pstImsaMsg->ulMsgName & TAF_IMSA_MSG_MASK)
{
case TAF_MSG_IMSA_MSG_BASE:
/* ´¦ÀíÀ´×ÔIMSAµÄSMSµÄMSG */
TAF_MSG_ProcImsaMsg(pstImsaMsg);
break;
case TAF_CALL_IMSA_MSG_BASE:
TAF_CALL_ProcImsaMsg(pstImsaMsg);
break;
default:
break;
}
}
#endif
VOS_VOID MN_DispatchMsg (struct MsgCB * pstMsg)
{
struct MsgCB *pstSrcMsg = VOS_NULL_PTR;
struct MsgCB *pstDestMsg = VOS_NULL_PTR;
if (VOS_NULL_PTR == pstMsg)
{
return;
}
if (VOS_TRUE == TAF_SDC_GetSvlteSupportFlag())
{
/* svlteÌØÐÔ¿ªÆôʱ£¬modem1¿ÉÄÜÊÕµ½usim0µÄÏûÏ¢£¬ÐèÒª½«ÏûÏ¢ÖÐsend pid½øÐÐת»» */
pstMsg->ulSenderPid = TAF_SDC_ConvertOamSendPid(pstMsg->ulSenderPid);
}
/* Ö§³ÖTD-SCDMAÌØÐÔʱ£¬Ðè¶ÔÏûÏ¢½øÐÐÊÊÅä´¦Àí */
if ( VOS_TRUE == NAS_UTRANCTRL_MsgProc(pstMsg, &pstDestMsg) )
{
/* ÏûÏ¢ÔÚUTRANCTRLÄ£¿é´¦ÀíÍê³É£¬Ö±½Ó·µ»Ø£¬²»½øÈëºóÐø´¦Àí */
return;
}
pstSrcMsg = pstDestMsg;
if (VOS_TRUE == TAF_SPM_MsgProc(pstSrcMsg, &pstDestMsg))
{
/* ÏûÏ¢ÔÚSPMÄ£¿é´¦ÀíÍê³É,Ö±½Ó·µ»Ø,²»ÐèÒª½øÈëºóÐø´¦Àí */
return;
}
/* Ìæ»»ÏûÏ¢Ö¸Õë */
switch (pstDestMsg->ulSenderPid)
{
case VOS_PID_TIMER:
MN_ProcTimerMsg(pstDestMsg);
break;
case UEPS_PID_CST:
MN_CALL_ProcCstCallPrimitive(pstDestMsg);
break;
case MAPS_STK_PID:
MN_DispatchStkMsg(pstDestMsg);
break;
case WUEPS_PID_TAF:
MN_DispatchTafMsg(pstDestMsg);
break;
case WUEPS_PID_AT:
MN_DispatchAppMsg(pstDestMsg);
break;
case WUEPS_PID_CC:
MN_CALL_ProcMnccPrimMsg(pstDestMsg);
break;
case WUEPS_PID_MMC:
MN_ProcMmcMsg(pstDestMsg);
break;
case WUEPS_PID_MMA:
MN_ProcMmaMsg(pstDestMsg);
break;
case WUEPS_PID_MM:
break;
case WUEPS_PID_SS:
break;
case WUEPS_PID_SMS:
MN_MSG_ProcSmsMsg((VOS_VOID*)pstDestMsg);
break;
#if (FEATURE_IMS == FEATURE_ON)
case PS_PID_IMSA:
MN_DispatchImsaMsg((VOS_VOID*)pstDestMsg);
break;
#endif
case WUEPS_PID_SM:
TAF_APS_ProcMsg(pstDestMsg);
break;
#if (FEATURE_ON == FEATURE_LTE)
case PS_PID_ESM:
TAF_APS_ProcMsg(pstDestMsg);
break;
case MSP_L4_L4A_PID:
TAF_APS_ProcMsg(pstDestMsg);
break;
#endif
case WUEPS_PID_RABM:
MN_DispatchRabmMsg(pstDestMsg);
break;
case UEPS_PID_SN:
TAF_APS_ProcMsg(pstDestMsg);
break;
case WUEPS_PID_USIM:
case MAPS_PB_PID:
MN_ProcUsimMsg(pstDestMsg);
break;
case MAPS_PIH_PID:
MN_ProcPihMsg(pstDestMsg);
break;
case WUEPS_PID_OM:
MN_ProcOmMsg(pstDestMsg);
break;
case WUEPS_PID_VC:
MN_CALL_ProcVCMsg(pstDestMsg);
break;
#if ((FEATURE_ON == FEATURE_GCBS) || (FEATURE_ON == FEATURE_WCBS))
case UEPS_PID_GAS:
case WUEPS_PID_BMC:
#if (FEATURE_ON == FEATURE_LTE)
case PS_PID_ERRC:
#endif
case WUEPS_PID_WRR:
TAF_CBA_MsgProc(pstDestMsg);
break;
#endif
case UEPS_PID_NDCLIENT:
TAF_APS_ProcMsg(pstDestMsg);
break;
case ACPU_PID_TAFAGENT:
TAF_APS_ProcMsg(pstDestMsg);
break;
default:
MN_ERR_LOG1("MN_DispatchMsg: Unknown message sender, SenderPid, ", (VOS_INT32)pstMsg->ulSenderPid);
break;
}
}
/*****************************************************************************
º¯ Êý Ãû : WuepsTafFidInit
¹¦ÄÜÃèÊö : ³õʼ»¯TAF FID
ÊäÈë²ÎÊý : ÂÔ
·µ »Ø Öµ : ÂÔ
µ÷Óú¯Êý :
±»µ÷º¯Êý :
ÐÞ¸ÄÀúÊ· :
1.ÈÕ ÆÚ : 2008Äê1ÔÂ10ÈÕ
×÷ Õß : ¶¡Çì 49431
ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý
*****************************************************************************/
extern VOS_UINT32 WuepsAdminPidInit ( enum VOS_INIT_PHASE_DEFINE ip );
extern VOS_VOID Admin_TaskEntry (struct MsgCB * pRcvMsg);
extern VOS_UINT32 WuepsVCPidInit ( enum VOS_INIT_PHASE_DEFINE ip );
extern VOS_VOID APP_VC_MsgProc(MsgBlock* pMsg);
#if (VOS_WIN32 == VOS_OS_VER)
extern VOS_VOID At_MsgProc(MsgBlock* pMsg);
extern VOS_UINT32 At_PidInit(enum VOS_INIT_PHASE_DEFINE enPhase);
#endif
VOS_UINT32 WuepsTafFidInit ( enum VOS_INIT_PHASE_DEFINE ip )
{
VOS_UINT32 ulRslt = VOS_OK;
switch( ip )
{
case VOS_IP_LOAD_CONFIG:
ulRslt = VOS_RegisterPIDInfo(WUEPS_PID_ADMIN,
(Init_Fun_Type) WuepsAdminPidInit,
(Msg_Fun_Type) Admin_TaskEntry );
if( VOS_OK != ulRslt )
{
return VOS_ERR;
}
ulRslt = VOS_RegisterPIDInfo(WUEPS_PID_TAF,
(Init_Fun_Type) MN_Init,
(Msg_Fun_Type) MN_DispatchMsg );
if( VOS_OK != ulRslt )
{
return VOS_ERR;
}
ulRslt = VOS_RegisterPIDInfo(WUEPS_PID_VC,
(Init_Fun_Type)WuepsVCPidInit,
(Msg_Fun_Type)APP_VC_MsgProc );
if( VOS_OK != ulRslt )
{
return VOS_ERR;
}
ulRslt = VOS_RegisterPIDInfo(WUEPS_PID_DRV_AGENT,
(Init_Fun_Type)DRVAGENT_Init,
(Msg_Fun_Type)DRVAGENT_DispatchMsg );
if( VOS_OK != ulRslt )
{
return VOS_ERR;
}
#if (VOS_WIN32 == VOS_OS_VER)
ulRslt = VOS_RegisterPIDInfo(WUEPS_PID_AT,
(Init_Fun_Type)At_PidInit,
(Msg_Fun_Type)At_MsgProc);
if (VOS_OK != ulRslt)
{
return VOS_ERR;
}
#endif
ulRslt = VOS_RegisterMsgTaskPrio(WUEPS_FID_TAF, VOS_PRIORITY_M5);
if( VOS_OK != ulRslt )
{
return VOS_ERR;
}
ulRslt = VOS_RegisterPIDInfo(UEPS_PID_MTA,
(Init_Fun_Type)TAF_MTA_InitPid,
(Msg_Fun_Type)TAF_MTA_ProcMsg );
if( VOS_OK != ulRslt )
{
return VOS_ERR;
}
break;
case VOS_IP_FARMALLOC:
case VOS_IP_INITIAL:
case VOS_IP_ENROLLMENT:
case VOS_IP_LOAD_DATA:
case VOS_IP_FETCH_DATA:
case VOS_IP_STARTUP:
case VOS_IP_RIVAL:
case VOS_IP_KICKOFF:
case VOS_IP_STANDBY:
case VOS_IP_BROADCAST_STATE:
case VOS_IP_RESTART:
case VOS_IP_BUTT:
break;
}
return VOS_OK;
}
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif
| wbrambley/Grace-kernel | drivers/vendor/hisi/modem/taf/gu/src/ccore/src/Mn/Task/Src/MnTask.c | C | gpl-2.0 | 26,467 |
<?php
/**
* HUBzero CMS
*
* Copyright 2005-2015 HUBzero Foundation, LLC.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* HUBzero is a registered trademark of Purdue University.
*
* @package hubzero-cms
* @author David Benham <dbenham@purdue.edu>
* @copyright Copyright 2005-2015 HUBzero Foundation, LLC.
* @license http://opensource.org/licenses/MIT MIT
*/
// No direct access
defined('_HZEXEC_') or die();
/**
* Groups plugin class for Member Options
*/
class plgGroupsMemberOptions extends \Hubzero\Plugin\Plugin
{
/**
* Affects constructor behavior. If true, language files will be loaded automatically.
*
* @var boolean
*/
protected $_autoloadLanguage = true;
/**
* Return the alias and name for this category of content
*
* @return array
*/
public function &onGroupAreas()
{
$area = array(
'name' => 'memberoptions',
'title' => Lang::txt('GROUP_MEMBEROPTIONS'),
'default_access' => 'registered',
'display_menu_tab' => $this->params->get('display_tab', 0),
'icon' => '2699'
);
return $area;
}
/**
* Return data on a group view (this will be some form of HTML)
*
* @param object $group Current group
* @param string $option Name of the component
* @param string $authorized User's authorization level
* @param integer $limit Number of records to pull
* @param integer $limitstart Start of records to pull
* @param string $action Action to perform
* @param array $access What can be accessed
* @param array $areas Active area(s)
* @return array
*/
public function onGroup($group, $option, $authorized, $limit=0, $limitstart=0, $action='', $access, $areas=null)
{
// The output array we're returning
$arr = array(
'html' => ''
);
$user = User::getInstance();
$this->group = $group;
$this->option = $option;
// Things we need from the form
$recvEmailOptionID = Request::getInt('memberoptionid', 0);
$recvEmailOptionValue = Request::getInt('recvpostemail', 0);
include_once(__DIR__ . DS . 'models' . DS . 'memberoption.php');
switch ($action)
{
case 'editmemberoptions':
$arr['html'] .= $this->edit($group, $user, $recvEmailOptionID, $recvEmailOptionValue);
break;
case 'savememberoptions':
$arr['html'] .= $this->save($group, $user, $recvEmailOptionID, $recvEmailOptionValue);
break;
default:
$arr['html'] .= $this->edit($group, $user, $recvEmailOptionID, $recvEmailOptionValue);
break;
}
return $arr;
}
/**
* Edit settings
*
* @param object $group
* @param object $user
* @param integer $recvEmailOptionID
* @param integer $recvEmailOptionValue
* @return string
*/
protected function edit($group, $user, $recvEmailOptionID, $recvEmailOptionValue)
{
// Load the options
$recvEmailOption = Plugins\Groups\Memberoptions\Models\Memberoption::oneByUserAndOption(
$group->get('gidNumber'),
$user->get('id'),
'receive-forum-email'
);
$view = $this->view('default', 'browse')
->set('recvEmailOptionID', $recvEmailOption->get('id', 0))
->set('recvEmailOptionValue', $recvEmailOption->get('optionvalue', 0))
->set('option', $this->option)
->set('group', $this->group);
// Return the output
return $view->loadTemplate();
}
/**
* Save settings
*
* @param object $group
* @param object $user
* @param integer $recvEmailOptionID
* @param integer $recvEmailOptionValue
* @return void
*/
protected function save($group, $user, $recvEmailOptionID, $recvEmailOptionValue)
{
$postSaveRedirect = Request::getVar('postsaveredirect', '');
// Save the GROUPS_MEMBEROPTION_TYPE_DISCUSSION_NOTIFICIATION setting
$row = Plugins\Groups\Memberoptions\Models\Memberoption::blank()->set(array(
'id' => $recvEmailOptionID,
'userid' => $user->get('id'),
'gidNumber' => $group->get('gidNumber'),
'optionname' => 'receive-forum-email',
'optionvalue' => $recvEmailOptionValue
));
// Store content
if (!$row->save())
{
$this->setError($row->getError());
return $this->edit($group, $user, $recvEmailOptionID, $recvEmailOptionValue);
}
if (Request::getInt('no_html'))
{
echo json_encode(array('success' => true));
exit();
}
if (!$postSaveRedirect)
{
$postSaveRedirect = Route::url('index.php?option=' . $this->option . '&cn=' . $this->group->get('cn') . '&active=memberoptions&action=edit');
}
App::redirect(
$postSaveRedirect,
Lang::txt('You have successfully updated your email settings')
);
}
/**
* Subscribe a person to emails on enrollment
*
* @param integer $gidNumber
* @param integer $userid
* @return void
*/
public function onGroupUserEnrollment($gidNumber, $userid)
{
// get group
$group = \Hubzero\User\Group::getInstance($gidNumber);
// is auto-subscribe on for discussion forum
$autosubscribe = $group->get('discussion_email_autosubscribe');
// log variable
Log::debug('$discussion_email_autosubscribe' . $autosubscribe);
// if were not auto-subscribed then stop
if (!$autosubscribe)
{
return;
}
include_once(__DIR__ . DS . 'models' . DS . 'memberoption.php');
// see if they've already got something, they shouldn't, but you never know
$row = Plugins\Groups\Memberoptions\Models\Memberoption::oneByUserAndOption(
$gidNumber,
$userid,
'receive-forum-email'
);
if ($row->get('id'))
{
// They already have a record, so ignore.
return;
}
$row->set('gidNumber', $gidNumber);
$row->set('userid', $userid);
$row->set('optionname', 'receive-forum-email');
$row->set('optionvalue', 1);
$row->save();
}
}
| kevinwojo/hubzero-cms | core/plugins/groups/memberoptions/memberoptions.php | PHP | gpl-2.0 | 6,730 |
#pragma once
namespace vm { using namespace ps3; }
// Return Codes
enum
{
CELL_ATRAC_ERROR_API_FAIL = 0x80610301,
CELL_ATRAC_ERROR_READSIZE_OVER_BUFFER = 0x80610311,
CELL_ATRAC_ERROR_UNKNOWN_FORMAT = 0x80610312,
CELL_ATRAC_ERROR_READSIZE_IS_TOO_SMALL = 0x80610313,
CELL_ATRAC_ERROR_ILLEGAL_SAMPLING_RATE = 0x80610314,
CELL_ATRAC_ERROR_ILLEGAL_DATA = 0x80610315,
CELL_ATRAC_ERROR_NO_DECODER = 0x80610321,
CELL_ATRAC_ERROR_UNSET_DATA = 0x80610322,
CELL_ATRAC_ERROR_DECODER_WAS_CREATED = 0x80610323,
CELL_ATRAC_ERROR_ALLDATA_WAS_DECODED = 0x80610331,
CELL_ATRAC_ERROR_NODATA_IN_BUFFER = 0x80610332,
CELL_ATRAC_ERROR_NOT_ALIGNED_OUT_BUFFER = 0x80610333,
CELL_ATRAC_ERROR_NEED_SECOND_BUFFER = 0x80610334,
CELL_ATRAC_ERROR_ALLDATA_IS_ONMEMORY = 0x80610341,
CELL_ATRAC_ERROR_ADD_DATA_IS_TOO_BIG = 0x80610342,
CELL_ATRAC_ERROR_NONEED_SECOND_BUFFER = 0x80610351,
CELL_ATRAC_ERROR_UNSET_LOOP_NUM = 0x80610361,
CELL_ATRAC_ERROR_ILLEGAL_SAMPLE = 0x80610371,
CELL_ATRAC_ERROR_ILLEGAL_RESET_BYTE = 0x80610372,
CELL_ATRAC_ERROR_ILLEGAL_PPU_THREAD_PRIORITY = 0x80610381,
CELL_ATRAC_ERROR_ILLEGAL_SPU_THREAD_PRIORITY = 0x80610382,
};
// Remain Frame
enum : s32
{
CELL_ATRAC_ALLDATA_IS_ON_MEMORY = -1,
CELL_ATRAC_NONLOOP_STREAM_DATA_IS_ON_MEMORY = -2,
CELL_ATRAC_LOOP_STREAM_DATA_IS_ON_MEMORY = -3,
};
struct set_alignment(8) CellAtracHandle
{
vm::ptr<u8> pucWorkMem;
// ...
};
CHECK_MAX_SIZE(CellAtracHandle, 512);
struct CellAtracBufferInfo
{
vm::ptr<u8> pucWriteAddr;
be_t<u32> uiWritableByte;
be_t<u32> uiMinWriteByte;
be_t<u32> uiReadPosition;
};
struct CellAtracExtRes
{
vm::ptr<struct CellSpurs> pSpurs;
u8 priority[8];
};
extern Module cellAtrac;
| hgstream/rpcs3 | rpcs3/Emu/SysCalls/Modules/cellAtrac.h | C | gpl-2.0 | 1,891 |
/************************************************************************
IMPORTANT NOTE : this file contains two clearly delimited sections :
the ARCHITECTURE section (in two parts) and the USER section. Each section
is governed by its own copyright and license. Please check individually
each section for license and copyright information.
*************************************************************************/
/*******************BEGIN ARCHITECTURE SECTION (part 1/2)****************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2003-2011 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section 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.
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, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************
************************************************************************/
#ifndef __alsa_dsp__
#define __alsa_dsp__
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <pwd.h>
#include <limits.h>
#include <alsa/asoundlib.h>
#include "faust/audio/audio.h"
#include "faust/audio/dsp.h"
/**
DEFAULT ALSA PARAMETERS CONTROLLED BY ENVIRONMENT VARIABLES
Some default parameters of Faust's ALSA applications are controlled by the following environment variables :
FAUST2ALSA_DEVICE = "hw:0"
FAUST2ALSA_FREQUENCY= 44100
FAUST2ALSA_BUFFER = 512
FAUST2ALSA_PERIODS = 2
*/
//using namespace std;
// handle 32/64 bits int size issues
#ifdef __x86_64__
#define uint32 unsigned int
#define uint64 unsigned long int
#define int32 int
#define int64 long int
#else
#define uint32 unsigned int
#define uint64 unsigned long long int
#define int32 int
#define int64 long long int
#endif
// check 32/64 bits issues are correctly handled
#define check_error(err) if (err) { printf("%s:%d, alsa error %d : %s\n", __FILE__, __LINE__, err, snd_strerror(err)); exit(1); }
#define check_error_msg(err,msg) if (err) { fprintf(stderr, "%s:%d, %s : %s(%d)\n", __FILE__, __LINE__, msg, snd_strerror(err), err); exit(1); }
#define display_error_msg(err,msg) if (err) { fprintf(stderr, "%s:%d, %s : %s(%d)\n", __FILE__, __LINE__, msg, snd_strerror(err), err); }
/**
* Used to set the priority and scheduling of the audi#include <sys/types.h>
#include <pwd.h>
o thread
*/
static bool setRealtimePriority ()
{
struct passwd * pw;
int err;
uid_t uid;
struct sched_param param;
uid = getuid ();
pw = getpwnam ("root");
setuid (pw->pw_uid);
param.sched_priority = 50; /* 0 to 99 */
err = sched_setscheduler(0, SCHED_RR, ¶m);
setuid (uid);
return (err != -1);
}
/******************************************************************************
*******************************************************************************
AUDIO INTERFACE
*******************************************************************************
*******************************************************************************/
enum { kRead = 1, kWrite = 2, kReadWrite = 3 };
/**
* A convenient class to pass parameters to AudioInterface
*/
class AudioParam
{
public:
const char* fCardName;
unsigned int fFrequency;
unsigned int fBuffering;
unsigned int fPeriods;
unsigned int fSoftInputs;
unsigned int fSoftOutputs;
public :
AudioParam() :
fCardName("hw:0"),
fFrequency(44100),
fBuffering(512),
fPeriods(2),
fSoftInputs(2),
fSoftOutputs(2)
{}
AudioParam& cardName(const char* n) { fCardName = n; return *this; }
AudioParam& frequency(int f) { fFrequency = f; return *this; }
AudioParam& buffering(int fpb) { fBuffering = fpb; return *this; }
AudioParam& periods(int p) { fPeriods = p; return *this; }
AudioParam& inputs(int n) { fSoftInputs = n; return *this; }
AudioParam& outputs(int n) { fSoftOutputs = n; return *this; }
};
/**
* An ALSA audio interface
*/
class AudioInterface : public AudioParam
{
public :
snd_pcm_t* fOutputDevice ;
snd_pcm_t* fInputDevice ;
snd_pcm_hw_params_t* fInputParams;
snd_pcm_hw_params_t* fOutputParams;
snd_pcm_format_t fSampleFormat;
snd_pcm_access_t fSampleAccess;
unsigned int fCardInputs;
unsigned int fCardOutputs;
unsigned int fChanInputs;
unsigned int fChanOutputs;
bool fDuplexMode;
// interleaved mode audiocard buffers
void* fInputCardBuffer;
void* fOutputCardBuffer;
// non interleaved mode audiocard buffers
void* fInputCardChannels[256];
void* fOutputCardChannels[256];
// non interleaved mod, floating point software buffers
float* fInputSoftChannels[256];
float* fOutputSoftChannels[256];
public :
const char* cardName() { return fCardName; }
int frequency() { return fFrequency; }
int buffering() { return fBuffering; }
int periods() { return fPeriods; }
float** inputSoftChannels() { return fInputSoftChannels; }
float** outputSoftChannels() { return fOutputSoftChannels; }
bool duplexMode() { return fDuplexMode; }
AudioInterface(const AudioParam& ap = AudioParam()) : AudioParam(ap)
{
fInputDevice = 0;
fOutputDevice = 0;
fInputParams = 0;
fOutputParams = 0;
}
/**
* Open the audio interface
*/
void open()
{
int err;
// try to open output device, quit if fail to open output device
err = snd_pcm_open( &fOutputDevice, fCardName, SND_PCM_STREAM_PLAYBACK, 0 ); check_error(err)
// setup output device parameters
err = snd_pcm_hw_params_malloc ( &fOutputParams ); check_error(err)
setAudioParams(fOutputDevice, fOutputParams);
fCardOutputs = fSoftOutputs;
snd_pcm_hw_params_set_channels_near(fOutputDevice, fOutputParams, &fCardOutputs);
err = snd_pcm_hw_params (fOutputDevice, fOutputParams ); check_error (err);
// allocate alsa output buffers
if (fSampleAccess == SND_PCM_ACCESS_RW_INTERLEAVED) {
fOutputCardBuffer = calloc(interleavedBufferSize(fOutputParams), 1);
} else {
for (unsigned int i = 0; i < fCardOutputs; i++) {
fOutputCardChannels[i] = calloc(noninterleavedBufferSize(fOutputParams), 1);
}
}
// check for duplex mode (if we need and have an input device)
if (fSoftInputs == 0) {
fDuplexMode = false;
fCardInputs = 0;
} else {
// try to open input device
err = snd_pcm_open( &fInputDevice, fCardName, SND_PCM_STREAM_CAPTURE, 0 );
if (err == 0) {
fDuplexMode = true;
} else {
printf("Warning : no input device");
fDuplexMode = false;
fCardInputs = 0;
}
}
if (fDuplexMode) {
// we have and need an input device
// set the number of physical inputs close to what we need
err = snd_pcm_hw_params_malloc ( &fInputParams ); check_error(err);
setAudioParams(fInputDevice, fInputParams);
fCardInputs = fSoftInputs;
snd_pcm_hw_params_set_channels_near(fInputDevice, fInputParams, &fCardInputs);
err = snd_pcm_hw_params (fInputDevice, fInputParams ); check_error (err);
// allocation of alsa buffers
if (fSampleAccess == SND_PCM_ACCESS_RW_INTERLEAVED) {
fInputCardBuffer = calloc(interleavedBufferSize(fInputParams), 1);
} else {
for (unsigned int i = 0; i < fCardInputs; i++) {
fInputCardChannels[i] = calloc(noninterleavedBufferSize(fInputParams), 1);
}
}
}
printf("inputs : %u, outputs : %u\n", fCardInputs, fCardOutputs);
// allocation of floating point buffers needed by the dsp code
fChanInputs = max(fSoftInputs, fCardInputs); assert (fChanInputs < 256);
fChanOutputs = max(fSoftOutputs, fCardOutputs); assert (fChanOutputs < 256);
for (unsigned int i = 0; i < fChanInputs; i++) {
fInputSoftChannels[i] = (float*) calloc (fBuffering, sizeof(float));
for (unsigned int j = 0; j < fBuffering; j++) {
fInputSoftChannels[i][j] = 0.0;
}
}
for (unsigned int i = 0; i < fChanOutputs; i++) {
fOutputSoftChannels[i] = (float*) calloc (fBuffering, sizeof(float));
for (unsigned int j = 0; j < fBuffering; j++) {
fOutputSoftChannels[i][j] = 0.0;
}
}
}
void setAudioParams(snd_pcm_t* stream, snd_pcm_hw_params_t* params)
{
int err;
// set params record with initial values
err = snd_pcm_hw_params_any ( stream, params );
check_error_msg(err, "unable to init parameters")
// set alsa access mode (and fSampleAccess field) either to non interleaved or interleaved
err = snd_pcm_hw_params_set_access (stream, params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
if (err) {
err = snd_pcm_hw_params_set_access (stream, params, SND_PCM_ACCESS_RW_INTERLEAVED );
check_error_msg(err, "unable to set access mode neither to non-interleaved or to interleaved");
}
snd_pcm_hw_params_get_access(params, &fSampleAccess);
// search for 32-bits or 16-bits format
err = snd_pcm_hw_params_set_format (stream, params, SND_PCM_FORMAT_S32);
if (err) {
err = snd_pcm_hw_params_set_format (stream, params, SND_PCM_FORMAT_S16);
check_error_msg(err, "unable to set format to either 32-bits or 16-bits");
}
snd_pcm_hw_params_get_format(params, &fSampleFormat);
// set sample frequency
snd_pcm_hw_params_set_rate_near (stream, params, &fFrequency, 0);
// set period and period size (buffering)
err = snd_pcm_hw_params_set_period_size (stream, params, fBuffering, 0);
check_error_msg(err, "period size not available");
err = snd_pcm_hw_params_set_periods (stream, params, fPeriods, 0);
check_error_msg(err, "number of periods not available");
}
ssize_t interleavedBufferSize (snd_pcm_hw_params_t* params)
{
_snd_pcm_format format; snd_pcm_hw_params_get_format(params, &format);
snd_pcm_uframes_t psize; snd_pcm_hw_params_get_period_size(params, &psize, NULL);
unsigned int channels; snd_pcm_hw_params_get_channels(params, &channels);
ssize_t bsize = snd_pcm_format_size (format, psize * channels);
return bsize;
}
ssize_t noninterleavedBufferSize (snd_pcm_hw_params_t* params)
{
_snd_pcm_format format; snd_pcm_hw_params_get_format(params, &format);
snd_pcm_uframes_t psize; snd_pcm_hw_params_get_period_size(params, &psize, NULL);
ssize_t bsize = snd_pcm_format_size (format, psize);
return bsize;
}
void close()
{}
/**
* Read audio samples from the audio card. Convert samples to floats and take
* care of interleaved buffers
*/
void read()
{
if (fSampleAccess == SND_PCM_ACCESS_RW_INTERLEAVED) {
int count = snd_pcm_readi(fInputDevice, fInputCardBuffer, fBuffering);
if (count<0) {
//display_error_msg(count, "reading samples");
int err = snd_pcm_prepare(fInputDevice);
//check_error_msg(err, "preparing input stream");
}
if (fSampleFormat == SND_PCM_FORMAT_S16) {
short* buffer16b = (short*) fInputCardBuffer;
for (unsigned int s = 0; s < fBuffering; s++) {
for (unsigned int c = 0; c < fCardInputs; c++) {
fInputSoftChannels[c][s] = float(buffer16b[c + s*fCardInputs])*(1.0/float(SHRT_MAX));
}
}
} else if (fSampleFormat == SND_PCM_FORMAT_S32) {
int32* buffer32b = (int32*) fInputCardBuffer;
for (unsigned int s = 0; s < fBuffering; s++) {
for (unsigned int c = 0; c < fCardInputs; c++) {
fInputSoftChannels[c][s] = float(buffer32b[c + s*fCardInputs])*(1.0/float(INT_MAX));
}
}
} else {
printf("unrecognized input sample format : %u\n", fSampleFormat);
exit(1);
}
} else if (fSampleAccess == SND_PCM_ACCESS_RW_NONINTERLEAVED) {
int count = snd_pcm_readn(fInputDevice, fInputCardChannels, fBuffering);
if (count<0) {
//display_error_msg(count, "reading samples");
int err = snd_pcm_prepare(fInputDevice);
//check_error_msg(err, "preparing input stream");
}
if (fSampleFormat == SND_PCM_FORMAT_S16) {
for (unsigned int c = 0; c < fCardInputs; c++) {
short* chan16b = (short*) fInputCardChannels[c];
for (unsigned int s = 0; s < fBuffering; s++) {
fInputSoftChannels[c][s] = float(chan16b[s])*(1.0/float(SHRT_MAX));
}
}
} else if (fSampleFormat == SND_PCM_FORMAT_S32) {
for (unsigned int c = 0; c < fCardInputs; c++) {
int32* chan32b = (int32*) fInputCardChannels[c];
for (unsigned int s = 0; s < fBuffering; s++) {
fInputSoftChannels[c][s] = float(chan32b[s])*(1.0/float(INT_MAX));
}
}
} else {
printf("unrecognized input sample format : %u\n", fSampleFormat);
exit(1);
}
} else {
check_error_msg(-10000, "unknow access mode");
}
}
/**
* write the output soft channels to the audio card. Convert sample
* format and interleaves buffers when needed
*/
void write()
{
recovery :
if (fSampleAccess == SND_PCM_ACCESS_RW_INTERLEAVED) {
if (fSampleFormat == SND_PCM_FORMAT_S16) {
short* buffer16b = (short*) fOutputCardBuffer;
for (unsigned int f = 0; f < fBuffering; f++) {
for (unsigned int c = 0; c < fCardOutputs; c++) {
float x = fOutputSoftChannels[c][f];
buffer16b[c + f*fCardOutputs] = short( max(min(x,1.0f),-1.0f) * float(SHRT_MAX) ) ;
}
}
} else if (fSampleFormat == SND_PCM_FORMAT_S32) {
int32* buffer32b = (int32*) fOutputCardBuffer;
for (unsigned int f = 0; f < fBuffering; f++) {
for (unsigned int c = 0; c < fCardOutputs; c++) {
float x = fOutputSoftChannels[c][f];
buffer32b[c + f*fCardOutputs] = int( max(min(x,1.0f),-1.0f) * float(INT_MAX) ) ;
}
}
} else {
printf("unrecognized output sample format : %u\n", fSampleFormat);
exit(1);
}
int count = snd_pcm_writei(fOutputDevice, fOutputCardBuffer, fBuffering);
if (count<0) {
//display_error_msg(count, "w3");
int err = snd_pcm_prepare(fOutputDevice);
//check_error_msg(err, "preparing output stream");
goto recovery;
}
} else if (fSampleAccess == SND_PCM_ACCESS_RW_NONINTERLEAVED) {
if (fSampleFormat == SND_PCM_FORMAT_S16) {
for (unsigned int c = 0; c < fCardOutputs; c++) {
short* chan16b = (short*) fOutputCardChannels[c];
for (unsigned int f = 0; f < fBuffering; f++) {
float x = fOutputSoftChannels[c][f];
chan16b[f] = short( max(min(x,1.0f),-1.0f) * float(SHRT_MAX) ) ;
}
}
} else if (fSampleFormat == SND_PCM_FORMAT_S32) {
for (unsigned int c = 0; c < fCardOutputs; c++) {
int32* chan32b = (int32*) fOutputCardChannels[c];
for (unsigned int f = 0; f < fBuffering; f++) {
float x = fOutputSoftChannels[c][f];
chan32b[f] = int( max(min(x,1.0f),-1.0f) * float(INT_MAX) ) ;
}
}
} else {
printf("unrecognized output sample format : %u\n", fSampleFormat);
exit(1);
}
int count = snd_pcm_writen(fOutputDevice, fOutputCardChannels, fBuffering);
if (count<0) {
//display_error_msg(count, "w3");
int err = snd_pcm_prepare(fOutputDevice);
//check_error_msg(err, "preparing output stream");
goto recovery;
}
} else {
check_error_msg(-10000, "unknow access mode");
}
}
/**
* print short information on the audio device
*/
void shortinfo()
{
int err;
snd_ctl_card_info_t* card_info;
snd_ctl_t* ctl_handle;
err = snd_ctl_open (&ctl_handle, fCardName, 0); check_error(err);
snd_ctl_card_info_alloca (&card_info);
err = snd_ctl_card_info(ctl_handle, card_info); check_error(err);
printf("%s|%d|%d|%d|%d|%s\n",
snd_ctl_card_info_get_driver(card_info),
fCardInputs, fCardOutputs,
fFrequency, fBuffering,
snd_pcm_format_name((_snd_pcm_format)fSampleFormat));
}
/**
* print more detailled information on the audio device
*/
void longinfo()
{
int err;
snd_ctl_card_info_t* card_info;
snd_ctl_t* ctl_handle;
printf("Audio Interface Description :\n");
printf("Sampling Frequency : %d, Sample Format : %s, buffering : %d\n",
fFrequency, snd_pcm_format_name((_snd_pcm_format)fSampleFormat), fBuffering);
printf("Software inputs : %2d, Software outputs : %2d\n", fSoftInputs, fSoftOutputs);
printf("Hardware inputs : %2d, Hardware outputs : %2d\n", fCardInputs, fCardOutputs);
printf("Channel inputs : %2d, Channel outputs : %2d\n", fChanInputs, fChanOutputs);
// affichage des infos de la carte
err = snd_ctl_open (&ctl_handle, fCardName, 0); check_error(err);
snd_ctl_card_info_alloca (&card_info);
err = snd_ctl_card_info(ctl_handle, card_info); check_error(err);
printCardInfo(card_info);
// affichage des infos liees aux streams d'entree-sortie
if (fSoftInputs > 0) printHWParams(fInputParams);
if (fSoftOutputs > 0) printHWParams(fOutputParams);
}
void printCardInfo(snd_ctl_card_info_t* ci)
{
printf("Card info (address : %p)\n", ci);
printf("\tID = %s\n", snd_ctl_card_info_get_id(ci));
printf("\tDriver = %s\n", snd_ctl_card_info_get_driver(ci));
printf("\tName = %s\n", snd_ctl_card_info_get_name(ci));
printf("\tLongName = %s\n", snd_ctl_card_info_get_longname(ci));
printf("\tMixerName = %s\n", snd_ctl_card_info_get_mixername(ci));
printf("\tComponents = %s\n", snd_ctl_card_info_get_components(ci));
printf("--------------\n");
}
void printHWParams( snd_pcm_hw_params_t* params )
{
printf("HW Params info (address : %p)\n", params);
#if 0
printf("\tChannels = %d\n", snd_pcm_hw_params_get_channels(params));
printf("\tFormat = %s\n", snd_pcm_format_name((_snd_pcm_format)snd_pcm_hw_params_get_format(params)));
printf("\tAccess = %s\n", snd_pcm_access_name((_snd_pcm_access)snd_pcm_hw_params_get_access(params)));
printf("\tRate = %d\n", snd_pcm_hw_params_get_rate(params, NULL));
printf("\tPeriods = %d\n", snd_pcm_hw_params_get_periods(params, NULL));
printf("\tPeriod size = %d\n", (int)snd_pcm_hw_params_get_period_size(params, NULL));
printf("\tPeriod time = %d\n", snd_pcm_hw_params_get_period_time(params, NULL));
printf("\tBuffer size = %d\n", (int)snd_pcm_hw_params_get_buffer_size(params));
printf("\tBuffer time = %d\n", snd_pcm_hw_params_get_buffer_time(params, NULL));
#endif
printf("--------------\n");
}
};
// lopt : Scan Command Line long int Arguments
long lopt(int argc, char *argv[], const char* longname, const char* shortname, long def)
{
for (int i=2; i<argc; i++)
if ( strcmp(argv[i-1], shortname) == 0 || strcmp(argv[i-1], longname) == 0 )
return atoi(argv[i]);
return def;
}
// sopt : Scan Command Line string Arguments
const char* sopt(int argc, char *argv[], const char* longname, const char* shortname, const char* def)
{
for (int i=2; i<argc; i++)
if ( strcmp(argv[i-1], shortname) == 0 || strcmp(argv[i-1], longname) == 0 )
return argv[i];
return def;
}
// fopt : Scan Command Line flag option (without argument), return true if the flag
bool fopt(int argc, char *argv[], const char* longname, const char* shortname)
{
for (int i=1; i<argc; i++)
if ( strcmp(argv[i], shortname) == 0 || strcmp(argv[i], longname) == 0 )
return true;
return false;
}
/**
* Return the value of an environment variable or defval if undefined.
*/
static int getDefaultEnv(const char* name, int defval)
{
const char* str = getenv(name);
if (str) {
return atoi(str);
} else {
return defval;
}
}
/**
* Return the value of an environment variable or defval if undefined.
*/
static const char* getDefaultEnv(const char* name, const char* defval)
{
const char* str = getenv(name);
if (str) {
return str;
} else {
return defval;
}
}
/******************************************************************************
*******************************************************************************
ALSA audio interface
*******************************************************************************
*******************************************************************************/
void* __run(void* ptr);
class alsaaudio : public audio
{
AudioInterface* fAudio;
dsp* fDSP;
pthread_t fAudioThread;
bool fRunning;
public:
alsaaudio(int argc, char *argv[], dsp* DSP) : fAudio(0), fDSP(DSP), fRunning(false) {
fAudio = new AudioInterface (
AudioParam().cardName( sopt(argc, argv, "--device", "-d", getDefaultEnv("FAUST2ALSA_DEVICE", "hw:0") ) )
.frequency( lopt(argc, argv, "--frequency", "-f", getDefaultEnv("FAUST2ALSA_FREQUENCY",44100) ) )
.buffering( lopt(argc, argv, "--buffer", "-b", getDefaultEnv("FAUST2ALSA_BUFFER",512) ) )
.periods( lopt(argc, argv, "--periods", "-p", getDefaultEnv("FAUST2ALSA_PERIODS",2) ) )
.inputs(DSP->getNumInputs())
.outputs(DSP->getNumOutputs()));
}
virtual ~alsaaudio() { stop(); delete fAudio; }
virtual bool init(const char */*name*/, dsp* DSP) {
AVOIDDENORMALS;
fAudio->open();
DSP->init(fAudio->frequency());
return true;
}
virtual bool start() {
fRunning = true;
if (pthread_create( &fAudioThread, 0, __run, this))
fRunning = false;
return fRunning;
}
virtual void stop() {
if (fRunning) {
fRunning = false;
pthread_join (fAudioThread, 0);
}
}
virtual void run() {
bool rt = setRealtimePriority();
printf(rt ? "RT : ":"NRT: "); fAudio->shortinfo();
if (fAudio->duplexMode()) {
fAudio->write();
fAudio->write();
while(fRunning) {
fAudio->read();
fDSP->compute(fAudio->buffering(), fAudio->inputSoftChannels(), fAudio->outputSoftChannels());
fAudio->write();
}
} else {
fAudio->write();
while(fRunning) {
fDSP->compute(fAudio->buffering(), fAudio->inputSoftChannels(), fAudio->outputSoftChannels());
fAudio->write();
}
}
}
};
void* __run (void* ptr)
{
alsaaudio * alsa = (alsaaudio*)ptr;
alsa->run();
return 0;
}
#endif
/********************END ARCHITECTURE SECTION (part 2/2)****************/
| scztt/sc3-plugins | source/DEINDUGens/include/faust/audio/alsa-dsp.h | C | gpl-2.0 | 22,547 |
/**
* Copyright (c) 2009--2012 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.taskomatic.task;
import com.redhat.rhn.common.conf.Config;
import com.redhat.rhn.common.hibernate.HibernateFactory;
import com.redhat.rhn.taskomatic.TaskoRun;
import com.redhat.rhn.taskomatic.task.threaded.TaskQueue;
import com.redhat.rhn.taskomatic.task.threaded.TaskQueueFactory;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.io.IOException;
/**
* Custom Quartz Job implementation which only allows one thread to
* run at a time. All other threads return without performing any work.
* This policy was chosen instead of blocking so as to reduce threading
* problems inside Quartz itself.
*
* @version $Rev $
*
*/
public abstract class RhnQueueJob implements RhnJob {
private TaskoRun jobRun = null;
protected abstract Logger getLogger();
/**
* {@inheritDoc}
*/
public void appendExceptionToLogError(Exception e) {
getLogger().error(e.getMessage());
getLogger().error(e.getCause());
}
private void logToNewFile() {
PatternLayout pattern =
new PatternLayout(DEFAULT_LOGGING_LAYOUT);
try {
getLogger().removeAllAppenders();
FileAppender appender = new FileAppender(pattern,
jobRun.buildStdOutputLogPath());
getLogger().addAppender(appender);
}
catch (IOException e) {
getLogger().warn("Logging to file disabled");
}
}
/**
* {@inheritDoc}
*/
public void execute(JobExecutionContext ctx, TaskoRun runIn)
throws JobExecutionException {
setJobRun(runIn);
try {
execute(ctx);
}
catch (Exception e) {
if (HibernateFactory.getSession().getTransaction().isActive()) {
HibernateFactory.rollbackTransaction();
HibernateFactory.closeSession();
}
appendExceptionToLogError(e);
jobRun.saveStatus(TaskoRun.STATUS_FAILED);
}
HibernateFactory.commitTransaction();
HibernateFactory.closeSession();
}
/**
* {@inheritDoc}
*/
public void execute(JobExecutionContext ctx)
throws JobExecutionException {
TaskQueueFactory factory = TaskQueueFactory.get();
String queueName = getQueueName();
TaskQueue queue = factory.getQueue(queueName);
if (queue == null) {
try {
queue = factory.createQueue(queueName, getDriverClass(), getLogger());
}
catch (Exception e) {
getLogger().error(e);
return;
}
}
if (queue.changeRun(jobRun)) {
jobRun.start();
HibernateFactory.commitTransaction();
HibernateFactory.closeSession();
logToNewFile();
getLogger().debug("Starting run " + jobRun.getId());
}
else {
// close current run
TaskoRun run = (TaskoRun) HibernateFactory.reload(jobRun);
run.appendToOutputLog("Run with id " + queue.getQueueRun().getId() +
" handles the whole task queue.");
run.skipped();
HibernateFactory.commitTransaction();
HibernateFactory.closeSession();
}
int defaultItems = 3;
if (queueName.equals("channel_repodata")) {
defaultItems = 1;
}
int maxWorkItems = Config.get().getInt("taskomatic." + queueName +
"_max_work_items", defaultItems);
if (queue.getQueueSize() < maxWorkItems) {
queue.run(this);
}
else {
getLogger().debug("Maximum number of workers already put ... skipping.");
}
}
/**
* @return Returns the run.
*/
public TaskoRun getRun() {
return jobRun;
}
/**
* @param runIn The run to set.
*/
public void setJobRun(TaskoRun runIn) {
jobRun = runIn;
}
protected abstract Class getDriverClass();
protected abstract String getQueueName();
}
| hustodemon/spacewalk | java/code/src/com/redhat/rhn/taskomatic/task/RhnQueueJob.java | Java | gpl-2.0 | 4,855 |
/* Copyright (c) 2009, Code Aurora Forum. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Code Aurora Forum nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* Alternatively, provided that this notice is retained in full, this software
* may be relicensed by the recipient under the terms of the GNU General Public
* License version 2 ("GPL") and only version 2, in which case the provisions of
* the GPL apply INSTEAD OF those given above. If the recipient relicenses the
* software under the GPL, then the identification text in the MODULE_LICENSE
* macro must be changed to reflect "GPLv2" instead of "Dual BSD/GPL". Once a
* recipient changes the license terms to the GPL, subsequent recipients shall
* not relicense under alternate licensing terms, including the BSD or dual
* BSD/GPL terms. In addition, the following license statement immediately
* below and between the words START and END shall also then apply when this
* software is relicensed under the GPL:
*
* START
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 and only version 2 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* END
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef __ARCH_ARM_MACH_MSM_CLOCK_PCOM_H
#define __ARCH_ARM_MACH_MSM_CLOCK_PCOM_H
/* clock IDs used by the modem processor */
#define P_ACPU_CLK 0 /* Applications processor clock */
#define P_ADM_CLK 1 /* Applications data mover clock */
#define P_ADSP_CLK 2 /* ADSP clock */
#define P_EBI1_CLK 3 /* External bus interface 1 clock */
#define P_EBI2_CLK 4 /* External bus interface 2 clock */
#define P_ECODEC_CLK 5 /* External CODEC clock */
#define P_EMDH_CLK 6 /* External MDDI host clock */
#define P_GP_CLK 7 /* General purpose clock */
#define P_GRP_CLK 8 /* Graphics clock */
#define P_I2C_CLK 9 /* I2C clock */
#define P_ICODEC_RX_CLK 10 /* Internal CODEX RX clock */
#define P_ICODEC_TX_CLK 11 /* Internal CODEX TX clock */
#define P_IMEM_CLK 12 /* Internal graphics memory clock */
#define P_MDC_CLK 13 /* MDDI client clock */
#define P_MDP_CLK 14 /* Mobile display processor clock */
#define P_PBUS_CLK 15 /* Peripheral bus clock */
#define P_PCM_CLK 16 /* PCM clock */
#define P_PMDH_CLK 17 /* Primary MDDI host clock */
#define P_SDAC_CLK 18 /* Stereo DAC clock */
#define P_SDC1_CLK 19 /* Secure Digital Card clocks */
#define P_SDC1_PCLK 20
#define P_SDC2_CLK 21
#define P_SDC2_PCLK 22
#define P_SDC3_CLK 23
#define P_SDC3_PCLK 24
#define P_SDC4_CLK 25
#define P_SDC4_PCLK 26
#define P_TSIF_CLK 27 /* Transport Stream Interface clocks */
#define P_TSIF_REF_CLK 28
#define P_TV_DAC_CLK 29 /* TV clocks */
#define P_TV_ENC_CLK 30
#define P_UART1_CLK 31 /* UART clocks */
#define P_UART2_CLK 32
#define P_UART3_CLK 33
#define P_UART1DM_CLK 34
#define P_UART2DM_CLK 35
#define P_USB_HS_CLK 36 /* High speed USB core clock */
#define P_USB_HS_PCLK 37 /* High speed USB pbus clock */
#define P_USB_OTG_CLK 38 /* Full speed USB clock */
#define P_VDC_CLK 39 /* Video controller clock */
#define P_VFE_MDC_CLK 40 /* Camera / Video Front End clock */
#define P_VFE_CLK 41 /* VFE MDDI client clock */
#define P_MDP_LCDC_PCLK_CLK 42
#define P_MDP_LCDC_PAD_PCLK_CLK 43
#define P_MDP_VSYNC_CLK 44
#define P_SPI_CLK 45
#define P_VFE_AXI_CLK 46
#define P_USB_HS2_CLK 47 /* High speed USB 2 core clock */
#define P_USB_HS2_PCLK 48 /* High speed USB 2 pbus clock */
#define P_USB_HS3_CLK 49 /* High speed USB 3 core clock */
#define P_USB_HS3_PCLK 50 /* High speed USB 3 pbus clock */
#define P_GRP_PCLK 51 /* Graphics pbus clock */
#define P_USB_PHY_CLK 52 /* USB PHY clock */
#define P_USB_HS_CORE_CLK 53 /* High speed USB 1 core clock */
#define P_USB_HS2_CORE_CLK 54 /* High speed USB 2 core clock */
#define P_USB_HS3_CORE_CLK 55 /* High speed USB 3 core clock */
#define P_CAM_MCLK_CLK 56
#define P_CAMIF_PAD_PCLK 57
#define P_GRP_2D_CLK 58
#define P_GRP_2D_PCLK 59
#define P_I2S_CLK 60
#define P_JPEG_CLK 61
#define P_JPEG_PCLK 62
#define P_LPA_CODEC_CLK 63
#define P_LPA_CORE_CLK 64
#define P_LPA_PCLK 65
#define P_MDC_IO_CLK 66
#define P_MDC_PCLK 67
#define P_MFC_CLK 68
#define P_MFC_DIV2_CLK 69
#define P_MFC_PCLK 70
#define P_QUP_I2C_CLK 71
#define P_ROTATOR_IMEM_CLK 72
#define P_ROTATOR_PCLK 73
#define P_VFE_CAMIF_CLK 74
#define P_VFE_PCLK 75
#define P_VPE_CLK 76
#define P_I2C_2_CLK 77
#define P_MI2S_CODEC_RX_SCLK 78
#define P_MI2S_CODEC_RX_MCLK 79
#define P_MI2S_CODEC_TX_SCLK 80
#define P_MI2S_CODEC_TX_MCLK 81
#define P_PMDH_PCLK 82
#define P_EMDH_PCLK 83
#define P_SPI_PCLK 84
#define P_TSIF_PCLK 85
#define P_MDP_PCLK 86
#define P_SDAC_MCLK 87
#define P_MI2S_HDMI_CLK 88
#define P_MI2S_HDMI_MCLK 89
#define P_NR_CLKS 90
struct clk_ops;
extern struct clk_ops clk_ops_pcom;
#define CLK_PCOM(clk_name, clk_id, clk_dev, clk_flags) { \
.name = clk_name, \
.id = P_##clk_id, \
.ops = &clk_ops_pcom, \
.flags = clk_flags, \
.dev = clk_dev, \
.dbg_name = #clk_id, \
}
#endif
| turl/zeppelin_kernel | arch/arm/mach-msm/clock-pcom.h | C | gpl-2.0 | 6,909 |
///////////////////////////////////////////////////////////////////////////////
// For information as to what this class does, see the Javadoc, below. //
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, //
// 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph //
// Ramsey, and Clark Glymour. //
// //
// 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 //
///////////////////////////////////////////////////////////////////////////////
package edu.cmu.tetrad.search.mb;
import edu.cmu.tetrad.data.DataSet;
import edu.cmu.tetrad.data.IKnowledge;
import edu.cmu.tetrad.data.Knowledge2;
import edu.cmu.tetrad.graph.EdgeListGraph;
import edu.cmu.tetrad.graph.Graph;
import edu.cmu.tetrad.graph.Node;
import edu.cmu.tetrad.search.FgesOrienter;
import edu.cmu.tetrad.search.GraphSearch;
import edu.cmu.tetrad.search.IndependenceTest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implements the MMHC algorithm.
*
* @author Joseph Ramsey (this version).
*/
public class Mmhc implements GraphSearch {
/**
* The independence test used for the PC search.
*/
private IndependenceTest independenceTest;
/**
* The maximum number of nodes conditioned on in the search.
*/
private int depth = Integer.MAX_VALUE;
private DataSet data;
private IKnowledge knowledge = new Knowledge2();
//=============================CONSTRUCTORS==========================//
public Mmhc(IndependenceTest test, DataSet dataSet) {
this.depth = -1;
this.independenceTest = test;
this.data = dataSet;
}
//==============================PUBLIC METHODS========================//
public IndependenceTest getIndependenceTest() {
return independenceTest;
}
public int getDepth() {
return depth;
}
public long getElapsedTime() {
return 0;
}
/**
* Runs PC starting with a fully connected graph over all of the variables in the domain of the independence test.
*/
public Graph search() {
List<Node> variables = independenceTest.getVariables();
Mmmb mmmb = new Mmmb(independenceTest, getDepth(), true);
Map<Node, List<Node>> pc = new HashMap<>();
for (Node x : variables) {
pc.put(x, mmmb.getPc(x));
}
Graph graph = new EdgeListGraph();
for (Node x : variables) {
graph.addNode(x);
}
for (Node x : variables) {
for (Node y : pc.get(x)) {
if (!graph.isAdjacentTo(x, y)) {
graph.addUndirectedEdge(x, y);
}
}
}
FgesOrienter orienter = new FgesOrienter(data);
orienter.orient(graph);
return graph;
}
public IKnowledge getKnowledge() {
return knowledge;
}
public void setKnowledge(IKnowledge knowledge) {
if (knowledge == null) {
throw new NullPointerException();
}
this.knowledge = knowledge;
}
public void setDepth(int depth) {
this.depth = depth;
}
}
| ekummerfeld/GdistanceP | tetrad-lib/src/main/java/edu/cmu/tetrad/search/mb/Mmhc.java | Java | gpl-2.0 | 4,266 |
/*
* pata_ninja32.c - Ninja32 PATA for new ATA layer
* (C) 2007 Red Hat Inc
* Alan Cox <alan@redhat.com>
*
* Note: The controller like many controllers has shared timings for
* PIO and DMA. We thus flip to the DMA timings in dma_start and flip back
* in the dma_stop function. Thus we actually don't need a set_dmamode
* method as the PIO method is always called and will set the right PIO
* timing parameters.
*
* The Ninja32 Cardbus is not a generic SFF controller. Instead it is
* laid out as follows off BAR 0. This is based upon Mark Lord's delkin
* driver and the extensive analysis done by the BSD developers, notably
* ITOH Yasufumi.
*
* Base + 0x00 IRQ Status
* Base + 0x01 IRQ control
* Base + 0x02 Chipset control
* Base + 0x03 Unknown
* Base + 0x04 VDMA and reset control + wait bits
* Base + 0x08 BMIMBA
* Base + 0x0C DMA Length
* Base + 0x10 Taskfile
* Base + 0x18 BMDMA Status ?
* Base + 0x1C
* Base + 0x1D Bus master control
* bit 0 = enable
* bit 1 = 0 write/1 read
* bit 2 = 1 sgtable
* bit 3 = go
* bit 4-6 wait bits
* bit 7 = done
* Base + 0x1E AltStatus
* Base + 0x1F timing register
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#define DRV_NAME "pata_ninja32"
#define DRV_VERSION "0.0.1"
/**
* ninja32_set_piomode - set initial PIO mode data
* @ap: ATA interface
* @adev: ATA device
*
* Called to do the PIO mode setup. Our timing registers are shared
* but we want to set the PIO timing by default.
*/
static void ninja32_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
static u16 pio_timing[5] = {
0xd6, 0x85, 0x44, 0x33, 0x13
};
iowrite8(pio_timing[adev->pio_mode - XFER_PIO_0],
ap->ioaddr.bmdma_addr + 0x1f);
ap->private_data = adev;
}
static void ninja32_dev_select(struct ata_port *ap, unsigned int device)
{
struct ata_device *adev = &ap->link.device[device];
if (ap->private_data != adev) {
iowrite8(0xd6, ap->ioaddr.bmdma_addr + 0x1f);
ata_std_dev_select(ap, device);
ninja32_set_piomode(ap, adev);
}
}
static struct scsi_host_template ninja32_sht = {
.module = THIS_MODULE,
.name = DRV_NAME,
.ioctl = ata_scsi_ioctl,
.queuecommand = ata_scsi_queuecmd,
.can_queue = ATA_DEF_QUEUE,
.this_id = ATA_SHT_THIS_ID,
.sg_tablesize = LIBATA_MAX_PRD,
.cmd_per_lun = ATA_SHT_CMD_PER_LUN,
.emulated = ATA_SHT_EMULATED,
.use_clustering = ATA_SHT_USE_CLUSTERING,
.proc_name = DRV_NAME,
.dma_boundary = ATA_DMA_BOUNDARY,
.slave_configure = ata_scsi_slave_config,
.slave_destroy = ata_scsi_slave_destroy,
.bios_param = ata_std_bios_param,
};
static struct ata_port_operations ninja32_port_ops = {
.set_piomode = ninja32_set_piomode,
.mode_filter = ata_pci_default_filter,
.tf_load = ata_tf_load,
.tf_read = ata_tf_read,
.check_status = ata_check_status,
.exec_command = ata_exec_command,
.dev_select = ninja32_dev_select,
.freeze = ata_bmdma_freeze,
.thaw = ata_bmdma_thaw,
.error_handler = ata_bmdma_error_handler,
.post_internal_cmd = ata_bmdma_post_internal_cmd,
.cable_detect = ata_cable_40wire,
.bmdma_setup = ata_bmdma_setup,
.bmdma_start = ata_bmdma_start,
.bmdma_stop = ata_bmdma_stop,
.bmdma_status = ata_bmdma_status,
.qc_prep = ata_qc_prep,
.qc_issue = ata_qc_issue_prot,
.data_xfer = ata_data_xfer,
.irq_handler = ata_interrupt,
.irq_clear = ata_bmdma_irq_clear,
.irq_on = ata_irq_on,
.port_start = ata_sff_port_start,
};
static int ninja32_init_one(struct pci_dev *dev, const struct pci_device_id *id)
{
struct ata_host *host;
struct ata_port *ap;
void __iomem *base;
int rc;
host = ata_host_alloc(&dev->dev, 1);
if (!host)
return -ENOMEM;
ap = host->ports[0];
/* Set up the PCI device */
rc = pcim_enable_device(dev);
if (rc)
return rc;
rc = pcim_iomap_regions(dev, 1 << 0, DRV_NAME);
if (rc == -EBUSY)
pcim_pin_device(dev);
if (rc)
return rc;
host->iomap = pcim_iomap_table(dev);
rc = pci_set_dma_mask(dev, ATA_DMA_MASK);
if (rc)
return rc;
rc = pci_set_consistent_dma_mask(dev, ATA_DMA_MASK);
if (rc)
return rc;
pci_set_master(dev);
/* Set up the register mappings */
base = host->iomap[0];
if (!base)
return -ENOMEM;
ap->ops = &ninja32_port_ops;
ap->pio_mask = 0x1F;
ap->flags |= ATA_FLAG_SLAVE_POSS;
ap->ioaddr.cmd_addr = base + 0x10;
ap->ioaddr.ctl_addr = base + 0x1E;
ap->ioaddr.altstatus_addr = base + 0x1E;
ap->ioaddr.bmdma_addr = base;
ata_std_ports(&ap->ioaddr);
iowrite8(0x05, base + 0x01); /* Enable interrupt lines */
iowrite8(0xBE, base + 0x02); /* Burst, ?? setup */
iowrite8(0x01, base + 0x03); /* Unknown */
iowrite8(0x20, base + 0x04); /* WAIT0 */
iowrite8(0x8f, base + 0x05); /* Unknown */
iowrite8(0xa4, base + 0x1c); /* Unknown */
iowrite8(0x83, base + 0x1d); /* BMDMA control: WAIT0 */
/* FIXME: Should we disable them at remove ? */
return ata_host_activate(host, dev->irq, ata_interrupt,
IRQF_SHARED, &ninja32_sht);
}
static const struct pci_device_id ninja32[] = {
{ 0x1145, 0xf021, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 },
{ 0x1145, 0xf024, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 },
{ },
};
static struct pci_driver ninja32_pci_driver = {
.name = DRV_NAME,
.id_table = ninja32,
.probe = ninja32_init_one,
.remove = ata_pci_remove_one
};
static int __init ninja32_init(void)
{
return pci_register_driver(&ninja32_pci_driver);
}
static void __exit ninja32_exit(void)
{
pci_unregister_driver(&ninja32_pci_driver);
}
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("low-level driver for Ninja32 ATA");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, ninja32);
MODULE_VERSION(DRV_VERSION);
module_init(ninja32_init);
module_exit(ninja32_exit);
| jkoelndorfer/android-kernel-msm | drivers/ata/pata_ninja32.c | C | gpl-2.0 | 5,793 |
<?php
/*
* Local plugin enable/disable settings
* Auto-generated through plugin/extension manager
*
* NOTE: Plugins will not be added to this file unless there is a need to override a default setting. Plugins are
* enabled by default, unless having a 'disabled' file in their plugin folder.
*/
$plugins['authmysql'] = 0;
$plugins['authad'] = 0;
$plugins['authpgsql'] = 0;
$plugins['authldap'] = 0;
| emanuel-bs/omd | packages/dokuwiki/skel/etc/dokuwiki/plugins.local.php | PHP | gpl-2.0 | 410 |
/*
*
* Copyright (c) 2003
* John Maddock
*
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
*/
/*
* LOCATION: see http://www.boost.org for most recent version.
* FILE regex_iterator_example_2.cpp
* VERSION see <boost/version.hpp>
* DESCRIPTION: regex_iterator example 2: searches a cpp file for class definitions,
* using global data.
*/
#include <string>
#include <map>
#include <fstream>
#include <iostream>
#include <boost/regex.hpp>
using namespace std;
// purpose:
// takes the contents of a file in the form of a string
// and searches for all the C++ class definitions, storing
// their locations in a map of strings/int's
typedef std::map<std::string, std::string::difference_type, std::less<std::string> > map_type;
const char* re =
// possibly leading whitespace:
"^[[:space:]]*"
// possible template declaration:
"(template[[:space:]]*<[^;:{]+>[[:space:]]*)?"
// class or struct:
"(class|struct)[[:space:]]*"
// leading declspec macros etc:
"("
"\\<\\w+\\>"
"("
"[[:blank:]]*\\([^)]*\\)"
")?"
"[[:space:]]*"
")*"
// the class name
"(\\<\\w*\\>)[[:space:]]*"
// template specialisation parameters
"(<[^;:{]+>)?[[:space:]]*"
// terminate in { or :
"(\\{|:[^;\\{()]*\\{)";
boost::regex expression(re);
map_type class_index;
bool regex_callback(const boost::match_results<std::string::const_iterator>& what)
{
// what[0] contains the whole string
// what[5] contains the class name.
// what[6] contains the template specialisation if any.
// add class name and position to map:
class_index[what[5].str() + what[6].str()] = what.position(5);
return true;
}
void load_file(std::string& s, std::istream& is)
{
s.erase();
if(is.bad()) return;
s.reserve(is.rdbuf()->in_avail());
char c;
while(is.get(c))
{
if(s.capacity() == s.size())
s.reserve(s.capacity() * 3);
s.append(1, c);
}
}
int main(int argc, const char** argv)
{
std::string text;
for(int i = 1; i < argc; ++i)
{
cout << "Processing file " << argv[i] << endl;
std::ifstream fs(argv[i]);
load_file(text, fs);
fs.close();
// construct our iterators:
boost::sregex_iterator m1(text.begin(), text.end(), expression);
boost::sregex_iterator m2;
std::for_each(m1, m2, ®ex_callback);
// copy results:
cout << class_index.size() << " matches found" << endl;
map_type::iterator c, d;
c = class_index.begin();
d = class_index.end();
while(c != d)
{
cout << "class \"" << (*c).first << "\" found at index: " << (*c).second << endl;
++c;
}
class_index.erase(class_index.begin(), class_index.end());
}
return 0;
}
| scs/uclinux | lib/boost/boost_1_38_0/libs/regex/example/snippets/regex_iterator_example.cpp | C++ | gpl-2.0 | 2,963 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Ip.php 8934 2013-03-29 19:17:23Z btowles $
*/
/**
* @see Zend_Validate_Abstract
*/
require_once 'Zend/Validate/Abstract.php';
/**
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Validate_Ip extends Zend_Validate_Abstract
{
const NOT_IP_ADDRESS = 'notIpAddress';
/**
* @var array
*/
protected $_messageTemplates = array(
self::NOT_IP_ADDRESS => "'%value%' does not appear to be a valid IP address"
);
/**
* Defined by Zend_Validate_Interface
*
* Returns true if and only if $value is a valid IP address
*
* @param mixed $value
* @return boolean
*/
public function isValid($value)
{
$valueString = (string) $value;
$this->_setValue($valueString);
if (ip2long($valueString) === false) {
$this->_error();
return false;
}
return true;
}
}
| omesan/SiteLegionTacticalPainball | plugins/system/rokupdater/lib/vendor/maciek-kemnitz/phpquery/phpQuery/phpQuery/Zend/Validate/Ip.php | PHP | gpl-2.0 | 1,777 |
~\\
\begin{enumerate}
\item \upc{43,9}
\item 197
\end{enumerate}
| DrPLG/livre | 3-13 TRIGONOMETRIE/manuel_chapitre_2014_2SP3/2SP3/corrections/corr-AE-SP3-5.tex | TeX | gpl-2.0 | 66 |
<head>
<title>{#tagwrap_dlg.titleP}</title>
<script type="text/javascript" src="../../../tinymce/tiny_mce_popup.js"></script>
<script type="text/javascript" src="js/dialog.js"></script>
<link rel="stylesheet" type="text/css" href="css/tagwrap.css" />
</head>
<body>
<div class="y_logo_contener">
<img src="img/html5.png" alt="HTML5" />
</div>
<div class="yinstr">
<p>{#tagwrap_dlg.noteP}</p>
<p>{#tagwrap_dlg.noteP3}</p>
</div>
<form onSubmit="TagwrapDialog.insert();return false;" action="#" method="post" name="P_tag">
<div class="mceActionPanel">
<script type="text/javascript" language="javascript">
var jwl_sel_content4 = tinyMCE.activeEditor.selection.getContent();
</script>
{#tagwrap_dlg.noteP1} <input id="title_value" type="text" name="title" width="200px" value="" /> <em> {#tagwrap_dlg.noteP2}</em>
<br /><br />
</div>
<div style="margin-top:80px;"</div>
<div class="bottom">
<p><!--{#tagwrap_dlg.bottomnote}--></p>
<p class="pagelink_hover"><!--{#tagwrap_dlg.bottomnote2}--></p>
</div>
<script type="text/javascript" language="javascript">
function jwl_pass_form_data () {
var name = jwl_title = document.getElementsByName("title")[0].value;
}
</script>
<div class="mceActionPanel">
<div style="float:left;padding-top:5px">
<input type="button" id="insert" name="insert" value="{#insert}" onClick="jwl_pass_form_data();tinyMCE.execCommand('mceInsertContent',false,'<p style=\'' + jwl_title + '\'>' + jwl_sel_content4 + '</p>');tinyMCEPopup.close();" /> <input type="button" id="cancel" name="cancel" value="{#cancel}" onClick="tinyMCEPopup.close();" />
</div>
</div>
</form>
<span style="float:right;"><a target="_blank" href="http://www.joshlobe.com/2012/07/ultimate-tinymce-advanced-html-tags/"><img src="img/tinymce_help.png" /></a></span>
</body> | gacarrigan/WP-Site | wp-content/plugins/ultimate-tinymce/addons/tagwrap/tags/p.php | PHP | gpl-2.0 | 1,842 |
/*
* 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.
*/
/**
* @author Vera Y. Petrashkova
*/
package org.apache.harmony.security.tests.java.security.cert;
import java.security.cert.CertificateExpiredException;
import junit.framework.TestCase;
/**
* Tests for <code>DigestException</code> class constructors and methods.
*
*/
public class CertificateExpiredExceptionTest extends TestCase {
public static void main(String[] args) {
}
/**
* Constructor for CertificateExpiredExceptionTests.
*
* @param arg0
*/
public CertificateExpiredExceptionTest(String arg0) {
super(arg0);
}
static String[] msgs = {
"",
"Check new message",
"Check new message Check new message Check new message Check new message Check new message" };
static Throwable tCause = new Throwable("Throwable for exception");
/**
* Test for <code>CertificateExpiredException()</code> constructor
* Assertion: constructs CertificateExpiredException with no detail message
*/
public void testCertificateExpiredException01() {
CertificateExpiredException tE = new CertificateExpiredException();
assertNull("getMessage() must return null.", tE.getMessage());
assertNull("getCause() must return null", tE.getCause());
}
/**
* Test for <code>CertificateExpiredException(String)</code> constructor
* Assertion: constructs CertificateExpiredException with detail message
* msg. Parameter <code>msg</code> is not null.
*/
public void testCertificateExpiredException02() {
CertificateExpiredException tE;
for (int i = 0; i < msgs.length; i++) {
tE = new CertificateExpiredException(msgs[i]);
assertEquals("getMessage() must return: ".concat(msgs[i]), tE
.getMessage(), msgs[i]);
assertNull("getCause() must return null", tE.getCause());
}
}
/**
* Test for <code>CertificateExpiredException(String)</code> constructor
* Assertion: constructs CertificateExpiredException when <code>msg</code>
* is null
*/
public void testCertificateExpiredException03() {
String msg = null;
CertificateExpiredException tE = new CertificateExpiredException(msg);
assertNull("getMessage() must return null.", tE.getMessage());
assertNull("getCause() must return null", tE.getCause());
}
}
| rex-xxx/mt6572_x201 | external/apache-harmony/security/src/test/api/java/org/apache/harmony/security/tests/java/security/cert/CertificateExpiredExceptionTest.java | Java | gpl-2.0 | 3,216 |
/*
* Bridge multicast support.
*
* Copyright (c) 2010 Herbert Xu <herbert@gondor.apana.org.au>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
*/
#include <linux/err.h>
#include <linux/if_ether.h>
#include <linux/igmp.h>
#include <linux/jhash.h>
#include <linux/kernel.h>
#include <linux/log2.h>
#include <linux/netdevice.h>
#include <linux/netfilter_bridge.h>
#include <linux/random.h>
#include <linux/rculist.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <linux/timer.h>
#include <net/ip.h>
#if IS_ENABLED(CONFIG_IPV6)
#include <net/ipv6.h>
#include <net/mld.h>
#include <net/addrconf.h>
#include <net/ip6_checksum.h>
#endif
#include "br_private.h"
#define mlock_dereference(X, br) \
rcu_dereference_protected(X, lockdep_is_held(&br->multicast_lock))
#if IS_ENABLED(CONFIG_IPV6)
static inline int ipv6_is_transient_multicast(const struct in6_addr *addr)
{
if (ipv6_addr_is_multicast(addr) && IPV6_ADDR_MC_FLAG_TRANSIENT(addr))
return 1;
return 0;
}
#endif
static inline int br_ip_equal(const struct br_ip *a, const struct br_ip *b)
{
if (a->proto != b->proto)
return 0;
switch (a->proto) {
case htons(ETH_P_IP):
return a->u.ip4 == b->u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
case htons(ETH_P_IPV6):
return ipv6_addr_equal(&a->u.ip6, &b->u.ip6);
#endif
}
return 0;
}
static inline int __br_ip4_hash(struct net_bridge_mdb_htable *mdb, __be32 ip)
{
return jhash_1word(mdb->secret, (__force u32)ip) & (mdb->max - 1);
}
#if IS_ENABLED(CONFIG_IPV6)
static inline int __br_ip6_hash(struct net_bridge_mdb_htable *mdb,
const struct in6_addr *ip)
{
return jhash2((__force u32 *)ip->s6_addr32, 4, mdb->secret) & (mdb->max - 1);
}
#endif
static inline int br_ip_hash(struct net_bridge_mdb_htable *mdb,
struct br_ip *ip)
{
switch (ip->proto) {
case htons(ETH_P_IP):
return __br_ip4_hash(mdb, ip->u.ip4);
#if IS_ENABLED(CONFIG_IPV6)
case htons(ETH_P_IPV6):
return __br_ip6_hash(mdb, &ip->u.ip6);
#endif
}
return 0;
}
static struct net_bridge_mdb_entry *__br_mdb_ip_get(
struct net_bridge_mdb_htable *mdb, struct br_ip *dst, int hash)
{
struct net_bridge_mdb_entry *mp;
struct hlist_node *p;
hlist_for_each_entry_rcu(mp, p, &mdb->mhash[hash], hlist[mdb->ver]) {
if (br_ip_equal(&mp->addr, dst))
return mp;
}
return NULL;
}
static struct net_bridge_mdb_entry *br_mdb_ip_get(
struct net_bridge_mdb_htable *mdb, struct br_ip *dst)
{
if (!mdb)
return NULL;
return __br_mdb_ip_get(mdb, dst, br_ip_hash(mdb, dst));
}
static struct net_bridge_mdb_entry *br_mdb_ip4_get(
struct net_bridge_mdb_htable *mdb, __be32 dst)
{
struct br_ip br_dst;
br_dst.u.ip4 = dst;
br_dst.proto = htons(ETH_P_IP);
return br_mdb_ip_get(mdb, &br_dst);
}
#if IS_ENABLED(CONFIG_IPV6)
static struct net_bridge_mdb_entry *br_mdb_ip6_get(
struct net_bridge_mdb_htable *mdb, const struct in6_addr *dst)
{
struct br_ip br_dst;
br_dst.u.ip6 = *dst;
br_dst.proto = htons(ETH_P_IPV6);
return br_mdb_ip_get(mdb, &br_dst);
}
#endif
struct net_bridge_mdb_entry *br_mdb_get(struct net_bridge *br,
struct sk_buff *skb)
{
struct net_bridge_mdb_htable *mdb = rcu_dereference(br->mdb);
struct br_ip ip;
int i = 0;
ip.u.ip4 = 0;
for (i=0; i<16; i++)
ip.u.ip6.s6_addr[i] = 0;
if (br->multicast_disabled)
return NULL;
if (BR_INPUT_SKB_CB(skb)->igmp)
return NULL;
ip.proto = skb->protocol;
switch (skb->protocol) {
case htons(ETH_P_IP):
ip.u.ip4 = ip_hdr(skb)->daddr;
break;
#if IS_ENABLED(CONFIG_IPV6)
case htons(ETH_P_IPV6):
ip.u.ip6 = ipv6_hdr(skb)->daddr;
break;
#endif
default:
return NULL;
}
return br_mdb_ip_get(mdb, &ip);
}
static void br_mdb_free(struct rcu_head *head)
{
struct net_bridge_mdb_htable *mdb =
container_of(head, struct net_bridge_mdb_htable, rcu);
struct net_bridge_mdb_htable *old = mdb->old;
mdb->old = NULL;
kfree(old->mhash);
kfree(old);
}
static int br_mdb_copy(struct net_bridge_mdb_htable *new,
struct net_bridge_mdb_htable *old,
int elasticity)
{
struct net_bridge_mdb_entry *mp;
struct hlist_node *p;
int maxlen;
int len;
int i;
for (i = 0; i < old->max; i++)
hlist_for_each_entry(mp, p, &old->mhash[i], hlist[old->ver])
hlist_add_head(&mp->hlist[new->ver],
&new->mhash[br_ip_hash(new, &mp->addr)]);
if (!elasticity)
return 0;
maxlen = 0;
for (i = 0; i < new->max; i++) {
len = 0;
hlist_for_each_entry(mp, p, &new->mhash[i], hlist[new->ver])
len++;
if (len > maxlen)
maxlen = len;
}
return maxlen > elasticity ? -EINVAL : 0;
}
static void br_multicast_free_pg(struct rcu_head *head)
{
struct net_bridge_port_group *p =
container_of(head, struct net_bridge_port_group, rcu);
kfree(p);
}
static void br_multicast_free_group(struct rcu_head *head)
{
struct net_bridge_mdb_entry *mp =
container_of(head, struct net_bridge_mdb_entry, rcu);
kfree(mp);
}
static void br_multicast_group_expired(unsigned long data)
{
struct net_bridge_mdb_entry *mp = (void *)data;
struct net_bridge *br = mp->br;
struct net_bridge_mdb_htable *mdb;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) || timer_pending(&mp->timer))
goto out;
mp->mglist = false;
if (mp->ports)
goto out;
mdb = mlock_dereference(br->mdb, br);
hlist_del_rcu(&mp->hlist[mdb->ver]);
mdb->size--;
call_rcu_bh(&mp->rcu, br_multicast_free_group);
out:
spin_unlock(&br->multicast_lock);
}
static void br_multicast_del_pg(struct net_bridge *br,
struct net_bridge_port_group *pg)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
mdb = mlock_dereference(br->mdb, br);
mp = br_mdb_ip_get(mdb, &pg->addr);
if (WARN_ON(!mp))
return;
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (p != pg)
continue;
rcu_assign_pointer(*pp, p->next);
hlist_del_init(&p->mglist);
del_timer(&p->timer);
call_rcu_bh(&p->rcu, br_multicast_free_pg);
if (!mp->ports && !mp->mglist &&
netif_running(br->dev))
mod_timer(&mp->timer, jiffies);
return;
}
WARN_ON(1);
}
static void br_multicast_port_group_expired(unsigned long data)
{
struct net_bridge_port_group *pg = (void *)data;
struct net_bridge *br = pg->port->br;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) || timer_pending(&pg->timer) ||
hlist_unhashed(&pg->mglist))
goto out;
br_multicast_del_pg(br, pg);
out:
spin_unlock(&br->multicast_lock);
}
static int br_mdb_rehash(struct net_bridge_mdb_htable __rcu **mdbp, int max,
int elasticity)
{
struct net_bridge_mdb_htable *old = rcu_dereference_protected(*mdbp, 1);
struct net_bridge_mdb_htable *mdb;
int err;
mdb = kmalloc(sizeof(*mdb), GFP_ATOMIC);
if (!mdb)
return -ENOMEM;
mdb->max = max;
mdb->old = old;
mdb->mhash = kzalloc(max * sizeof(*mdb->mhash), GFP_ATOMIC);
if (!mdb->mhash) {
kfree(mdb);
return -ENOMEM;
}
mdb->size = old ? old->size : 0;
mdb->ver = old ? old->ver ^ 1 : 0;
if (!old || elasticity)
get_random_bytes(&mdb->secret, sizeof(mdb->secret));
else
mdb->secret = old->secret;
if (!old)
goto out;
err = br_mdb_copy(mdb, old, elasticity);
if (err) {
kfree(mdb->mhash);
kfree(mdb);
return err;
}
call_rcu_bh(&mdb->rcu, br_mdb_free);
out:
rcu_assign_pointer(*mdbp, mdb);
return 0;
}
static struct sk_buff *br_ip4_multicast_alloc_query(struct net_bridge *br,
__be32 group)
{
struct sk_buff *skb;
struct igmphdr *ih;
struct ethhdr *eth;
struct iphdr *iph;
skb = netdev_alloc_skb_ip_align(br->dev, sizeof(*eth) + sizeof(*iph) +
sizeof(*ih) + 4);
if (!skb)
goto out;
skb->protocol = htons(ETH_P_IP);
skb_reset_mac_header(skb);
eth = eth_hdr(skb);
memcpy(eth->h_source, br->dev->dev_addr, 6);
eth->h_dest[0] = 1;
eth->h_dest[1] = 0;
eth->h_dest[2] = 0x5e;
eth->h_dest[3] = 0;
eth->h_dest[4] = 0;
eth->h_dest[5] = 1;
eth->h_proto = htons(ETH_P_IP);
skb_put(skb, sizeof(*eth));
skb_set_network_header(skb, skb->len);
iph = ip_hdr(skb);
iph->version = 4;
iph->ihl = 6;
iph->tos = 0xc0;
iph->tot_len = htons(sizeof(*iph) + sizeof(*ih) + 4);
iph->id = 0;
iph->frag_off = htons(IP_DF);
iph->ttl = 1;
iph->protocol = IPPROTO_IGMP;
iph->saddr = 0;
iph->daddr = htonl(INADDR_ALLHOSTS_GROUP);
((u8 *)&iph[1])[0] = IPOPT_RA;
((u8 *)&iph[1])[1] = 4;
((u8 *)&iph[1])[2] = 0;
((u8 *)&iph[1])[3] = 0;
ip_send_check(iph);
skb_put(skb, 24);
skb_set_transport_header(skb, skb->len);
ih = igmp_hdr(skb);
ih->type = IGMP_HOST_MEMBERSHIP_QUERY;
ih->code = (group ? br->multicast_last_member_interval :
br->multicast_query_response_interval) /
(HZ / IGMP_TIMER_SCALE);
ih->group = group;
ih->csum = 0;
ih->csum = ip_compute_csum((void *)ih, sizeof(struct igmphdr));
skb_put(skb, sizeof(*ih));
__skb_pull(skb, sizeof(*eth));
out:
return skb;
}
#if IS_ENABLED(CONFIG_IPV6)
static struct sk_buff *br_ip6_multicast_alloc_query(struct net_bridge *br,
const struct in6_addr *group)
{
struct sk_buff *skb;
struct ipv6hdr *ip6h;
struct mld_msg *mldq;
struct ethhdr *eth;
u8 *hopopt;
unsigned long interval;
skb = netdev_alloc_skb_ip_align(br->dev, sizeof(*eth) + sizeof(*ip6h) +
8 + sizeof(*mldq));
if (!skb)
goto out;
skb->protocol = htons(ETH_P_IPV6);
/* Ethernet header */
skb_reset_mac_header(skb);
eth = eth_hdr(skb);
memcpy(eth->h_source, br->dev->dev_addr, 6);
eth->h_proto = htons(ETH_P_IPV6);
skb_put(skb, sizeof(*eth));
/* IPv6 header + HbH option */
skb_set_network_header(skb, skb->len);
ip6h = ipv6_hdr(skb);
*(__force __be32 *)ip6h = htonl(0x60000000);
ip6h->payload_len = htons(8 + sizeof(*mldq));
ip6h->nexthdr = IPPROTO_HOPOPTS;
ip6h->hop_limit = 1;
ipv6_addr_set(&ip6h->daddr, htonl(0xff020000), 0, 0, htonl(1));
if (ipv6_dev_get_saddr(dev_net(br->dev), br->dev, &ip6h->daddr, 0,
&ip6h->saddr)) {
kfree_skb(skb);
return NULL;
}
ipv6_eth_mc_map(&ip6h->daddr, eth->h_dest);
hopopt = (u8 *)(ip6h + 1);
hopopt[0] = IPPROTO_ICMPV6; /* next hdr */
hopopt[1] = 0; /* length of HbH */
hopopt[2] = IPV6_TLV_ROUTERALERT; /* Router Alert */
hopopt[3] = 2; /* Length of RA Option */
hopopt[4] = 0; /* Type = 0x0000 (MLD) */
hopopt[5] = 0;
hopopt[6] = IPV6_TLV_PAD0; /* Pad0 */
hopopt[7] = IPV6_TLV_PAD0; /* Pad0 */
skb_put(skb, sizeof(*ip6h) + 8);
/* ICMPv6 */
skb_set_transport_header(skb, skb->len);
mldq = (struct mld_msg *) icmp6_hdr(skb);
interval = ipv6_addr_any(group) ?
br->multicast_query_response_interval :
br->multicast_last_member_interval;
mldq->mld_type = ICMPV6_MGM_QUERY;
mldq->mld_code = 0;
mldq->mld_cksum = 0;
mldq->mld_maxdelay = htons((u16)jiffies_to_msecs(interval));
mldq->mld_reserved = 0;
mldq->mld_mca = *group;
/* checksum */
mldq->mld_cksum = csum_ipv6_magic(&ip6h->saddr, &ip6h->daddr,
sizeof(*mldq), IPPROTO_ICMPV6,
csum_partial(mldq,
sizeof(*mldq), 0));
skb_put(skb, sizeof(*mldq));
__skb_pull(skb, sizeof(*eth));
out:
return skb;
}
#endif
static struct sk_buff *br_multicast_alloc_query(struct net_bridge *br,
struct br_ip *addr)
{
switch (addr->proto) {
case htons(ETH_P_IP):
return br_ip4_multicast_alloc_query(br, addr->u.ip4);
#if IS_ENABLED(CONFIG_IPV6)
case htons(ETH_P_IPV6):
return br_ip6_multicast_alloc_query(br, &addr->u.ip6);
#endif
}
return NULL;
}
static struct net_bridge_mdb_entry *br_multicast_get_group(
struct net_bridge *br, struct net_bridge_port *port,
struct br_ip *group, int hash)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
struct hlist_node *p;
unsigned count = 0;
unsigned max;
int elasticity;
int err;
mdb = rcu_dereference_protected(br->mdb, 1);
hlist_for_each_entry(mp, p, &mdb->mhash[hash], hlist[mdb->ver]) {
count++;
if (unlikely(br_ip_equal(group, &mp->addr)))
return mp;
}
elasticity = 0;
max = mdb->max;
if (unlikely(count > br->hash_elasticity && count)) {
if (net_ratelimit())
br_info(br, "Multicast hash table "
"chain limit reached: %s\n",
port ? port->dev->name : br->dev->name);
elasticity = br->hash_elasticity;
}
if (mdb->size >= max) {
max *= 2;
if (unlikely(max >= br->hash_max)) {
br_warn(br, "Multicast hash table maximum "
"reached, disabling snooping: %s, %d\n",
port ? port->dev->name : br->dev->name, max);
err = -E2BIG;
disable:
br->multicast_disabled = 1;
goto err;
}
}
if (max > mdb->max || elasticity) {
if (mdb->old) {
if (net_ratelimit())
br_info(br, "Multicast hash table "
"on fire: %s\n",
port ? port->dev->name : br->dev->name);
err = -EEXIST;
goto err;
}
err = br_mdb_rehash(&br->mdb, max, elasticity);
if (err) {
br_warn(br, "Cannot rehash multicast "
"hash table, disabling snooping: %s, %d, %d\n",
port ? port->dev->name : br->dev->name,
mdb->size, err);
goto disable;
}
err = -EAGAIN;
goto err;
}
return NULL;
err:
mp = ERR_PTR(err);
return mp;
}
static struct net_bridge_mdb_entry *br_multicast_new_group(
struct net_bridge *br, struct net_bridge_port *port,
struct br_ip *group)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
int hash;
int err;
mdb = rcu_dereference_protected(br->mdb, 1);
if (!mdb) {
err = br_mdb_rehash(&br->mdb, BR_HASH_SIZE, 0);
if (err)
return ERR_PTR(err);
goto rehash;
}
hash = br_ip_hash(mdb, group);
mp = br_multicast_get_group(br, port, group, hash);
switch (PTR_ERR(mp)) {
case 0:
break;
case -EAGAIN:
rehash:
mdb = rcu_dereference_protected(br->mdb, 1);
hash = br_ip_hash(mdb, group);
break;
default:
goto out;
}
mp = kzalloc(sizeof(*mp), GFP_ATOMIC);
if (unlikely(!mp))
return ERR_PTR(-ENOMEM);
mp->br = br;
mp->addr = *group;
setup_timer(&mp->timer, br_multicast_group_expired,
(unsigned long)mp);
hlist_add_head_rcu(&mp->hlist[mdb->ver], &mdb->mhash[hash]);
mdb->size++;
out:
return mp;
}
static int br_multicast_add_group(struct net_bridge *br,
struct net_bridge_port *port,
struct br_ip *group)
{
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
unsigned long now = jiffies;
int err;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) ||
(port && port->state == BR_STATE_DISABLED))
goto out;
mp = br_multicast_new_group(br, port, group);
err = PTR_ERR(mp);
if (IS_ERR(mp))
goto err;
if (!port) {
mp->mglist = true;
mod_timer(&mp->timer, now + br->multicast_membership_interval);
goto out;
}
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (p->port == port)
goto found;
if ((unsigned long)p->port < (unsigned long)port)
break;
}
p = kzalloc(sizeof(*p), GFP_ATOMIC);
err = -ENOMEM;
if (unlikely(!p))
goto err;
p->addr = *group;
p->port = port;
p->next = *pp;
hlist_add_head(&p->mglist, &port->mglist);
setup_timer(&p->timer, br_multicast_port_group_expired,
(unsigned long)p);
rcu_assign_pointer(*pp, p);
found:
mod_timer(&p->timer, now + br->multicast_membership_interval);
out:
err = 0;
err:
spin_unlock(&br->multicast_lock);
return err;
}
static int br_ip4_multicast_add_group(struct net_bridge *br,
struct net_bridge_port *port,
__be32 group)
{
struct br_ip br_group;
if (ipv4_is_local_multicast(group))
return 0;
br_group.u.ip4 = group;
br_group.proto = htons(ETH_P_IP);
return br_multicast_add_group(br, port, &br_group);
}
#if IS_ENABLED(CONFIG_IPV6)
static int br_ip6_multicast_add_group(struct net_bridge *br,
struct net_bridge_port *port,
const struct in6_addr *group)
{
struct br_ip br_group;
if (!ipv6_is_transient_multicast(group))
return 0;
br_group.u.ip6 = *group;
br_group.proto = htons(ETH_P_IPV6);
return br_multicast_add_group(br, port, &br_group);
}
#endif
static void br_multicast_router_expired(unsigned long data)
{
struct net_bridge_port *port = (void *)data;
struct net_bridge *br = port->br;
spin_lock(&br->multicast_lock);
if (port->multicast_router != 1 ||
timer_pending(&port->multicast_router_timer) ||
hlist_unhashed(&port->rlist))
goto out;
hlist_del_init_rcu(&port->rlist);
out:
spin_unlock(&br->multicast_lock);
}
static void br_multicast_local_router_expired(unsigned long data)
{
}
static void __br_multicast_send_query(struct net_bridge *br,
struct net_bridge_port *port,
struct br_ip *ip)
{
struct sk_buff *skb;
skb = br_multicast_alloc_query(br, ip);
if (!skb)
return;
if (port) {
__skb_push(skb, sizeof(struct ethhdr));
skb->dev = port->dev;
NF_HOOK(NFPROTO_BRIDGE, NF_BR_LOCAL_OUT, skb, NULL, skb->dev,
dev_queue_xmit);
} else
netif_rx(skb);
}
static void br_multicast_send_query(struct net_bridge *br,
struct net_bridge_port *port, u32 sent)
{
unsigned long time;
struct br_ip br_group;
if (!netif_running(br->dev) || br->multicast_disabled ||
timer_pending(&br->multicast_querier_timer))
return;
memset(&br_group.u, 0, sizeof(br_group.u));
br_group.proto = htons(ETH_P_IP);
__br_multicast_send_query(br, port, &br_group);
#if IS_ENABLED(CONFIG_IPV6)
br_group.proto = htons(ETH_P_IPV6);
__br_multicast_send_query(br, port, &br_group);
#endif
time = jiffies;
time += sent < br->multicast_startup_query_count ?
br->multicast_startup_query_interval :
br->multicast_query_interval;
mod_timer(port ? &port->multicast_query_timer :
&br->multicast_query_timer, time);
}
static void br_multicast_port_query_expired(unsigned long data)
{
struct net_bridge_port *port = (void *)data;
struct net_bridge *br = port->br;
spin_lock(&br->multicast_lock);
if (port->state == BR_STATE_DISABLED ||
port->state == BR_STATE_BLOCKING)
goto out;
if (port->multicast_startup_queries_sent <
br->multicast_startup_query_count)
port->multicast_startup_queries_sent++;
br_multicast_send_query(port->br, port,
port->multicast_startup_queries_sent);
out:
spin_unlock(&br->multicast_lock);
}
void br_multicast_add_port(struct net_bridge_port *port)
{
port->multicast_router = 1;
setup_timer(&port->multicast_router_timer, br_multicast_router_expired,
(unsigned long)port);
setup_timer(&port->multicast_query_timer,
br_multicast_port_query_expired, (unsigned long)port);
}
void br_multicast_del_port(struct net_bridge_port *port)
{
del_timer_sync(&port->multicast_router_timer);
}
static void __br_multicast_enable_port(struct net_bridge_port *port)
{
port->multicast_startup_queries_sent = 0;
if (try_to_del_timer_sync(&port->multicast_query_timer) >= 0 ||
del_timer(&port->multicast_query_timer))
mod_timer(&port->multicast_query_timer, jiffies);
}
void br_multicast_enable_port(struct net_bridge_port *port)
{
struct net_bridge *br = port->br;
spin_lock(&br->multicast_lock);
if (br->multicast_disabled || !netif_running(br->dev))
goto out;
__br_multicast_enable_port(port);
out:
spin_unlock(&br->multicast_lock);
}
void br_multicast_disable_port(struct net_bridge_port *port)
{
struct net_bridge *br = port->br;
struct net_bridge_port_group *pg;
struct hlist_node *p, *n;
spin_lock(&br->multicast_lock);
hlist_for_each_entry_safe(pg, p, n, &port->mglist, mglist)
br_multicast_del_pg(br, pg);
if (!hlist_unhashed(&port->rlist))
hlist_del_init_rcu(&port->rlist);
del_timer(&port->multicast_router_timer);
del_timer(&port->multicast_query_timer);
spin_unlock(&br->multicast_lock);
}
static int br_ip4_multicast_igmp3_report(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
struct igmpv3_report *ih;
struct igmpv3_grec *grec;
int i;
int len;
int num;
int type;
int err = 0;
__be32 group;
if (!pskb_may_pull(skb, sizeof(*ih)))
return -EINVAL;
ih = igmpv3_report_hdr(skb);
num = ntohs(ih->ngrec);
len = sizeof(*ih);
for (i = 0; i < num; i++) {
len += sizeof(*grec);
if (!pskb_may_pull(skb, len))
return -EINVAL;
grec = (void *)(skb->data + len - sizeof(*grec));
group = grec->grec_mca;
type = grec->grec_type;
len += ntohs(grec->grec_nsrcs) * 4;
if (!pskb_may_pull(skb, len))
return -EINVAL;
/* We treat this as an IGMPv2 report for now. */
switch (type) {
case IGMPV3_MODE_IS_INCLUDE:
case IGMPV3_MODE_IS_EXCLUDE:
case IGMPV3_CHANGE_TO_INCLUDE:
case IGMPV3_CHANGE_TO_EXCLUDE:
case IGMPV3_ALLOW_NEW_SOURCES:
case IGMPV3_BLOCK_OLD_SOURCES:
break;
default:
continue;
}
err = br_ip4_multicast_add_group(br, port, group);
if (err)
break;
}
return err;
}
#if IS_ENABLED(CONFIG_IPV6)
static int br_ip6_multicast_mld2_report(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
struct icmp6hdr *icmp6h;
struct mld2_grec *grec;
int i;
int len;
int num;
int err = 0;
if (!pskb_may_pull(skb, sizeof(*icmp6h)))
return -EINVAL;
icmp6h = icmp6_hdr(skb);
num = ntohs(icmp6h->icmp6_dataun.un_data16[1]);
len = sizeof(*icmp6h);
for (i = 0; i < num; i++) {
__be16 *nsrcs, _nsrcs;
nsrcs = skb_header_pointer(skb,
len + offsetof(struct mld2_grec,
grec_nsrcs),
sizeof(_nsrcs), &_nsrcs);
if (!nsrcs)
return -EINVAL;
if (!pskb_may_pull(skb,
len + sizeof(*grec) +
sizeof(struct in6_addr) * ntohs(*nsrcs)))
return -EINVAL;
grec = (struct mld2_grec *)(skb->data + len);
len += sizeof(*grec) +
sizeof(struct in6_addr) * ntohs(*nsrcs);
/* We treat these as MLDv1 reports for now. */
switch (grec->grec_type) {
case MLD2_MODE_IS_INCLUDE:
case MLD2_MODE_IS_EXCLUDE:
case MLD2_CHANGE_TO_INCLUDE:
case MLD2_CHANGE_TO_EXCLUDE:
case MLD2_ALLOW_NEW_SOURCES:
case MLD2_BLOCK_OLD_SOURCES:
break;
default:
continue;
}
err = br_ip6_multicast_add_group(br, port, &grec->grec_mca);
if (err)
break;
}
return err;
}
#endif
/*
* Add port to rotuer_list
* list is maintained ordered by pointer value
* and locked by br->multicast_lock and RCU
*/
static void br_multicast_add_router(struct net_bridge *br,
struct net_bridge_port *port)
{
struct net_bridge_port *p;
struct hlist_node *n, *slot = NULL;
if (!hlist_unhashed(&port->rlist))
return;
hlist_for_each_entry(p, n, &br->router_list, rlist) {
if ((unsigned long) port >= (unsigned long) p)
break;
slot = n;
}
if (slot)
hlist_add_after_rcu(slot, &port->rlist);
else
hlist_add_head_rcu(&port->rlist, &br->router_list);
}
static void br_multicast_mark_router(struct net_bridge *br,
struct net_bridge_port *port)
{
unsigned long now = jiffies;
if (!port) {
if (br->multicast_router == 1)
mod_timer(&br->multicast_router_timer,
now + br->multicast_querier_interval);
return;
}
if (port->multicast_router != 1)
return;
br_multicast_add_router(br, port);
mod_timer(&port->multicast_router_timer,
now + br->multicast_querier_interval);
}
static void br_multicast_query_received(struct net_bridge *br,
struct net_bridge_port *port,
int saddr)
{
if (saddr)
mod_timer(&br->multicast_querier_timer,
jiffies + br->multicast_querier_interval);
else if (timer_pending(&br->multicast_querier_timer))
return;
br_multicast_mark_router(br, port);
}
static int br_ip4_multicast_query(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
const struct iphdr *iph = ip_hdr(skb);
struct igmphdr *ih = igmp_hdr(skb);
struct net_bridge_mdb_entry *mp;
struct igmpv3_query *ih3;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
unsigned long max_delay;
unsigned long now = jiffies;
__be32 group;
int err = 0;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) ||
(port && port->state == BR_STATE_DISABLED))
goto out;
br_multicast_query_received(br, port, !!iph->saddr);
group = ih->group;
if (skb->len == sizeof(*ih)) {
max_delay = ih->code * (HZ / IGMP_TIMER_SCALE);
if (!max_delay) {
max_delay = 10 * HZ;
group = 0;
}
} else {
if (!pskb_may_pull(skb, sizeof(struct igmpv3_query))) {
err = -EINVAL;
goto out;
}
ih3 = igmpv3_query_hdr(skb);
if (ih3->nsrcs)
goto out;
max_delay = ih3->code ?
IGMPV3_MRC(ih3->code) * (HZ / IGMP_TIMER_SCALE) : 1;
}
if (!group)
goto out;
mp = br_mdb_ip4_get(mlock_dereference(br->mdb, br), group);
if (!mp)
goto out;
max_delay *= br->multicast_last_member_count;
if (mp->mglist &&
(timer_pending(&mp->timer) ?
time_after(mp->timer.expires, now + max_delay) :
try_to_del_timer_sync(&mp->timer) >= 0))
mod_timer(&mp->timer, now + max_delay);
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (timer_pending(&p->timer) ?
time_after(p->timer.expires, now + max_delay) :
try_to_del_timer_sync(&p->timer) >= 0)
mod_timer(&p->timer, now + max_delay);
}
out:
spin_unlock(&br->multicast_lock);
return err;
}
#if IS_ENABLED(CONFIG_IPV6)
static int br_ip6_multicast_query(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
const struct ipv6hdr *ip6h = ipv6_hdr(skb);
struct mld_msg *mld = (struct mld_msg *) icmp6_hdr(skb);
struct net_bridge_mdb_entry *mp;
struct mld2_query *mld2q;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
unsigned long max_delay;
unsigned long now = jiffies;
const struct in6_addr *group = NULL;
int err = 0;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) ||
(port && port->state == BR_STATE_DISABLED))
goto out;
br_multicast_query_received(br, port, !ipv6_addr_any(&ip6h->saddr));
/* RFC2710+RFC3810 (MLDv1+MLDv2) require link-local source addresses */
if (!(ipv6_addr_type(&ip6h->saddr) & IPV6_ADDR_LINKLOCAL)) {
err = -EINVAL;
goto out;
}
if (skb->len == sizeof(*mld)) {
if (!pskb_may_pull(skb, sizeof(*mld))) {
err = -EINVAL;
goto out;
}
mld = (struct mld_msg *) icmp6_hdr(skb);
max_delay = msecs_to_jiffies(htons(mld->mld_maxdelay));
if (max_delay)
group = &mld->mld_mca;
} else if (skb->len >= sizeof(*mld2q)) {
if (!pskb_may_pull(skb, sizeof(*mld2q))) {
err = -EINVAL;
goto out;
}
mld2q = (struct mld2_query *)icmp6_hdr(skb);
if (!mld2q->mld2q_nsrcs)
group = &mld2q->mld2q_mca;
max_delay = max(msecs_to_jiffies(MLDV2_MRC(ntohs(mld2q->mld2q_mrc))), 1UL);
}
if (!group)
goto out;
mp = br_mdb_ip6_get(mlock_dereference(br->mdb, br), group);
if (!mp)
goto out;
max_delay *= br->multicast_last_member_count;
if (mp->mglist &&
(timer_pending(&mp->timer) ?
time_after(mp->timer.expires, now + max_delay) :
try_to_del_timer_sync(&mp->timer) >= 0))
mod_timer(&mp->timer, now + max_delay);
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (timer_pending(&p->timer) ?
time_after(p->timer.expires, now + max_delay) :
try_to_del_timer_sync(&p->timer) >= 0)
mod_timer(&p->timer, now + max_delay);
}
out:
spin_unlock(&br->multicast_lock);
return err;
}
#endif
static void br_multicast_leave_group(struct net_bridge *br,
struct net_bridge_port *port,
struct br_ip *group)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p;
unsigned long now;
unsigned long time;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) ||
(port && port->state == BR_STATE_DISABLED) ||
timer_pending(&br->multicast_querier_timer))
goto out;
mdb = mlock_dereference(br->mdb, br);
mp = br_mdb_ip_get(mdb, group);
if (!mp)
goto out;
now = jiffies;
time = now + br->multicast_last_member_count *
br->multicast_last_member_interval;
if (!port) {
if (mp->mglist &&
(timer_pending(&mp->timer) ?
time_after(mp->timer.expires, time) :
try_to_del_timer_sync(&mp->timer) >= 0)) {
mod_timer(&mp->timer, time);
}
goto out;
}
for (p = mlock_dereference(mp->ports, br);
p != NULL;
p = mlock_dereference(p->next, br)) {
if (p->port != port)
continue;
if (!hlist_unhashed(&p->mglist) &&
(timer_pending(&p->timer) ?
time_after(p->timer.expires, time) :
try_to_del_timer_sync(&p->timer) >= 0)) {
mod_timer(&p->timer, time);
}
break;
}
out:
spin_unlock(&br->multicast_lock);
}
static void br_ip4_multicast_leave_group(struct net_bridge *br,
struct net_bridge_port *port,
__be32 group)
{
struct br_ip br_group;
if (ipv4_is_local_multicast(group))
return;
br_group.u.ip4 = group;
br_group.proto = htons(ETH_P_IP);
br_multicast_leave_group(br, port, &br_group);
}
#if IS_ENABLED(CONFIG_IPV6)
static void br_ip6_multicast_leave_group(struct net_bridge *br,
struct net_bridge_port *port,
const struct in6_addr *group)
{
struct br_ip br_group;
if (!ipv6_is_transient_multicast(group))
return;
br_group.u.ip6 = *group;
br_group.proto = htons(ETH_P_IPV6);
br_multicast_leave_group(br, port, &br_group);
}
#endif
static int br_multicast_ipv4_rcv(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
struct sk_buff *skb2 = skb;
const struct iphdr *iph;
struct igmphdr *ih;
unsigned len;
unsigned offset;
int err;
/* We treat OOM as packet loss for now. */
if (!pskb_may_pull(skb, sizeof(*iph)))
return -EINVAL;
iph = ip_hdr(skb);
if (iph->ihl < 5 || iph->version != 4)
return -EINVAL;
if (!pskb_may_pull(skb, ip_hdrlen(skb)))
return -EINVAL;
iph = ip_hdr(skb);
if (unlikely(ip_fast_csum((u8 *)iph, iph->ihl)))
return -EINVAL;
if (iph->protocol != IPPROTO_IGMP) {
if ((iph->daddr & IGMP_LOCAL_GROUP_MASK) != IGMP_LOCAL_GROUP)
BR_INPUT_SKB_CB(skb)->mrouters_only = 1;
return 0;
}
len = ntohs(iph->tot_len);
if (skb->len < len || len < ip_hdrlen(skb))
return -EINVAL;
if (skb->len > len) {
skb2 = skb_clone(skb, GFP_ATOMIC);
if (!skb2)
return -ENOMEM;
err = pskb_trim_rcsum(skb2, len);
if (err)
goto err_out;
}
len -= ip_hdrlen(skb2);
offset = skb_network_offset(skb2) + ip_hdrlen(skb2);
__skb_pull(skb2, offset);
skb_reset_transport_header(skb2);
err = -EINVAL;
if (!pskb_may_pull(skb2, sizeof(*ih)))
goto out;
switch (skb2->ip_summed) {
case CHECKSUM_COMPLETE:
if (!csum_fold(skb2->csum))
break;
/* fall through */
case CHECKSUM_NONE:
skb2->csum = 0;
if (skb_checksum_complete(skb2))
goto out;
}
err = 0;
BR_INPUT_SKB_CB(skb)->igmp = 1;
ih = igmp_hdr(skb2);
switch (ih->type) {
case IGMP_HOST_MEMBERSHIP_REPORT:
case IGMPV2_HOST_MEMBERSHIP_REPORT:
BR_INPUT_SKB_CB(skb)->mrouters_only = 1;
err = br_ip4_multicast_add_group(br, port, ih->group);
break;
case IGMPV3_HOST_MEMBERSHIP_REPORT:
err = br_ip4_multicast_igmp3_report(br, port, skb2);
break;
case IGMP_HOST_MEMBERSHIP_QUERY:
err = br_ip4_multicast_query(br, port, skb2);
break;
case IGMP_HOST_LEAVE_MESSAGE:
br_ip4_multicast_leave_group(br, port, ih->group);
break;
}
out:
__skb_push(skb2, offset);
err_out:
if (skb2 != skb)
kfree_skb(skb2);
return err;
}
#if IS_ENABLED(CONFIG_IPV6)
static int br_multicast_ipv6_rcv(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
struct sk_buff *skb2;
const struct ipv6hdr *ip6h;
u8 icmp6_type;
u8 nexthdr;
__be16 frag_off;
unsigned len;
int offset;
int err;
if (!pskb_may_pull(skb, sizeof(*ip6h)))
return -EINVAL;
ip6h = ipv6_hdr(skb);
/*
* We're interested in MLD messages only.
* - Version is 6
* - MLD has always Router Alert hop-by-hop option
* - But we do not support jumbrograms.
*/
if (ip6h->version != 6 ||
ip6h->nexthdr != IPPROTO_HOPOPTS ||
ip6h->payload_len == 0)
return 0;
len = ntohs(ip6h->payload_len) + sizeof(*ip6h);
if (skb->len < len)
return -EINVAL;
nexthdr = ip6h->nexthdr;
offset = ipv6_skip_exthdr(skb, sizeof(*ip6h), &nexthdr, &frag_off);
if (offset < 0 || nexthdr != IPPROTO_ICMPV6)
return 0;
/* Okay, we found ICMPv6 header */
skb2 = skb_clone(skb, GFP_ATOMIC);
if (!skb2)
return -ENOMEM;
err = -EINVAL;
if (!pskb_may_pull(skb2, offset + sizeof(struct icmp6hdr)))
goto out;
len -= offset - skb_network_offset(skb2);
__skb_pull(skb2, offset);
skb_reset_transport_header(skb2);
skb_postpull_rcsum(skb2, skb_network_header(skb2),
skb_network_header_len(skb2));
icmp6_type = icmp6_hdr(skb2)->icmp6_type;
switch (icmp6_type) {
case ICMPV6_MGM_QUERY:
case ICMPV6_MGM_REPORT:
case ICMPV6_MGM_REDUCTION:
case ICMPV6_MLD2_REPORT:
break;
default:
err = 0;
goto out;
}
/* Okay, we found MLD message. Check further. */
if (skb2->len > len) {
err = pskb_trim_rcsum(skb2, len);
if (err)
goto out;
err = -EINVAL;
}
ip6h = ipv6_hdr(skb2);
switch (skb2->ip_summed) {
case CHECKSUM_COMPLETE:
if (!csum_ipv6_magic(&ip6h->saddr, &ip6h->daddr, skb2->len,
IPPROTO_ICMPV6, skb2->csum))
break;
/*FALLTHROUGH*/
case CHECKSUM_NONE:
skb2->csum = ~csum_unfold(csum_ipv6_magic(&ip6h->saddr,
&ip6h->daddr,
skb2->len,
IPPROTO_ICMPV6, 0));
if (__skb_checksum_complete(skb2))
goto out;
}
err = 0;
BR_INPUT_SKB_CB(skb)->igmp = 1;
switch (icmp6_type) {
case ICMPV6_MGM_REPORT:
{
struct mld_msg *mld;
if (!pskb_may_pull(skb2, sizeof(*mld))) {
err = -EINVAL;
goto out;
}
mld = (struct mld_msg *)skb_transport_header(skb2);
BR_INPUT_SKB_CB(skb)->mrouters_only = 1;
err = br_ip6_multicast_add_group(br, port, &mld->mld_mca);
break;
}
case ICMPV6_MLD2_REPORT:
err = br_ip6_multicast_mld2_report(br, port, skb2);
break;
case ICMPV6_MGM_QUERY:
err = br_ip6_multicast_query(br, port, skb2);
break;
case ICMPV6_MGM_REDUCTION:
{
struct mld_msg *mld;
if (!pskb_may_pull(skb2, sizeof(*mld))) {
err = -EINVAL;
goto out;
}
mld = (struct mld_msg *)skb_transport_header(skb2);
br_ip6_multicast_leave_group(br, port, &mld->mld_mca);
}
}
out:
kfree_skb(skb2);
return err;
}
#endif
int br_multicast_rcv(struct net_bridge *br, struct net_bridge_port *port,
struct sk_buff *skb)
{
BR_INPUT_SKB_CB(skb)->igmp = 0;
BR_INPUT_SKB_CB(skb)->mrouters_only = 0;
if (br->multicast_disabled)
return 0;
switch (skb->protocol) {
case htons(ETH_P_IP):
return br_multicast_ipv4_rcv(br, port, skb);
#if IS_ENABLED(CONFIG_IPV6)
case htons(ETH_P_IPV6):
return br_multicast_ipv6_rcv(br, port, skb);
#endif
}
return 0;
}
static void br_multicast_query_expired(unsigned long data)
{
struct net_bridge *br = (void *)data;
spin_lock(&br->multicast_lock);
if (br->multicast_startup_queries_sent <
br->multicast_startup_query_count)
br->multicast_startup_queries_sent++;
br_multicast_send_query(br, NULL, br->multicast_startup_queries_sent);
spin_unlock(&br->multicast_lock);
}
void br_multicast_init(struct net_bridge *br)
{
br->hash_elasticity = 4;
br->hash_max = 512;
br->multicast_router = 1;
br->multicast_last_member_count = 2;
br->multicast_startup_query_count = 2;
br->multicast_last_member_interval = HZ;
br->multicast_query_response_interval = 10 * HZ;
br->multicast_startup_query_interval = 125 * HZ / 4;
br->multicast_query_interval = 125 * HZ;
br->multicast_querier_interval = 255 * HZ;
br->multicast_membership_interval = 260 * HZ;
spin_lock_init(&br->multicast_lock);
setup_timer(&br->multicast_router_timer,
br_multicast_local_router_expired, 0);
setup_timer(&br->multicast_querier_timer,
br_multicast_local_router_expired, 0);
setup_timer(&br->multicast_query_timer, br_multicast_query_expired,
(unsigned long)br);
}
void br_multicast_open(struct net_bridge *br)
{
br->multicast_startup_queries_sent = 0;
if (br->multicast_disabled)
return;
mod_timer(&br->multicast_query_timer, jiffies);
}
void br_multicast_stop(struct net_bridge *br)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
struct hlist_node *p, *n;
u32 ver;
int i;
del_timer_sync(&br->multicast_router_timer);
del_timer_sync(&br->multicast_querier_timer);
del_timer_sync(&br->multicast_query_timer);
spin_lock_bh(&br->multicast_lock);
mdb = mlock_dereference(br->mdb, br);
if (!mdb)
goto out;
br->mdb = NULL;
ver = mdb->ver;
for (i = 0; i < mdb->max; i++) {
hlist_for_each_entry_safe(mp, p, n, &mdb->mhash[i],
hlist[ver]) {
del_timer(&mp->timer);
call_rcu_bh(&mp->rcu, br_multicast_free_group);
}
}
if (mdb->old) {
spin_unlock_bh(&br->multicast_lock);
rcu_barrier_bh();
spin_lock_bh(&br->multicast_lock);
WARN_ON(mdb->old);
}
mdb->old = mdb;
call_rcu_bh(&mdb->rcu, br_mdb_free);
out:
spin_unlock_bh(&br->multicast_lock);
}
int br_multicast_set_router(struct net_bridge *br, unsigned long val)
{
int err = -ENOENT;
spin_lock_bh(&br->multicast_lock);
if (!netif_running(br->dev))
goto unlock;
switch (val) {
case 0:
case 2:
del_timer(&br->multicast_router_timer);
/* fall through */
case 1:
br->multicast_router = val;
err = 0;
break;
default:
err = -EINVAL;
break;
}
unlock:
spin_unlock_bh(&br->multicast_lock);
return err;
}
int br_multicast_set_port_router(struct net_bridge_port *p, unsigned long val)
{
struct net_bridge *br = p->br;
int err = -ENOENT;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) || p->state == BR_STATE_DISABLED)
goto unlock;
switch (val) {
case 0:
case 1:
case 2:
p->multicast_router = val;
err = 0;
if (val < 2 && !hlist_unhashed(&p->rlist))
hlist_del_init_rcu(&p->rlist);
if (val == 1)
break;
del_timer(&p->multicast_router_timer);
if (val == 0)
break;
br_multicast_add_router(br, p);
break;
default:
err = -EINVAL;
break;
}
unlock:
spin_unlock(&br->multicast_lock);
return err;
}
int br_multicast_toggle(struct net_bridge *br, unsigned long val)
{
struct net_bridge_port *port;
int err = 0;
struct net_bridge_mdb_htable *mdb;
spin_lock_bh(&br->multicast_lock);
if (br->multicast_disabled == !val)
goto unlock;
br->multicast_disabled = !val;
if (br->multicast_disabled)
goto unlock;
if (!netif_running(br->dev))
goto unlock;
mdb = mlock_dereference(br->mdb, br);
if (mdb) {
if (mdb->old) {
err = -EEXIST;
rollback:
br->multicast_disabled = !!val;
goto unlock;
}
err = br_mdb_rehash(&br->mdb, mdb->max,
br->hash_elasticity);
if (err)
goto rollback;
}
br_multicast_open(br);
list_for_each_entry(port, &br->port_list, list) {
if (port->state == BR_STATE_DISABLED ||
port->state == BR_STATE_BLOCKING)
continue;
__br_multicast_enable_port(port);
}
unlock:
spin_unlock_bh(&br->multicast_lock);
return err;
}
int br_multicast_set_hash_max(struct net_bridge *br, unsigned long val)
{
int err = -ENOENT;
u32 old;
struct net_bridge_mdb_htable *mdb;
spin_lock_bh(&br->multicast_lock);
if (!netif_running(br->dev))
goto unlock;
err = -EINVAL;
if (!is_power_of_2(val))
goto unlock;
mdb = mlock_dereference(br->mdb, br);
if (mdb && val < mdb->size)
goto unlock;
err = 0;
old = br->hash_max;
br->hash_max = val;
if (mdb) {
if (mdb->old) {
err = -EEXIST;
rollback:
br->hash_max = old;
goto unlock;
}
err = br_mdb_rehash(&br->mdb, br->hash_max,
br->hash_elasticity);
if (err)
goto rollback;
}
unlock:
spin_unlock_bh(&br->multicast_lock);
return err;
}
| Minia89/MetallizedKernelRebased | net/bridge/br_multicast.c | C | gpl-2.0 | 39,498 |
/*
Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
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, version 2.0, 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <ndb_global.h>
#include <ndb_version.h>
#include "InitConfigFileParser.hpp"
#include "Config.hpp"
#include <NdbOut.hpp>
#include "ConfigInfo.hpp"
#include "EventLogger.hpp"
#include <m_string.h>
#include <util/SparseBitmask.hpp>
#include "../common/util/parse_mask.hpp"
extern EventLogger *g_eventLogger;
const int MAX_LINE_LENGTH = 1024; // Max length of line of text in config file
static void trim(char *);
//****************************************************************************
// Ctor / Dtor
//****************************************************************************
InitConfigFileParser::InitConfigFileParser()
{
m_info = new ConfigInfo();
}
InitConfigFileParser::~InitConfigFileParser() {
delete m_info;
}
//****************************************************************************
// Read Config File
//****************************************************************************
InitConfigFileParser::Context::Context(const ConfigInfo * info)
: m_userProperties(true), m_configValues(1000, 20) {
m_config = new Properties(true);
m_defaults = new Properties(true);
}
InitConfigFileParser::Context::~Context(){
if(m_config != 0)
delete m_config;
if(m_defaults != 0)
delete m_defaults;
}
Config *
InitConfigFileParser::parseConfig(const char * filename) {
FILE * file = fopen(filename, "r");
if(file == 0){
g_eventLogger->error("Error opening '%s', error: %d, %s", filename, errno, strerror(errno));
return 0;
}
Config * ret = parseConfig(file);
fclose(file);
return ret;
}
Config *
InitConfigFileParser::parseConfig(FILE * file) {
char line[MAX_LINE_LENGTH];
Context ctx(m_info);
ctx.m_lineno = 0;
ctx.m_currentSection = 0;
/*************
* Open file *
*************/
if (file == NULL) {
return 0;
}
/***********************
* While lines to read *
***********************/
while (fgets(line, MAX_LINE_LENGTH, file)) {
ctx.m_lineno++;
trim(line);
if (isEmptyLine(line)) // Skip if line is empty or comment
continue;
// End with NULL instead of newline
if (line[strlen(line)-1] == '\n')
line[strlen(line)-1] = '\0';
/********************************
* 1. Parse new default section *
********************************/
if (char* section = parseDefaultSectionHeader(line)) {
if(!storeSection(ctx)){
free(section);
ctx.reportError("Could not store previous default section "
"of configuration file.");
return 0;
}
BaseString::snprintf(ctx.fname, sizeof(ctx.fname), "%s", section);
free(section);
ctx.type = InitConfigFileParser::DefaultSection;
ctx.m_sectionLineno = ctx.m_lineno;
ctx.m_currentSection = new Properties(true);
ctx.m_userDefaults = NULL;
require((ctx.m_currentInfo = m_info->getInfo(ctx.fname)) != 0);
require((ctx.m_systemDefaults = m_info->getDefaults(ctx.fname)) != 0);
continue;
}
/************************
* 2. Parse new section *
************************/
if (char* section = parseSectionHeader(line)) {
if(!storeSection(ctx)){
free(section);
ctx.reportError("Could not store previous section "
"of configuration file.");
return 0;
}
BaseString::snprintf(ctx.fname, sizeof(ctx.fname), "%s", section);
free(section);
ctx.type = InitConfigFileParser::Section;
ctx.m_sectionLineno = ctx.m_lineno;
ctx.m_currentSection = new Properties(true);
ctx.m_userDefaults = getSection(ctx.fname, ctx.m_defaults);
require((ctx.m_currentInfo = m_info->getInfo(ctx.fname)) != 0);
require((ctx.m_systemDefaults = m_info->getDefaults(ctx.fname)) != 0);
continue;
}
/****************************
* 3. Parse name-value pair *
****************************/
if (!parseNameValuePair(ctx, line)) {
ctx.reportError("Could not parse name-value pair in config file.");
return 0;
}
}
if (ferror(file)){
ctx.reportError("Failure in reading");
return 0;
}
if(!storeSection(ctx)) {
ctx.reportError("Could not store section of configuration file.");
return 0;
}
return run_config_rules(ctx);
}
Config*
InitConfigFileParser::run_config_rules(Context& ctx)
{
for(size_t i = 0; ConfigInfo::m_ConfigRules[i].m_configRule != 0; i++){
ctx.type = InitConfigFileParser::Undefined;
ctx.m_info = m_info;
ctx.m_currentSection = 0;
ctx.m_userDefaults = 0;
ctx.m_currentInfo = 0;
ctx.m_systemDefaults = 0;
Vector<ConfigInfo::ConfigRuleSection> tmp;
if(!(* ConfigInfo::m_ConfigRules[i].m_configRule)(tmp, ctx,
ConfigInfo::m_ConfigRules[i].m_ruleData))
return 0;
for(unsigned j = 0; j<tmp.size(); j++){
BaseString::snprintf(ctx.fname, sizeof(ctx.fname),
"%s", tmp[j].m_sectionType.c_str());
ctx.type = InitConfigFileParser::Section;
ctx.m_currentSection = tmp[j].m_sectionData;
ctx.m_userDefaults = getSection(ctx.fname, ctx.m_defaults);
require((ctx.m_currentInfo = m_info->getInfo(ctx.fname)) != 0);
require((ctx.m_systemDefaults = m_info->getDefaults(ctx.fname)) != 0);
if(!storeSection(ctx))
return 0;
}
}
Uint32 nConnections = 0;
Uint32 nComputers = 0;
Uint32 nNodes = 0;
Uint32 nExtConnections = 0;
const char * system = "?";
ctx.m_userProperties.get("NoOfConnections", &nConnections);
ctx.m_userProperties.get("NoOfComputers", &nComputers);
ctx.m_userProperties.get("NoOfNodes", &nNodes);
ctx.m_userProperties.get("ExtNoOfConnections", &nExtConnections);
ctx.m_userProperties.get("ExtSystem", &system);
ctx.m_config->put("NoOfConnections", nConnections);
ctx.m_config->put("NoOfComputers", nComputers);
ctx.m_config->put("NoOfNodes", nNodes);
char tmpLine[MAX_LINE_LENGTH];
BaseString::snprintf(tmpLine, MAX_LINE_LENGTH,
"EXTERNAL SYSTEM_%s:NoOfConnections", system);
ctx.m_config->put(tmpLine, nExtConnections);
return new Config(ctx.m_configValues.getConfigValues());
}
//****************************************************************************
// Parse Name-Value Pair
//****************************************************************************
bool InitConfigFileParser::parseNameValuePair(Context& ctx, const char* line)
{
if (ctx.m_currentSection == NULL){
ctx.reportError("Value specified outside section");
return false;
}
// *************************************
// Split string at first occurrence of
// '=' or ':'
// *************************************
Vector<BaseString> tmp_string_split;
if (BaseString(line).split(tmp_string_split,
"=:", 2) != 2)
{
ctx.reportError("Parse error");
return false;
}
// *************************************
// Remove all after #
// *************************************
Vector<BaseString> tmp_string_split2;
tmp_string_split[1].split(tmp_string_split2,
"#", 2);
tmp_string_split[1]=tmp_string_split2[0];
// *************************************
// Remove leading and trailing chars
// *************************************
{
for (int i = 0; i < 2; i++)
tmp_string_split[i].trim("\r\n \t");
}
return storeNameValuePair(ctx,
tmp_string_split[0].c_str(), // fname
tmp_string_split[1].c_str()); // value
}
bool
InitConfigFileParser::storeNameValuePair(Context& ctx,
const char* fname,
const char* value)
{
if (ctx.m_currentSection->contains(fname))
{
ctx.reportError("[%s] Parameter %s specified twice", ctx.fname, fname);
return false;
}
if (!ctx.m_currentInfo->contains(fname))
{
ctx.reportError("[%s] Unknown parameter: %s", ctx.fname, fname);
return false;
}
ConfigInfo::Status status = m_info->getStatus(ctx.m_currentInfo, fname);
if (status == ConfigInfo::CI_NOTIMPLEMENTED) {
ctx.reportWarning("[%s] %s not yet implemented", ctx.fname, fname);
}
if (status == ConfigInfo::CI_DEPRECATED) {
const char * desc = m_info->getDescription(ctx.m_currentInfo, fname);
if(desc && desc[0]){
ctx.reportWarning("[%s] %s is deprecated, use %s instead",
ctx.fname, fname, desc);
} else if (desc == 0){
ctx.reportWarning("[%s] %s is deprecated", ctx.fname, fname);
}
}
const ConfigInfo::Type type = m_info->getType(ctx.m_currentInfo, fname);
switch(type){
case ConfigInfo::CI_BOOL: {
bool value_bool;
if (!convertStringToBool(value, value_bool)) {
ctx.reportError("Illegal boolean value for parameter %s", fname);
return false;
}
require(ctx.m_currentSection->put(fname, value_bool));
break;
}
case ConfigInfo::CI_INT:
case ConfigInfo::CI_INT64:{
Uint64 value_int;
if (!convertStringToUint64(value, value_int)) {
ctx.reportError("Illegal integer value for parameter %s", fname);
return false;
}
if (!m_info->verify(ctx.m_currentInfo, fname, value_int)) {
ctx.reportError("Illegal value %s for parameter %s.\n"
"Legal values are between %llu and %llu", value, fname,
m_info->getMin(ctx.m_currentInfo, fname),
m_info->getMax(ctx.m_currentInfo, fname));
return false;
}
if(type == ConfigInfo::CI_INT){
require(ctx.m_currentSection->put(fname, (Uint32)value_int));
} else {
require(ctx.m_currentSection->put64(fname, value_int));
}
break;
}
case ConfigInfo::CI_STRING:
require(ctx.m_currentSection->put(fname, value));
break;
case ConfigInfo::CI_ENUM:{
Uint32 value_int;
if (!m_info->verify_enum(ctx.m_currentInfo, fname, value, value_int)) {
BaseString values;
m_info->get_enum_values(ctx.m_currentInfo, fname, values);
ctx.reportError("Illegal value '%s' for parameter %s. "
"Legal values are: '%s'", value, fname,
values.c_str());
return false;
}
require(ctx.m_currentSection->put(fname, value_int));
break;
}
case ConfigInfo::CI_BITMASK:{
if (strlen(value) <= 0)
{
ctx.reportError("Illegal value '%s' for parameter %s. "
"Error: Zero length string",
value, fname);
return false;
}
Uint64 max = m_info->getMax(ctx.m_currentInfo, fname);
SparseBitmask mask((unsigned)max);
int res = parse_mask(value, mask);
if (res < 0)
{
BaseString desc("Unknown error.");
switch(res)
{
case -1:
desc.assign("Invalid syntax for bitmask");
break;
case -2:
desc.assfmt("Too large id used in bitmask, max is %llu", max);
break;
default:
break;
}
ctx.reportError("Illegal value '%s' for parameter %s. Error: %s",
value, fname, desc.c_str());
return false;
}
require(ctx.m_currentSection->put(fname, value));
break;
}
case ConfigInfo::CI_SECTION:
abort();
}
return true;
}
//****************************************************************************
// Is Empty Line
//****************************************************************************
bool InitConfigFileParser::isEmptyLine(const char* line) const {
int i;
// Check if it is a comment line
if (line[0] == '#') return true;
// Check if it is a line with only spaces
for (i = 0; i < MAX_LINE_LENGTH && line[i] != '\n' && line[i] != '\0'; i++) {
if (line[i] != ' ' && line[i] != '\t') return false;
}
return true;
}
//****************************************************************************
// Convert String to Int
//****************************************************************************
bool InitConfigFileParser::convertStringToUint64(const char* s,
Uint64& val,
Uint32 log10base) {
if (s == NULL)
return false;
if (strlen(s) == 0)
return false;
errno = 0;
char* p;
Int64 v = my_strtoll(s, &p, log10base);
if (errno != 0)
return false;
long mul = 0;
if (p != &s[strlen(s)]){
char * tmp = strdup(p);
trim(tmp);
switch(tmp[0]){
case 'k':
case 'K':
mul = 10;
break;
case 'M':
mul = 20;
break;
case 'G':
mul = 30;
break;
default:
free(tmp);
return false;
}
free(tmp);
}
val = (v << mul);
return true;
}
bool InitConfigFileParser::convertStringToBool(const char* s, bool& val) {
if (s == NULL) return false;
if (strlen(s) == 0) return false;
if (!strcmp(s, "Y") || !strcmp(s, "y") ||
!strcmp(s, "Yes") || !strcmp(s, "YES") || !strcmp(s, "yes") ||
!strcmp(s, "True") || !strcmp(s, "TRUE") || !strcmp(s, "true") ||
!strcmp(s, "1")) {
val = true;
return true;
}
if (!strcmp(s, "N") || !strcmp(s, "n") ||
!strcmp(s, "No") || !strcmp(s, "NO") || !strcmp(s, "no") ||
!strcmp(s, "False") || !strcmp(s, "FALSE") || !strcmp(s, "false") ||
!strcmp(s, "0")) {
val = false;
return true;
}
return false; // Failure to convert
}
//****************************************************************************
// Parse Section Header
//****************************************************************************
static void
trim(char * str){
int len = (int)strlen(str);
for(len--;
(str[len] == '\r' || str[len] == '\n' ||
str[len] == ' ' || str[len] == '\t') &&
len > 0;
len--)
str[len] = 0;
int pos = 0;
while(str[pos] == ' ' || str[pos] == '\t')
pos++;
if(str[pos] == '\"' && str[len] == '\"') {
pos++;
str[len] = 0;
len--;
}
memmove(str, &str[pos], len - pos + 2);
}
char*
InitConfigFileParser::parseSectionHeader(const char* line) const {
char * tmp = strdup(line);
if(tmp[0] != '['){
free(tmp);
return NULL;
}
if(tmp[strlen(tmp)-1] != ']'){
free(tmp);
return NULL;
}
tmp[strlen(tmp)-1] = 0;
tmp[0] = ' ';
trim(tmp);
// Get the correct header name if an alias
{
const char *tmp_alias= m_info->getAlias(tmp);
if (tmp_alias) {
free(tmp);
tmp= strdup(tmp_alias);
}
}
// Lookup token among sections
if(!m_info->isSection(tmp)) {
free(tmp);
return NULL;
}
if(m_info->getInfo(tmp)) return tmp;
free(tmp);
return NULL;
}
//****************************************************************************
// Parse Default Section Header
//****************************************************************************
char*
InitConfigFileParser::parseDefaultSectionHeader(const char* line) const {
static char token1[MAX_LINE_LENGTH], token2[MAX_LINE_LENGTH];
int no = sscanf(line, "[%120[A-Z_a-z] %120[A-Z_a-z]]", token1, token2);
// Not correct no of tokens
if (no != 2) return NULL;
// Not correct keyword at end
if (!native_strcasecmp(token2, "DEFAULT") == 0) return NULL;
const char *token1_alias= m_info->getAlias(token1);
if (token1_alias == 0)
token1_alias= token1;
if(m_info->getInfo(token1_alias)){
return strdup(token1_alias);
}
// Did not find section
return NULL;
}
const Properties *
InitConfigFileParser::getSection(const char * name, const Properties * src){
const Properties * p;
if(src && src->get(name, &p))
return p;
return 0;
}
//****************************************************************************
// STORE section
//****************************************************************************
bool
InitConfigFileParser::storeSection(Context& ctx){
if(ctx.m_currentSection == NULL)
return true;
for(int i = (int)strlen(ctx.fname) - 1; i>=0; i--){
ctx.fname[i] = toupper(ctx.fname[i]);
}
BaseString::snprintf(ctx.pname, sizeof(ctx.pname), "%s", ctx.fname);
char buf[255];
if(ctx.type == InitConfigFileParser::Section)
BaseString::snprintf(buf, sizeof(buf), "%s", ctx.fname);
if(ctx.type == InitConfigFileParser::DefaultSection)
BaseString::snprintf(buf, sizeof(buf), "%s DEFAULT", ctx.fname);
BaseString::snprintf(ctx.fname, sizeof(ctx.fname), "%s", buf);
if(ctx.type == InitConfigFileParser::Section){
for(int i = 0; i<m_info->m_NoOfRules; i++){
const ConfigInfo::SectionRule & rule = m_info->m_SectionRules[i];
if(!strcmp(rule.m_section, "*") || !strcmp(rule.m_section, ctx.fname)){
if(!(* rule.m_sectionRule)(ctx, rule.m_ruleData)){
return false;
}
}
}
}
if(ctx.type == InitConfigFileParser::DefaultSection &&
!ctx.m_defaults->put(ctx.pname, ctx.m_currentSection))
{
ctx.reportError("Duplicate default section not allowed");
return false;
}
if(ctx.type == InitConfigFileParser::Section)
require(ctx.m_config->put(ctx.pname, ctx.m_currentSection));
delete ctx.m_currentSection; ctx.m_currentSection = NULL;
return true;
}
void
InitConfigFileParser::Context::reportError(const char * fmt, ...){
va_list ap;
char buf[1000];
va_start(ap, fmt);
if (fmt != 0)
BaseString::vsnprintf(buf, sizeof(buf)-1, fmt, ap);
va_end(ap);
g_eventLogger->error("at line %d: %s",
m_lineno, buf);
//m_currentSection->print();
}
void
InitConfigFileParser::Context::reportWarning(const char * fmt, ...){
va_list ap;
char buf[1000];
va_start(ap, fmt);
if (fmt != 0)
BaseString::vsnprintf(buf, sizeof(buf)-1, fmt, ap);
va_end(ap);
g_eventLogger->warning("at line %d: %s",
m_lineno, buf);
}
#include <my_sys.h>
#include <my_getopt.h>
#ifdef HAVE_MY_DEFAULT_H
#include <my_default.h>
#endif
static int order = 1;
static
my_bool
parse_mycnf_opt(int, const struct my_option * opt, char * value)
{
long *app_type= (long*) &opt->app_type;
if(opt->comment)
(*app_type)++;
else
*app_type = order++;
return 0;
}
bool
InitConfigFileParser::store_in_properties(Vector<struct my_option>& options,
InitConfigFileParser::Context& ctx,
const char * name)
{
for(unsigned i = 0; i<options.size(); i++)
{
if (options[i].app_type == 0)
{
// Option not found in in my.cnf
continue;
}
const char* section = options[i].comment;
if (!section)
{
// Option which is not to be saved, like "ndbd", "ndbapi", "mysqld" etc.
continue;
}
if (strcmp(section, name) == 0)
{
const char* value = NULL;
char buf[32];
switch(options[i].var_type){
case GET_INT:
case GET_UINT:
BaseString::snprintf(buf, sizeof(buf), "%u",
*(Uint32*)options[i].value);
value = buf;
break;
case GET_ULL:
BaseString::snprintf(buf, sizeof(buf), "%llu",
*(Uint64*)options[i].value);
value = buf;
break;
case GET_STR:
value = *(char**)options[i].value;
break;
default:
abort();
}
const char* fname = options[i].name;
if (!storeNameValuePair(ctx, fname, value))
return false;
}
}
return true;
}
bool
InitConfigFileParser::handle_mycnf_defaults(Vector<struct my_option>& options,
InitConfigFileParser::Context& ctx,
const char * name)
{
strcpy(ctx.fname, name);
ctx.type = InitConfigFileParser::DefaultSection;
ctx.m_currentSection = new Properties(true);
ctx.m_userDefaults = NULL;
require((ctx.m_currentInfo = m_info->getInfo(ctx.fname)) != 0);
require((ctx.m_systemDefaults = m_info->getDefaults(ctx.fname)) != 0);
if(store_in_properties(options, ctx, name))
return storeSection(ctx);
return false;
}
static
int
load_defaults(Vector<struct my_option>& options, const char* groups[])
{
int argc = 1;
const char * argv[] = { "ndb_mgmd", 0, 0, 0, 0 };
BaseString file;
BaseString extra_file;
BaseString group_suffix;
const char *save_file = my_defaults_file;
#if MYSQL_VERSION_ID >= 50508
const
#endif
char *save_extra_file = my_defaults_extra_file;
const char *save_group_suffix = my_defaults_group_suffix;
if (my_defaults_file)
{
file.assfmt("--defaults-file=%s", my_defaults_file);
argv[argc++] = file.c_str();
}
if (my_defaults_extra_file)
{
extra_file.assfmt("--defaults-extra-file=%s", my_defaults_extra_file);
argv[argc++] = extra_file.c_str();
}
if (my_defaults_group_suffix)
{
group_suffix.assfmt("--defaults-group-suffix=%s",
my_defaults_group_suffix);
argv[argc++] = group_suffix.c_str();
}
char ** tmp = (char**)argv;
int ret = load_defaults("my", groups, &argc, &tmp);
my_defaults_file = save_file;
my_defaults_extra_file = save_extra_file;
my_defaults_group_suffix = save_group_suffix;
if (ret == 0)
{
return handle_options(&argc, &tmp, options.getBase(), parse_mycnf_opt);
}
return ret;
}
bool
InitConfigFileParser::load_mycnf_groups(Vector<struct my_option> & options,
InitConfigFileParser::Context& ctx,
const char * name,
const char *groups[])
{
unsigned i;
Vector<struct my_option> copy;
for(i = 0; i<options.size(); i++)
{
if(options[i].comment && strcmp(options[i].comment, name) == 0)
{
options[i].app_type = 0;
copy.push_back(options[i]);
}
}
struct my_option end;
memset(&end, 0, sizeof(end));
copy.push_back(end);
if (load_defaults(copy, groups))
return false;
return store_in_properties(copy, ctx, name);
}
Config *
InitConfigFileParser::parse_mycnf()
{
Config * res = 0;
Vector<struct my_option> options;
for(int i = 0 ; i < ConfigInfo::m_NoOfParams ; ++ i)
{
{
struct my_option opt;
memset(&opt, 0, sizeof(opt));
const ConfigInfo::ParamInfo& param = ConfigInfo::m_ParamInfo[i];
switch(param._type){
case ConfigInfo::CI_BOOL:
opt.value = (uchar **)malloc(sizeof(int));
opt.var_type = GET_INT;
break;
case ConfigInfo::CI_INT:
opt.value = (uchar**)malloc(sizeof(uint));
opt.var_type = GET_UINT;
break;
case ConfigInfo::CI_INT64:
opt.value = (uchar**)malloc(sizeof(Uint64));
opt.var_type = GET_ULL;
break;
case ConfigInfo::CI_ENUM:
case ConfigInfo::CI_STRING:
case ConfigInfo::CI_BITMASK:
opt.value = (uchar**)malloc(sizeof(char *));
opt.var_type = GET_STR;
break;
default:
continue;
}
opt.name = param._fname;
opt.id = 256;
opt.app_type = 0;
opt.arg_type = REQUIRED_ARG;
opt.comment = param._section;
options.push_back(opt);
}
}
struct my_option *ndbd, *ndb_mgmd, *mysqld, *api;
/**
* Add ndbd, ndb_mgmd, api/mysqld
*/
Uint32 idx = options.size();
{
struct my_option opt;
memset(&opt, 0, sizeof(opt));
opt.name = "ndbd";
opt.id = 256;
opt.value = (uchar**)malloc(sizeof(char*));
opt.var_type = GET_STR;
opt.arg_type = REQUIRED_ARG;
options.push_back(opt);
opt.name = "ndb_mgmd";
opt.id = 256;
opt.value = (uchar**)malloc(sizeof(char*));
opt.var_type = GET_STR;
opt.arg_type = REQUIRED_ARG;
options.push_back(opt);
opt.name = "mysqld";
opt.id = 256;
opt.value = (uchar**)malloc(sizeof(char*));
opt.var_type = GET_STR;
opt.arg_type = REQUIRED_ARG;
options.push_back(opt);
opt.name = "ndbapi";
opt.id = 256;
opt.value = (uchar**)malloc(sizeof(char*));
opt.var_type = GET_STR;
opt.arg_type = REQUIRED_ARG;
options.push_back(opt);
memset(&opt, 0, sizeof(opt));
options.push_back(opt);
ndbd = &options[idx];
ndb_mgmd = &options[idx+1];
mysqld = &options[idx+2];
api = &options[idx+3];
}
Context ctx(m_info);
const char *groups[]= { "cluster_config", 0 };
if (load_defaults(options, groups))
goto end;
ctx.m_lineno = 0;
if(!handle_mycnf_defaults(options, ctx, "DB"))
goto end;
if(!handle_mycnf_defaults(options, ctx, "API"))
goto end;
if(!handle_mycnf_defaults(options, ctx, "MGM"))
goto end;
if(!handle_mycnf_defaults(options, ctx, "TCP"))
goto end;
if(!handle_mycnf_defaults(options, ctx, "SHM"))
goto end;
if(!handle_mycnf_defaults(options, ctx, "SCI"))
goto end;
{
struct sect { struct my_option* src; const char * name; } sections[] =
{
{ ndb_mgmd, "MGM" },
{ ndbd, "DB" },
{ mysqld, "API" },
{ api, "API" }
};
for(unsigned i = 0; i + 1 < NDB_ARRAY_SIZE(sections) ; i++)
{
for(unsigned j = i + 1; j < NDB_ARRAY_SIZE(sections) ; j++)
{
if (sections[j].src->app_type < sections[i].src->app_type)
{
sect swap = sections[i];
sections[i] = sections[j];
sections[j] = swap;
}
}
}
ctx.type = InitConfigFileParser::Section;
ctx.m_sectionLineno = ctx.m_lineno;
for(unsigned i = 0; i < NDB_ARRAY_SIZE(sections) ; i++)
{
if (sections[i].src->app_type)
{
strcpy(ctx.fname, sections[i].name);
BaseString str(*(char**)sections[i].src->value);
Vector<BaseString> list;
str.split(list, ",");
const char * defaults_groups[] = { 0, 0, 0 };
for(unsigned j = 0; j<list.size(); j++)
{
// Remove leading and trailing spaces from hostname
list[j].trim();
BaseString group_idx;
BaseString group_host;
group_idx.assfmt("%s.%s.%d", groups[0],
sections[i].src->name, j + 1);
group_host.assfmt("%s.%s.%s", groups[0],
sections[i].src->name, list[j].c_str());
defaults_groups[0] = group_idx.c_str();
if(list[j].length())
defaults_groups[1] = group_host.c_str();
else
defaults_groups[1] = 0;
ctx.m_currentSection = new Properties(true);
ctx.m_userDefaults = getSection(ctx.fname, ctx.m_defaults);
require((ctx.m_currentInfo = m_info->getInfo(ctx.fname)) != 0);
require((ctx.m_systemDefaults = m_info->getDefaults(ctx.fname))!= 0);
if(!load_mycnf_groups(options, ctx, sections[i].name,
defaults_groups))
goto end;
// The [cluster_config] section in my.cnf specifies the hostname,
// but it can also be specified a second time in the nodes section
// make sure they match if specified in both places, else
// save the value from cluster_config section
//
// Example:
// [cluster_config]
// ndbd=hostname1
// ^^^^^^^^^
// [cluster_config.ndbd.1]
// HostName=hostname1
// ^^^^^^^^^
//
if (ctx.m_currentSection->contains("HostName"))
{
// HostName specified a second time, check that it matches
const char* host_name;
require(ctx.m_currentSection->get("HostName", &host_name));
if (strcmp(host_name, list[j].c_str()))
{
ctx.reportError("Illegal value 'HostName=%s' specified for "
"%s, previously set to '%s'",
host_name, group_idx.c_str(),
list[j].c_str());
goto end;
}
}
else
{
require(ctx.m_currentSection->put("HostName", list[j].c_str()));
}
if(!storeSection(ctx))
goto end;
}
}
}
}
res = run_config_rules(ctx);
end:
for(int i = 0; options[i].name; i++)
free(options[i].value);
return res;
}
template class Vector<struct my_option>;
/*
See include/my_getopt.h for the declaration of struct my_option
*/
| greenlion/mysql-server | storage/ndb/src/mgmsrv/InitConfigFileParser.cpp | C++ | gpl-2.0 | 28,624 |
'use strict';
const common = require('../common.js');
const bench = common.createBenchmark(main, {
pieces: [1, 4, 16],
pieceSize: [1, 16, 256],
withTotalLength: [0, 1],
n: [1024]
});
function main(conf) {
const n = +conf.n;
const size = +conf.pieceSize;
const pieces = +conf.pieces;
const list = new Array(pieces);
list.fill(Buffer.allocUnsafe(size));
const totalLength = conf.withTotalLength ? pieces * size : undefined;
bench.start();
for (var i = 0; i < n * 1024; i++) {
Buffer.concat(list, totalLength);
}
bench.end(n);
}
| domino-team/openwrt-cc | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/benchmark/buffers/buffer-concat.js | JavaScript | gpl-2.0 | 563 |
/*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if ENABLE(INSPECTOR) && ENABLE(WORKERS)
#include "WorkerRuntimeAgent.h"
#include "InjectedScript.h"
#include "InstrumentingAgents.h"
#include "ScriptState.h"
#include "WorkerContext.h"
#include "WorkerDebuggerAgent.h"
#include "WorkerRunLoop.h"
#include "WorkerThread.h"
namespace WebCore {
WorkerRuntimeAgent::WorkerRuntimeAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, WorkerContext* workerContext)
: InspectorRuntimeAgent(instrumentingAgents, state, injectedScriptManager)
, m_workerContext(workerContext)
, m_paused(false)
{
m_instrumentingAgents->setWorkerRuntimeAgent(this);
}
WorkerRuntimeAgent::~WorkerRuntimeAgent()
{
m_instrumentingAgents->setWorkerRuntimeAgent(0);
}
InjectedScript WorkerRuntimeAgent::injectedScriptForEval(ErrorString* error, const int* executionContextId)
{
if (executionContextId) {
*error = "Execution context id is not supported for workers as there is only one execution context.";
return InjectedScript();
}
ScriptState* scriptState = scriptStateFromWorkerContext(m_workerContext);
return injectedScriptManager()->injectedScriptFor(scriptState);
}
void WorkerRuntimeAgent::muteConsole()
{
// We don't need to mute console for workers.
}
void WorkerRuntimeAgent::unmuteConsole()
{
// We don't need to mute console for workers.
}
void WorkerRuntimeAgent::run(ErrorString*)
{
m_paused = false;
}
#if ENABLE(JAVASCRIPT_DEBUGGER)
void WorkerRuntimeAgent::pauseWorkerContext(WorkerContext* context)
{
m_paused = true;
MessageQueueWaitResult result;
do {
result = context->thread()->runLoop().runInMode(context, WorkerDebuggerAgent::debuggerTaskMode);
// Keep waiting until execution is resumed.
} while (result == MessageQueueMessageReceived && m_paused);
}
#endif // ENABLE(JAVASCRIPT_DEBUGGER)
} // namespace WebCore
#endif // ENABLE(INSPECTOR) && ENABLE(WORKERS)
| 166MMX/openjdk.java.net-openjfx-8u40-rt | modules/web/src/main/native/Source/WebCore/inspector/WorkerRuntimeAgent.cpp | C++ | gpl-2.0 | 3,564 |
<?php
/*
$id author Puddled Internet - http://www.puddled.co.uk
email support@puddled.co.uk
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com
Copyright (c) 2002 osCommerce
Released under the GNU General Public License
*/
require('includes/application_top.php');
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch ($action) {
case 'insert':
case 'save':
$return_reason_id = isset($_GET['oID']) ? tep_db_prepare_input($_GET['oID']) : 0;
$languages = tep_get_languages();
for ($i = 0, $n = sizeof($languages); $i < $n; $i++) {
$return_reason_name_array = $_POST['return_reason_name'];
$language_id = $languages[$i]['id'];
$sql_data_array = array('return_reason_name' => tep_db_prepare_input($return_reason_name_array[$language_id]));
if ($_GET['action'] == 'insert') {
if (!tep_not_null($return_reason_id)) {
$next_id_query = tep_db_query("select max(return_reason_id) as return_reason_id from " . TABLE_RETURN_REASONS . "");
$next_id = tep_db_fetch_array($next_id_query);
$return_reason_id = $next_id['return_reason_id'] + 1;
}
$insert_sql_data = array('return_reason_id' => $return_reason_id,
'language_id' => $language_id);
$sql_data_array = array_merge($sql_data_array, $insert_sql_data);
tep_db_perform(TABLE_RETURN_REASONS, $sql_data_array);
} elseif ($_GET['action'] == 'save') {
tep_db_perform(TABLE_RETURN_REASONS, $sql_data_array, 'update', "return_reason_id = '" . tep_db_input($return_reason_id) . "' and language_id = '" . $language_id . "'");
}
}
if ($_POST['default'] == 'on') {
tep_db_query("update " . TABLE_CONFIGURATION . " set configuration_value = '" . tep_db_input($return_reason_id) . "' where configuration_key = 'DEFAULT_RETURN_REASON'");
}
tep_redirect(tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $return_reason_id));
break;
case 'deleteconfirm':
$oID = tep_db_prepare_input($_GET['oID']);
$orders_status_query = tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'DEFAULT_RETURN_REASON'");
$orders_status = tep_db_fetch_array($orders_status_query);
if ($orders_status['configuration_value'] == $oID) {
tep_db_query("update " . TABLE_CONFIGURATION . " set configuration_value = '' where configuration_key = 'DEFAULT_RETURN_REASON'");
}
tep_db_query("delete from " . TABLE_RETURN_REASONS . " where return_reason_id = '" . tep_db_input($oID) . "'");
tep_redirect(tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page']));
break;
case 'delete':
$oID = tep_db_prepare_input($_GET['oID']);
/*
$status_query = tep_db_query("select count(*) as count from " . TABLE_RETURN_REASONS . " where orders_status = '" . tep_db_input($oID) . "'");
$status = tep_db_fetch_array($status_query);
*/
$remove_status = true;
/* if ($oID == DEFAULT_ORDERS_STATUS_ID) {
$remove_status = false;
$messageStack->add(ERROR_REMOVE_DEFAULT_ORDER_STATUS, 'error');
} elseif ($status['count'] > 0) {
$remove_status = false;
$messageStack->add(ERROR_STATUS_USED_IN_ORDERS, 'error');
} else {
$history_query = tep_db_query("select count(*) as count from " . TABLE_RETURN_REASONS_HISTORY . " where '" . tep_db_input($oID) . "' in (new_value, old_value)");
$history = tep_db_fetch_array($history_query);
if ($history['count'] > 0) {
$remove_status = false;
$messageStack->add(ERROR_STATUS_USED_IN_HISTORY, 'error');
}
}
break; */
}
if (!isset($_GET['action'])) {
$_GET['action'] = '';
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html <?php echo HTML_PARAMS; ?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<title><?php echo TITLE; ?></title>
<script type="text/javascript" src="<?php echo (($request_type == 'SSL') ? 'https:' : 'http:'); ?>//ajax.googleapis.com/ajax/libs/jquery/<?php echo JQUERY_VERSION; ?>/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
//alert('You are running a local copy of jQuery!');
document.write(unescape("%3Cscript src='includes/javascript/jquery-1.6.2.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="includes/stylesheet-ie.css">
<![endif]-->
<script language="javascript" src="includes/general.js"></script>
<link rel="stylesheet" type="text/css" href="includes/headernavmenu.css">
<script type="text/javascript" src="includes/menu.js"></script>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF" onload="SetFocus();">
<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->
<!-- body //-->
<div id="body">
<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0" class="body-table">
<tr>
<!-- left_navigation //-->
<?php require(DIR_WS_INCLUDES . 'column_left.php'); ?>
<!-- left_navigation_eof //-->
<!-- body_text //-->
<td width="100%" valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2">
<tr>
<td><table border="0" width="100%" cellspacing="0" cellpadding="0">
<tr>
<td><?php echo tep_draw_separator('pixel_trans.gif', '1', '5'); ?></td>
</tr>
<tr>
<td class="pageHeading"><?php echo HEADING_TITLE; ?></td>
<td class="pageHeading" align="right"><?php echo tep_draw_separator('pixel_trans.gif', HEADING_IMAGE_WIDTH, HEADING_IMAGE_HEIGHT); ?></td>
</tr>
</table></td>
</tr>
<tr>
<td valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="0">
<tr>
<td valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2" class="data-table">
<tr class="dataTableHeadingRow">
<td class="dataTableHeadingContent"><?php echo TABLE_HEADING_ORDERS_STATUS; ?></td>
<td class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_ACTION; ?> </td>
</tr>
<?php
$orders_status_query_raw = "select return_reason_id, return_reason_name from " . TABLE_RETURN_REASONS . " where language_id = '" . $languages_id . "' order by return_reason_id";
$orders_status_split = new splitPageResults($_GET['page'], MAX_DISPLAY_SEARCH_RESULTS, $orders_status_query_raw, $orders_status_query_numrows);
$orders_status_query = tep_db_query($orders_status_query_raw);
while ($orders_status = tep_db_fetch_array($orders_status_query)) {
if (((!isset($_GET['oID'])) || (isset($_GET['oID']) && $_GET['oID'] == $orders_status['return_reason_id'])) && (!isset($oInfo)) && ( substr($_GET['action'], 0, 3) != 'new')) {
$oInfo = new objectInfo($orders_status);
}
if ( isset($oInfo) && (is_object($oInfo)) && ($orders_status['return_reason_id'] == $oInfo->return_reason_id) ) {
echo ' <tr class="dataTableRowSelected" onmouseover="this.style.cursor=\'hand\'" onclick="document.location.href=\'' . tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $oInfo->return_reason_id . '&action=edit') . '\'">' . "\n";
} else {
echo ' <tr class="dataTableRow" onmouseover="this.className=\'dataTableRowOver\';this.style.cursor=\'hand\'" onmouseout="this.className=\'dataTableRow\'" onclick="document.location.href=\'' . tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $orders_status['return_reason_id']) . '\'">' . "\n";
}
if (DEFAULT_RETURN_REASON == $orders_status['return_reason_id']) {
echo ' <td class="dataTableContent"><b>' . $orders_status['return_reason_name'] . ' (' . TEXT_DEFAULT . ')</b></td>' . "\n";
} else {
echo ' <td class="dataTableContent">' . $orders_status['return_reason_name'] . '</td>' . "\n";
}
?>
<td class="dataTableContent" align="right"><?php if ( isset($oInfo) && (is_object($oInfo)) && ($orders_status['return_reason_id'] == $oInfo->return_reason_id) ) { echo tep_image(DIR_WS_IMAGES . 'arrow_right_blue.png', ''); } else { echo '<a href="' . tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $orders_status['return_reason_id']) . '">' . tep_image(DIR_WS_IMAGES . 'information.png', IMAGE_ICON_INFO) . '</a>'; } ?> </td>
</tr>
<?php
}
?> </table><table border="0" cellpadding="0" cellspacing="0" width="100%" class="data-table-foot">
<tr>
<td colspan="2"><table border="0" width="100%" cellspacing="0" cellpadding="2">
<tr>
<td class="smallText" valign="top"><?php echo $orders_status_split->display_count($orders_status_query_numrows, MAX_DISPLAY_SEARCH_RESULTS, $_GET['page'], TEXT_DISPLAY_NUMBER_OF_TICKET_STATUS); ?></td>
<td class="smallText" align="right"><?php echo $orders_status_split->display_links($orders_status_query_numrows, MAX_DISPLAY_SEARCH_RESULTS, MAX_DISPLAY_PAGE_LINKS, $_GET['page']); ?></td>
</tr>
<?php
if (isset($_GET['action']) && substr($_GET['action'], 0, 3) != 'new') {
?>
<tr>
<td colspan="2" align="right"><?php echo '<a href="' . tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&action=new') . '">' . tep_image_button('button_insert.gif', IMAGE_INSERT) . '</a>'; ?> </td>
</tr>
<?php
}
?>
</table></td>
</tr>
</table></td>
<?php
$heading = array();
$contents = array();
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch ($action) {
case 'new':
$heading[] = array('text' => '<b>' . TEXT_INFO_HEADING_NEW_ORDERS_STATUS . '</b>');
$contents = array('form' => tep_draw_form('status', FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&action=insert'));
$contents[] = array('text' => TEXT_INFO_INSERT_INTRO);
$orders_status_inputs_string = '';
$languages = tep_get_languages();
for ($i = 0, $n = sizeof($languages); $i < $n; $i++) {
$orders_status_inputs_string .= '<br>' . tep_image(DIR_WS_CATALOG_LANGUAGES . $languages[$i]['directory'] . '/images/' . $languages[$i]['image'], $languages[$i]['name']) . ' ' . tep_draw_input_field('return_reason_name[' . $languages[$i]['id'] . ']');
}
$contents[] = array('text' => '<br>' . TEXT_INFO_ORDERS_STATUS_NAME . $orders_status_inputs_string);
$contents[] = array('text' => '<br>' . tep_draw_checkbox_field('default') . ' ' . TEXT_SET_DEFAULT);
$contents[] = array('align' => 'center', 'text' => '<br><a href="' . tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page']) . '">' . tep_image_button('button_cancel.gif', IMAGE_CANCEL) . '</a>' . tep_image_submit('button_insert.gif', IMAGE_INSERT));
break;
case 'edit':
$heading[] = array('text' => '<b>' . TEXT_INFO_HEADING_EDIT_ORDERS_STATUS . '</b>');
$contents = array('form' => tep_draw_form('status', FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $oInfo->return_reason_id . '&action=save'));
$contents[] = array('text' => TEXT_INFO_EDIT_INTRO);
$orders_status_inputs_string = '';
$languages = tep_get_languages();
for ($i = 0, $n = sizeof($languages); $i < $n; $i++) {
$orders_status_inputs_string .= '<br>' . tep_image(DIR_WS_CATALOG_LANGUAGES . $languages[$i]['directory'] . '/images/' . $languages[$i]['image'], $languages[$i]['name']) . ' ' . tep_draw_input_field('return_reason_name[' . $languages[$i]['id'] . ']', tep_get_return_reason_name($oInfo->return_reason_id, $languages[$i]['id']));
}
$contents[] = array('text' => '<br>' . TEXT_INFO_ORDERS_STATUS_NAME . $orders_status_inputs_string);
if (DEFAULT_ORDERS_STATUS_ID != $oInfo->return_reason_id) $contents[] = array('text' => '<br>' . tep_draw_checkbox_field('default') . ' ' . TEXT_SET_DEFAULT);
$contents[] = array('align' => 'center', 'text' => '<br><a href="' . tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $oInfo->return_reason_id) . '">' . tep_image_button('button_cancel.gif', IMAGE_CANCEL) . '</a>' . tep_image_submit('button_update.gif', IMAGE_UPDATE));
break;
case 'delete':
$heading[] = array('text' => '<b>' . TEXT_INFO_HEADING_DELETE_ORDERS_STATUS . '</b>');
$contents = array('form' => tep_draw_form('status', FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $oInfo->return_reason_id . '&action=deleteconfirm'));
$contents[] = array('text' => TEXT_INFO_DELETE_INTRO);
$contents[] = array('text' => '<br><b>' . $oInfo->return_reason_name . '</b>');
if ($remove_status) $contents[] = array('align' => 'center', 'text' => '<br><a href="' . tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $oInfo->return_reason_id) . '">' . tep_image_button('button_cancel.gif', IMAGE_CANCEL) . '</a>' . tep_image_submit('button_delete.gif', IMAGE_DELETE));
break;
default:
if (isset($oInfo) && is_object($oInfo)) {
$heading[] = array('text' => '<b>' . $oInfo->return_reason_name . '</b>');
$contents[] = array('align' => 'center', 'text' => '<br><a href="' . tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $oInfo->return_reason_id . '&action=edit') . '">' . tep_image_button('button_page_edit.png', IMAGE_EDIT) . '</a><a href="' . tep_href_link(FILENAME_RETURNS_REASONS, 'page=' . $_GET['page'] . '&oID=' . $oInfo->return_reason_id . '&action=delete') . '">' . tep_image_button('button_delete.gif', IMAGE_DELETE) . '</a>');
$orders_status_inputs_string = '';
$languages = tep_get_languages();
for ($i = 0, $n = sizeof($languages); $i < $n; $i++) {
$orders_status_inputs_string .= '<br>' . tep_image(DIR_WS_CATALOG_LANGUAGES . $languages[$i]['directory'] . '/images/' . $languages[$i]['image'], $languages[$i]['name']) . ' ' . tep_get_return_reason_name($oInfo->return_reason_id, $languages[$i]['id']);
}
$contents[] = array('text' => $orders_status_inputs_string);
}
break;
}
if ( (tep_not_null($heading)) && (tep_not_null($contents)) ) {
echo ' <td width="25%" valign="top">' . "\n";
$box = new box;
echo $box->infoBox($heading, $contents);
echo ' </td>' . "\n";
}
?>
</tr>
</table></td>
</tr>
</table></td>
<!-- body_text_eof //-->
</tr>
</table>
</div>
<!-- body_eof //-->
<!-- footer //-->
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<!-- footer_eof //-->
<br>
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
| loadedcommerce/loaded6 | 6.5/Loaded_Commerce_PRO_v6.5.2_Upgrade_from_all_Std_OR_Pro_versions/admin/returns_reasons.php | PHP | gpl-2.0 | 15,332 |
#!/usr/bin/perl
use warnings;
use strict;
use CGI;
use Graphics::Magick;
use POSIX qw(ceil);
use autouse 'Data::Dumper' => qw(Dumper);
use C4::Context;
use C4::Auth;
use C4::Output;
use C4::Debug;
use C4::Creators 1.000000;
use C4::Patroncards 1.000000;
my $cgi = CGI->new;
my ($template, $loggedinuser, $cookie) = get_template_and_user({
template_name => "patroncards/image-manage.tmpl",
query => $cgi,
type => "intranet",
authnotrequired => 0,
flagsrequired => {tools => 'batch_upload_patron_images'}, # FIXME: establish flag for patron card creator
debug => 0,
});
my $image_name = $cgi->param('image_name') || '';
my $file_name = $cgi->param('uploadfile') || '';
my $upload_file = $cgi->upload('uploadfile') || '';
my $op = $cgi->param('op') || 'none';
my @image_ids = $cgi->param('image_id') if $cgi->param('image_id');
my $source_file = "$file_name"; # otherwise we end up with what amounts to a pointer to a filehandle rather than a user-friendly filename
my $display_columns = { image => [ #{db column => {label => 'col label', is link? }},
{image_id => {label => 'ID', link_field => 0}},
{image_name => {label => 'Name', link_field => 0}},
{select => {label => 'Select', value => 'image_id'}},
],
};
my $table = html_table($display_columns->{'image'}, get_image(undef, "image_id, image_name"));
my $image_limit = C4::Context->preference('ImageLimit') || '';
my $errstr = ''; # NOTE: For error codes see error-messages.inc
if ($op eq 'upload') {
if (!$upload_file) {
warn sprintf('An error occurred while attempting to upload file %s.', $source_file);
$errstr = 301;
$template->param(
IMPORT_SUCCESSFUL => 0,
SOURCE_FILE => $source_file,
IMAGE_NAME => $image_name,
TABLE => $table,
error => 1,
$errstr => 1,
);
}
else {
my $image = Graphics::Magick->new;
eval{$image->Read($cgi->tmpFileName($file_name));};
if ($@) {
warn sprintf('An error occurred while creating the image object: %s',$@);
$errstr = 202;
$template->param(
IMPORT_SUCCESSFUL => 0,
SOURCE_FILE => $source_file,
IMAGE_NAME => $image_name,
TABLE => $table,
error => 1,
$errstr => 1,
);
}
else {
my $errstr = '';
my $size = $image->Get('filesize');
$errstr = 302 if $size > 500000;
$image->Set(magick => 'png'); # convert all images to png as this is a lossless format which is important for resizing operations later on
my $err = put_image($image_name, $image->ImageToBlob()) || '0';
$errstr = 101 if $err == 1;
$errstr = 303 if $err == 202;
if ($errstr) {
$template->param(
IMPORT_SUCCESSFUL => 0,
SOURCE_FILE => $source_file,
IMAGE_NAME => $image_name,
TABLE => $table,
error => 1,
$errstr => 1,
image_limit => $image_limit,
);
}
else {
$table = html_table($display_columns->{'image'}, get_image(undef, "image_id, image_name")); # refresh table data after successfully performing save operation
$template->param(
IMPORT_SUCCESSFUL => 1,
SOURCE_FILE => $source_file,
IMAGE_NAME => $image_name,
TABLE => $table,
);
}
}
}
}
elsif ($op eq 'delete') {
my $err = '';
my $errstr = '';
if (@image_ids) {
$err = rm_image(\@image_ids);
$errstr = 102 if $err;
}
else {
warn sprintf('No image ids passed in to delete.');
$errstr = 202;
}
if ($errstr) {
$template->param(
DELETE_SUCCESSFULL => 0,
IMAGE_IDS => join(', ', @image_ids),
TABLE => $table,
error => 1,
$errstr => 1,
image_ids => join(',',@image_ids),
);
}
else {
$table = html_table($display_columns->{'image'}, get_image(undef, "image_id, image_name")); # refresh table data after successfully performing delete operation
$template->param(
DELETE_SUCCESSFULL => 1,
TABLE => $table,
);
}
}
elsif ($op eq 'none') {
$template->param(
IMPORT_SUCCESSFUL => 0,
SOURCE_FILE => $source_file,
IMAGE_NAME => $image_name,
TABLE => $table,
);
}
else { # to trap unsupported operations
warn sprintf('Image upload interface called an unsupported operation: %s',$op);
$errstr = 201;
$template->param(
IMPORT_SUCCESSFUL => 0,
SOURCE_FILE => $source_file,
IMAGE_NAME => $image_name,
TABLE => $table,
error => 1,
$errstr => 1,
);
}
output_html_with_http_headers $cgi, $cookie, $template->output;
__END__
=head1 NAME
image-upload.pl - Script for handling uploading of single images and importing them into the database.
=head1 SYNOPSIS
image-upload.pl
=head1 DESCRIPTION
This script is called and presents the user with an interface allowing him/her to upload a single image file. Files greater than 500K will be refused.
=head1 AUTHOR
Chris Nighswonger <cnighswonger AT foundations DOT edu>
=head1 COPYRIGHT
Copyright 2009 Foundations Bible College.
=head1 LICENSE
This file is part of Koha.
Koha 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.
You should have received a copy of the GNU General Public License along with Koha; if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
Fifth Floor, Boston, MA 02110-1301 USA.
=head1 DISCLAIMER OF WARRANTY
Koha 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.
=cut
| MASmedios/koha | patroncards/image-manage.pl | Perl | gpl-2.0 | 6,701 |
/* Implementation of the BSD usleep function using nanosleep.
Copyright (C) 1996-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <drepper@cygnus.com>, 1996.
The GNU C 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.
The GNU C 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 the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <time.h>
#include <unistd.h>
int
usleep (useconds_t useconds)
{
struct timespec ts = { .tv_sec = (long int) (useconds / 1000000),
.tv_nsec = (long int) (useconds % 1000000) * 1000ul };
/* Note the usleep() is a cancellation point. But since we call
nanosleep() which itself is a cancellation point we do not have
to do anything here. */
return __nanosleep (&ts, NULL);
}
| Chilledheart/glibc | sysdeps/posix/usleep.c | C | gpl-2.0 | 1,316 |
{% extends "allianceauth/base.html" %}
{% load bootstrap %}
{% load staticfiles %}
{% load i18n %}
{% block page_title %}{% trans "Jabber Broadcast" %}{% endblock page_title %}
{% block extra_css %}{% endblock extra_css %}
{% block content %}
<div class="col-lg-12">
<h1 class="page-header text-center">{% trans "Jabber Broadcast" %}</h1>
<div class="container-fluid">
<div class="col-md-4 col-md-offset-4">
<div class="row">
{% if success %}
<div class="alert alert-success" role="alert">{% trans "Broadcast Sent!!" %}</div>
{% endif %}
<form class="form-signin" role="form" action="" method="POST"
onsubmit="submitbutton.disabled = true; return true;">
{% csrf_token %}
{{ form|bootstrap }}
<br/>
<button class="btn btn-lg btn-primary btn-block" name="submitbutton" type="submit">{% trans "Broadcast" %}
</button>
</form>
</div>
</div>
</div>
</div>
{% endblock content %}
| R4stl1n/allianceauth | allianceauth/services/modules/openfire/templates/services/openfire/broadcast.html | HTML | gpl-2.0 | 1,217 |
#include <config.h>
#include "testutils.h"
#ifdef WITH_OPENVZ
# include <stdio.h>
# include <string.h>
# include <unistd.h>
# include "internal.h"
# include "viralloc.h"
# include "openvz/openvz_conf.h"
# include "virstring.h"
# define VIR_FROM_THIS VIR_FROM_OPENVZ
static int
testLocateConfFile(int vpsid ATTRIBUTE_UNUSED, char **conffile,
const char *ext ATTRIBUTE_UNUSED)
{
return virAsprintf(conffile, "%s/openvzutilstest.conf", abs_srcdir);
}
struct testConfigParam {
const char *param;
const char *value;
int ret;
};
static struct testConfigParam configParams[] = {
{ "OSTEMPLATE", "rhel-5-lystor", 1 },
{ "IP_ADDRESS", "194.44.18.88", 1 },
{ "THIS_PARAM_IS_MISSING", NULL, 0 },
};
static int
testReadConfigParam(const void *data ATTRIBUTE_UNUSED)
{
int result = -1;
size_t i;
char *conf = NULL;
char *value = NULL;
if (virAsprintf(&conf, "%s/openvzutilstest.conf", abs_srcdir) < 0)
return -1;
for (i = 0; i < ARRAY_CARDINALITY(configParams); ++i) {
if (openvzReadConfigParam(conf, configParams[i].param,
&value) != configParams[i].ret) {
goto cleanup;
}
if (configParams[i].ret != 1)
continue;
if (STRNEQ(configParams[i].value, value)) {
virtTestDifference(stderr, configParams[i].value, value);
goto cleanup;
}
}
result = 0;
cleanup:
VIR_FREE(conf);
VIR_FREE(value);
return result;
}
static int
testReadNetworkConf(const void *data ATTRIBUTE_UNUSED)
{
int result = -1;
virDomainDefPtr def = NULL;
char *actual = NULL;
virErrorPtr err = NULL;
const char *expected =
"<domain type='openvz'>\n"
" <uuid>00000000-0000-0000-0000-000000000000</uuid>\n"
" <memory unit='KiB'>0</memory>\n"
" <currentMemory unit='KiB'>0</currentMemory>\n"
" <vcpu placement='static'>0</vcpu>\n"
" <os>\n"
" <type>exe</type>\n"
" <init>/sbin/init</init>\n"
" </os>\n"
" <clock offset='utc'/>\n"
" <on_poweroff>destroy</on_poweroff>\n"
" <on_reboot>destroy</on_reboot>\n"
" <on_crash>destroy</on_crash>\n"
" <devices>\n"
" <interface type='ethernet'>\n"
" <mac address='00:00:00:00:00:00'/>\n"
" <ip address='194.44.18.88' family='ipv4'/>\n"
" </interface>\n"
" <interface type='bridge'>\n"
" <mac address='00:18:51:c1:05:ee'/>\n"
" <target dev='veth105.10'/>\n"
" </interface>\n"
" </devices>\n"
"</domain>\n";
if (!(def = virDomainDefNew()) ||
VIR_STRDUP(def->os.type, "exe") < 0 ||
VIR_STRDUP(def->os.init, "/sbin/init") < 0)
goto cleanup;
def->virtType = VIR_DOMAIN_VIRT_OPENVZ;
if (openvzReadNetworkConf(def, 1) < 0) {
err = virGetLastError();
fprintf(stderr, "ERROR: %s\n", err != NULL ? err->message : "<unknown>");
goto cleanup;
}
actual = virDomainDefFormat(def, VIR_DOMAIN_DEF_FORMAT_INACTIVE);
if (actual == NULL) {
err = virGetLastError();
fprintf(stderr, "ERROR: %s\n", err != NULL ? err->message : "<unknown>");
goto cleanup;
}
if (STRNEQ(expected, actual)) {
virtTestDifference(stderr, expected, actual);
goto cleanup;
}
result = 0;
cleanup:
VIR_FREE(actual);
virDomainDefFree(def);
return result;
}
static int
mymain(void)
{
int result = 0;
openvzLocateConfFile = testLocateConfFile;
# define DO_TEST(_name) \
do { \
if (virtTestRun("OpenVZ "#_name, test##_name, \
NULL) < 0) { \
result = -1; \
} \
} while (0)
DO_TEST(ReadConfigParam);
DO_TEST(ReadNetworkConf);
return result == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}
VIRT_TEST_MAIN(mymain)
#else
int main(void)
{
return EXIT_AM_SKIP;
}
#endif /* WITH_OPENVZ */
| ethernetdan/libvirt | tests/openvzutilstest.c | C | gpl-2.0 | 4,363 |
/* Install given floating-point environment.
Copyright (C) 1997-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
The GNU C 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.
The GNU C 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 the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <fenv.h>
#include <fpu_control.h>
#include <assert.h>
#include <unistd.h>
#include <ldsodefs.h>
#include <dl-procinfo.h>
/* All exceptions, including the x86-specific "denormal operand"
exception. */
#define FE_ALL_EXCEPT_X86 (FE_ALL_EXCEPT | __FE_DENORM)
int
__fesetenv (const fenv_t *envp)
{
fenv_t temp;
/* The memory block used by fstenv/fldenv has a size of 28 bytes. */
assert (sizeof (fenv_t) == 28);
/* Install the environment specified by ENVP. But there are a few
values which we do not want to come from the saved environment.
Therefore, we get the current environment and replace the values
we want to use from the environment specified by the parameter. */
__asm__ ("fnstenv %0" : "=m" (*&temp));
if (envp == FE_DFL_ENV)
{
temp.__control_word |= FE_ALL_EXCEPT_X86;
temp.__control_word &= ~FE_TOWARDZERO;
temp.__control_word |= _FPU_EXTENDED;
temp.__status_word &= ~FE_ALL_EXCEPT_X86;
}
else if (envp == FE_NOMASK_ENV)
{
temp.__control_word &= ~(FE_ALL_EXCEPT | FE_TOWARDZERO);
/* Keep the "denormal operand" exception masked. */
temp.__control_word |= __FE_DENORM;
temp.__control_word |= _FPU_EXTENDED;
temp.__status_word &= ~FE_ALL_EXCEPT_X86;
}
else
{
temp.__control_word &= ~(FE_ALL_EXCEPT_X86
| FE_TOWARDZERO
| _FPU_EXTENDED);
temp.__control_word |= (envp->__control_word
& (FE_ALL_EXCEPT_X86
| FE_TOWARDZERO
| _FPU_EXTENDED));
temp.__status_word &= ~FE_ALL_EXCEPT_X86;
temp.__status_word |= envp->__status_word & FE_ALL_EXCEPT_X86;
}
temp.__eip = 0;
temp.__cs_selector = 0;
temp.__opcode = 0;
temp.__data_offset = 0;
temp.__data_selector = 0;
__asm__ ("fldenv %0" : : "m" (temp));
if ((GLRO(dl_hwcap) & HWCAP_I386_XMM) != 0)
{
unsigned int mxcsr;
__asm__ ("stmxcsr %0" : "=m" (mxcsr));
if (envp == FE_DFL_ENV)
{
/* Clear SSE exceptions. */
mxcsr &= ~FE_ALL_EXCEPT_X86;
/* Set mask for SSE MXCSR. */
mxcsr |= (FE_ALL_EXCEPT_X86 << 7);
/* Set rounding to FE_TONEAREST. */
mxcsr &= ~0x6000;
mxcsr |= (FE_TONEAREST << 3);
/* Clear the FZ and DAZ bits. */
mxcsr &= ~0x8040;
}
else if (envp == FE_NOMASK_ENV)
{
/* Clear SSE exceptions. */
mxcsr &= ~FE_ALL_EXCEPT_X86;
/* Do not mask exceptions. */
mxcsr &= ~(FE_ALL_EXCEPT << 7);
/* Keep the "denormal operand" exception masked. */
mxcsr |= (__FE_DENORM << 7);
/* Set rounding to FE_TONEAREST. */
mxcsr &= ~0x6000;
mxcsr |= (FE_TONEAREST << 3);
/* Clear the FZ and DAZ bits. */
mxcsr &= ~0x8040;
}
else
mxcsr = envp->__eip;
__asm__ ("ldmxcsr %0" : : "m" (mxcsr));
}
/* Success. */
return 0;
}
#include <shlib-compat.h>
#if SHLIB_COMPAT (libm, GLIBC_2_1, GLIBC_2_2)
strong_alias (__fesetenv, __old_fesetenv)
compat_symbol (libm, __old_fesetenv, fesetenv, GLIBC_2_1);
#endif
libm_hidden_def (__fesetenv)
libm_hidden_ver (__fesetenv, fesetenv)
versioned_symbol (libm, __fesetenv, fesetenv, GLIBC_2_2);
| Chilledheart/glibc | sysdeps/i386/fpu/fesetenv.c | C | gpl-2.0 | 3,996 |
/*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
* Free SoftwareFoundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.ejb.cfg;
import com.caucho.config.ConfigException;
import com.caucho.config.types.DescriptionGroupConfig;
import com.caucho.config.types.Signature;
import com.caucho.util.L10N;
import com.caucho.vfs.Path;
import java.util.*;
import javax.annotation.PostConstruct;
/**
* Configuration for an ejb bean.
*/
public class EjbJar extends DescriptionGroupConfig {
private static final L10N L = new L10N(EjbJar.class);
private final EjbConfig _config;
private String _ejbModuleName;
private Path _rootPath;
private boolean _isMetadataComplete;
private boolean _isSkip;
public EjbJar(EjbConfig config,
String ejbModuleName,
Path rootPath)
{
_config = config;
_ejbModuleName = ejbModuleName;
_rootPath = rootPath;
}
public String getModuleName()
{
return _ejbModuleName;
}
public void setModuleName(String moduleName)
{
_ejbModuleName = moduleName;
}
public void setVersion(String version)
{
}
public void setSchemaLocation(String value)
{
}
public void setSkip(boolean isSkip)
{
_isSkip = isSkip;
}
public boolean isSkip()
{
return _isSkip;
}
public void setMetadataComplete(boolean isMetadataComplete)
{
_isMetadataComplete = isMetadataComplete;
}
public boolean isMetadataComplete()
{
return _isMetadataComplete;
}
public EjbEnterpriseBeans createEnterpriseBeans()
throws ConfigException
{
return new EjbEnterpriseBeans(_config, this, _ejbModuleName);
}
public InterceptorsConfig createInterceptors()
throws ConfigException
{
return new InterceptorsConfig(_config);
}
public Relationships createRelationships()
throws ConfigException
{
return new Relationships(_config);
}
public AssemblyDescriptor createAssemblyDescriptor()
throws ConfigException
{
return new AssemblyDescriptor(this, _config);
}
public void addQueryFunction(QueryFunction fun)
{
}
public void setBooleanLiteral(BooleanLiteral literal)
{
}
ContainerTransaction createContainerTransaction()
{
return new ContainerTransaction(this, _config);
}
MethodPermission createMethodPermission()
{
return new MethodPermission(_config);
}
public String toString()
{
return getClass().getSimpleName() + "[" + _rootPath.getFullPath() + "]";
}
public class MethodPermission {
EjbConfig _config;
MethodSignature _method;
ArrayList<String> _roles;
MethodPermission(EjbConfig config)
{
_config = config;
}
public void setDescription(String description)
{
}
public void setUnchecked(boolean unchecked)
{
}
public void setRoleName(String roleName)
{
if (_roles == null)
_roles = new ArrayList<String>();
_roles.add(roleName);
}
public void setMethod(MethodSignature method)
{
_method = method;
}
@PostConstruct
public void init()
throws ConfigException
{
if (isSkip())
return;
EjbBean bean = _config.getBeanConfig(_method.getEJBName());
if (bean == null)
throw new ConfigException(L.l("'{0}' is an unknown bean.",
_method.getEJBName()));
EjbMethodPattern method = bean.createMethod(_method);
if (_roles != null)
method.setRoles(_roles);
}
}
public static class QueryFunction {
FunctionSignature _sig;
String _sql;
public void setSignature(Signature sig)
throws ConfigException
{
_sig = new FunctionSignature(sig.getSignature());
}
public FunctionSignature getSignature()
{
return _sig;
}
public void setSQL(String sql)
throws ConfigException
{
_sql = sql;
}
public String getSQL()
{
return _sql;
}
@PostConstruct
public void init()
{
_sig.setSQL(_sql);
}
}
public static class Relationships {
EjbConfig _config;
Relationships(EjbConfig config)
{
_config = config;
}
}
}
| WelcomeHUME/svn-caucho-com-resin | modules/resin/src/com/caucho/ejb/cfg/EjbJar.java | Java | gpl-2.0 | 5,125 |
/***************************************************************************
qgslabelposition.h
-------------------
begin : February 2021
copyright : (C) Nyall Dawson
email : nyall dot dawson at gmail dot com
***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#ifndef QGSLABELPOSITION_H
#define QGSLABELPOSITION_H
#include "qgis_core.h"
#include "qgis_sip.h"
#include "qgspointxy.h"
#include "qgsrectangle.h"
#include "qgsgeometry.h"
#include <QFont>
/**
* \ingroup core
* \class QgsLabelPosition
* \brief Represents the calculated placement of a map label.
*/
class CORE_EXPORT QgsLabelPosition
{
public:
/**
* Constructor for QgsLabelPosition.
* \param id associated feature ID
* \param r label rotation in degrees clockwise
* \param corners corner points of label bounding box, in map units
* \param rect label bounding box, in map units
* \param w width of label, in map units
* \param h height of label, in map units
* \param layer ID of associated map layer
* \param labeltext text rendered for label
* \param labelfont font used to render label
* \param upside_down TRUE if label is upside down
* \param diagram TRUE if label is a diagram
* \param pinned TRUE if label has pinned placement
* \param providerId ID of associated label provider
* \param labelGeometry polygon geometry of label boundary
* \param isUnplaced set to TRUE if label was unplaced (e.g. due to collisions with other labels)
*/
QgsLabelPosition( QgsFeatureId id, double r, const QVector< QgsPointXY > &corners, const QgsRectangle &rect, double w, double h, const QString &layer, const QString &labeltext, const QFont &labelfont, bool upside_down, bool diagram = false, bool pinned = false, const QString &providerId = QString(),
const QgsGeometry &labelGeometry = QgsGeometry(), bool isUnplaced = false )
: featureId( id )
, rotation( r )
, cornerPoints( corners )
, labelRect( rect )
, labelGeometry( labelGeometry )
, width( w )
, height( h )
, layerID( layer )
, labelText( labeltext )
, labelFont( labelfont )
, upsideDown( upside_down )
, isDiagram( diagram )
, isPinned( pinned )
, providerID( providerId )
, isUnplaced( isUnplaced )
{}
//! Constructor for QgsLabelPosition
QgsLabelPosition() = default;
/**
* ID of feature associated with this label.
*/
QgsFeatureId featureId = FID_NULL;
/**
* Rotation of label, in degrees clockwise.
*/
double rotation = 0;
QVector< QgsPointXY > cornerPoints;
QgsRectangle labelRect;
/**
* A polygon geometry representing the label's bounds in map coordinates.
* \since QGIS 3.4.9
*/
QgsGeometry labelGeometry;
/**
* Width of label bounding box, in map units.
*/
double width = 0;
/**
* Heeght of label bounding box, in map units.
*/
double height = 0;
/**
* ID of associated map layer.
*/
QString layerID;
/**
* String shown in label.
*/
QString labelText;
/**
* Font which the label is rendered using.
*/
QFont labelFont;
/**
* TRUE if label is upside down.
*/
bool upsideDown = false;
/**
* TRUE if label is a diagram.
*/
bool isDiagram = false;
/**
* TRUE if label position has been pinned.
*/
bool isPinned = false;
/**
* ID of the associated label provider.
* \since QGIS 2.14
*/
QString providerID;
/**
* TRUE if label position corresponds to an unplaced label.
* \since QGIS 3.10
*/
bool isUnplaced = false;
};
#endif // QGSLABELPOSITION_H
| dmarteau/QGIS | src/core/labeling/qgslabelposition.h | C | gpl-2.0 | 4,392 |
#include "fdiskP.h"
/*
* Don't use this function derectly, use fdisk_new_context_from_filename()
*/
int fdisk_probe_labels(struct fdisk_context *cxt)
{
size_t i;
cxt->label = NULL;
for (i = 0; i < cxt->nlabels; i++) {
struct fdisk_label *lb = cxt->labels[i];
struct fdisk_label *org = cxt->label;
int rc;
if (!lb->op->probe)
continue;
if (lb->disabled) {
DBG(CXT, ul_debugobj(cxt, "%s: disabled -- ignore", lb->name));
continue;
}
DBG(CXT, ul_debugobj(cxt, "probing for %s", lb->name));
cxt->label = lb;
rc = lb->op->probe(cxt);
cxt->label = org;
if (rc != 1) {
if (lb->op->deinit)
lb->op->deinit(lb); /* for sure */
continue;
}
__fdisk_context_switch_label(cxt, lb);
return 0;
}
DBG(CXT, ul_debugobj(cxt, "no label found"));
return 1; /* not found */
}
/**
* fdisk_dev_has_disklabel:
* @cxt: fdisk context
*
* Returns: return 1 if there is label on the device.
*/
int fdisk_dev_has_disklabel(struct fdisk_context *cxt)
{
return cxt && cxt->label;
}
/**
* fdisk_dev_is_disklabel:
* @cxt: fdisk context
* @l: disklabel type
*
* Returns: return 1 if there is @l disklabel on the device.
*/
int fdisk_dev_is_disklabel(struct fdisk_context *cxt, enum fdisk_labeltype l)
{
return cxt && cxt->label && cxt->label->id == l;
}
/**
* fdisk_write_disklabel:
* @cxt: fdisk context
*
* Write in-memory changes to disk
*
* Returns 0 on success, otherwise, a corresponding error.
*/
int fdisk_write_disklabel(struct fdisk_context *cxt)
{
if (!cxt || !cxt->label || cxt->readonly)
return -EINVAL;
if (!cxt->label->op->write)
return -ENOSYS;
return cxt->label->op->write(cxt);
}
int fdisk_require_geometry(struct fdisk_context *cxt)
{
assert(cxt);
return cxt->label
&& cxt->label->flags & FDISK_LABEL_FL_REQUIRE_GEOMETRY ? 1 : 0;
}
int fdisk_missing_geometry(struct fdisk_context *cxt)
{
int rc;
assert(cxt);
rc = (fdisk_require_geometry(cxt) &&
(!cxt->geom.heads || !cxt->geom.sectors
|| !cxt->geom.cylinders));
if (rc && !fdisk_context_listonly(cxt))
fdisk_warnx(cxt, _("Incomplete geometry setting."));
return rc;
}
/**
* fdisk_get_columns:
* @cxt: fdisk context
* @all: 1 or 0
* @cols: returns allocated array with FDISK_COL_* IDs
* @ncols: returns number of items in cols
*
* This function returns the default or all columns for the current label. The
* library uses the columns for list operations (see fdisk_list_disklabel() and
* fdisk_list_partitions()). Note that the set of the default columns depends
* on fdisk_context_enable_details() function. If the details are eanable then
* this function usually returns more columns.
*
* Returns 0 on success, otherwise, a corresponding error.
*/
int fdisk_get_columns(struct fdisk_context *cxt, int all, int **cols, size_t *ncols)
{
size_t i, n;
int *c;
assert(cxt);
if (!cxt->label)
return -EINVAL;
if (!cxt->label->columns || !cxt->label->ncolumns)
return -ENOSYS;
c = calloc(cxt->label->ncolumns, sizeof(int));
if (!c)
return -ENOMEM;
for (n = 0, i = 0; i < cxt->label->ncolumns; i++) {
int id = cxt->label->columns[i].id;
if (!all &&
((fdisk_context_display_details(cxt) &&
(cxt->label->columns[i].flags & FDISK_COLFL_EYECANDY))
|| (!fdisk_context_display_details(cxt) &&
(cxt->label->columns[i].flags & FDISK_COLFL_DETAIL))
|| (id == FDISK_COL_SECTORS &&
fdisk_context_use_cylinders(cxt))
|| (id == FDISK_COL_CYLINDERS &&
!fdisk_context_use_cylinders(cxt))))
continue;
c[n++] = id;
}
if (cols)
*cols = c;
else
free(c);
if (ncols)
*ncols = n;
return 0;
}
const struct fdisk_column *fdisk_label_get_column(
struct fdisk_label *lb, int id)
{
size_t i;
assert(lb);
assert(id > 0);
for (i = 0; i < lb->ncolumns; i++) {
if (lb->columns[i].id == id)
return &lb->columns[i];
}
return NULL;
}
/**
* fdisk_verify_disklabel:
* @cxt: fdisk context
*
* Verifies the partition table.
*
* Returns: 0 on success, otherwise, a corresponding error.
*/
int fdisk_verify_disklabel(struct fdisk_context *cxt)
{
if (!cxt || !cxt->label)
return -EINVAL;
if (!cxt->label->op->verify)
return -ENOSYS;
if (fdisk_missing_geometry(cxt))
return -EINVAL;
return cxt->label->op->verify(cxt);
}
/**
* fdisk_list_disklabel:
* @cxt: fdisk context
*
* Lists details about disklabel, but no partitions.
*
* This function uses libfdisk ASK interface to print data. The details about
* partitions table are printed by FDISK_ASKTYPE_INFO.
*
* Returns 0 on success, otherwise, a corresponding error.
*/
int fdisk_list_disklabel(struct fdisk_context *cxt)
{
if (!cxt || !cxt->label)
return -EINVAL;
if (!cxt->label->op->list)
return -ENOSYS;
return cxt->label->op->list(cxt);
}
/**
* fdisk_create_disklabel:
* @cxt: fdisk context
* @name: label name
*
* Creates a new disk label of type @name. If @name is NULL, then it
* will create a default system label type, either SUN or DOS.
*
* Returns 0 on success, otherwise, a corresponding error.
*/
int fdisk_create_disklabel(struct fdisk_context *cxt, const char *name)
{
int haslabel = 0;
struct fdisk_label *lb;
if (!cxt)
return -EINVAL;
if (!name) { /* use default label creation */
#ifdef __sparc__
name = "sun";
#else
name = "dos";
#endif
}
if (cxt->label) {
fdisk_deinit_label(cxt->label);
haslabel = 1;
}
lb = fdisk_context_get_label(cxt, name);
if (!lb || lb->disabled)
return -EINVAL;
if (!lb->op->create)
return -ENOSYS;
__fdisk_context_switch_label(cxt, lb);
if (haslabel && !cxt->parent)
fdisk_reset_device_properties(cxt);
DBG(CXT, ul_debugobj(cxt, "create a new %s label", lb->name));
return cxt->label->op->create(cxt);
}
int fdisk_locate_disklabel(struct fdisk_context *cxt, int n, const char **name,
off_t *offset, size_t *size)
{
if (!cxt || !cxt->label)
return -EINVAL;
if (!cxt->label->op->locate)
return -ENOSYS;
DBG(CXT, ul_debugobj(cxt, "locating %d chunk of %s.", n, cxt->label->name));
return cxt->label->op->locate(cxt, n, name, offset, size);
}
/**
* fdisk_get_disklabel_id:
* @cxt: fdisk context
* @id: returns pointer to allocated string
*
* Returns 0 on success, otherwise, a corresponding error.
*/
int fdisk_get_disklabel_id(struct fdisk_context *cxt, char **id)
{
if (!cxt || !cxt->label)
return -EINVAL;
if (!cxt->label->op->get_id)
return -ENOSYS;
DBG(CXT, ul_debugobj(cxt, "asking for disk %s ID", cxt->label->name));
return cxt->label->op->get_id(cxt, id);
}
/**
* fdisk_get_disklabel_id:
* @cxt: fdisk context
*
* Returns 0 on success, otherwise, a corresponding error.
*/
int fdisk_set_disklabel_id(struct fdisk_context *cxt)
{
if (!cxt || !cxt->label)
return -EINVAL;
if (!cxt->label->op->set_id)
return -ENOSYS;
DBG(CXT, ul_debugobj(cxt, "setting %s disk ID", cxt->label->name));
return cxt->label->op->set_id(cxt);
}
/**
* fdisk_set_partition_type:
* @cxt: fdisk context
* @partnum: partition number
* @t: new type
*
* Returns 0 on success, < 0 on error.
*/
int fdisk_set_partition_type(struct fdisk_context *cxt,
size_t partnum,
struct fdisk_parttype *t)
{
if (!cxt || !cxt->label)
return -EINVAL;
if (!cxt->label->op->part_set_type)
return -ENOSYS;
DBG(CXT, ul_debugobj(cxt, "partition: %zd: set type", partnum));
return cxt->label->op->part_set_type(cxt, partnum, t);
}
/**
* fdisk_get_nparttypes:
* @cxt: fdisk context
*
* Returns: number of partition types supported by the current label
*/
size_t fdisk_get_nparttypes(struct fdisk_context *cxt)
{
if (!cxt || !cxt->label)
return 0;
return cxt->label->nparttypes;
}
/**
* fdisk_partition_taggle_flag:
* @cxt: fdisk context
* @partnum: partition number
* @status: flags
*
* Returns 0 on success, otherwise, a corresponding error.
*/
int fdisk_partition_toggle_flag(struct fdisk_context *cxt,
size_t partnum,
unsigned long flag)
{
int rc;
if (!cxt || !cxt->label)
return -EINVAL;
if (!cxt->label->op->part_toggle_flag)
return -ENOSYS;
rc = cxt->label->op->part_toggle_flag(cxt, partnum, flag);
DBG(CXT, ul_debugobj(cxt, "partition: %zd: toggle: 0x%04lx [rc=%d]", partnum, flag, rc));
return rc;
}
/**
* fdisk_reorder_partitions
* @cxt: fdisk context
*
* Sort partitions according to the partition start sector.
*
* Returns 0 on success, otherwise, a corresponding error.
*/
int fdisk_reorder_partitions(struct fdisk_context *cxt)
{
if (!cxt || !cxt->label)
return -EINVAL;
if (!cxt->label->op->reorder)
return -ENOSYS;
return cxt->label->op->reorder(cxt);
}
/*
* Resets the current used label driver to initial state
*/
void fdisk_deinit_label(struct fdisk_label *lb)
{
assert(lb);
/* private label information */
if (lb->op->deinit)
lb->op->deinit(lb);
}
void fdisk_label_set_changed(struct fdisk_label *lb, int changed)
{
assert(lb);
lb->changed = changed ? 1 : 0;
}
int fdisk_label_is_changed(struct fdisk_label *lb)
{
assert(lb);
return lb ? lb->changed : 0;
}
void fdisk_label_set_disabled(struct fdisk_label *lb, int disabled)
{
assert(lb);
DBG(LABEL, ul_debug("%s label %s",
lb->name,
disabled ? "DISABLED" : "ENABLED"));
lb->disabled = disabled ? 1 : 0;
}
int fdisk_label_is_disabled(struct fdisk_label *lb)
{
assert(lb);
return lb ? lb->disabled : 0;
}
| azuwis/debian_util-linux-extra | libfdisk/src/label.c | C | gpl-2.0 | 9,342 |
/* Copyright (c) 2009-2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 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.
*
*/
#include <linux/libra_sdioif.h>
#include <linux/delay.h>
#include <linux/mmc/sdio.h>
#include <linux/mmc/mmc.h>
#include <linux/mmc/host.h>
#include <linux/mmc/card.h>
/* Libra SDIO function device */
static struct sdio_func *libra_sdio_func;
static struct mmc_host *libra_mmc_host;
static int libra_mmc_host_index;
/* SDIO Card ID / Device ID */
static unsigned short libra_sdio_card_id;
/* completion variables */
struct completion gCard_rem_event_var;
EXPORT_SYMBOL(gCard_rem_event_var);
struct completion gShutdown_event_var;
EXPORT_SYMBOL(gShutdown_event_var);
static suspend_handler_t *libra_suspend_hldr;
static resume_handler_t *libra_resume_hldr;
static notify_card_removal_t *libra_notify_card_removal_hdlr;
static shutdown_handler_t *libra_sdio_shutdown_hdlr;
int libra_enable_sdio_irq_in_chip(struct sdio_func *func, u8 enable)
{
unsigned char reg = 0;
int err = 0;
sdio_claim_host(func);
/* Read the value into reg */
libra_sdiocmd52(func, SDIO_CCCR_IENx, ®, 0, &err);
if (err)
printk(KERN_ERR "%s: Could not read SDIO_CCCR_IENx register "
"err=%d\n", __func__, err);
if (libra_mmc_host) {
if (enable) {
reg |= 1 << func->num;
reg |= 1;
} else {
reg &= ~(1 << func->num);
}
libra_sdiocmd52(func, SDIO_CCCR_IENx, ®, 1, &err);
if (err)
printk(KERN_ERR "%s: Could not enable/disable irq "
"err=%d\n", __func__, err);
}
sdio_release_host(func);
return err;
}
EXPORT_SYMBOL(libra_enable_sdio_irq_in_chip);
/**
* libra_sdio_configure() - Function to configure the SDIO device param
* @libra_sdio_rxhandler Rx handler
* @func_drv_fn Function driver function for special setup
* @funcdrv_timeout Function Enable timeout
* @blksize Block size
*
* Configure SDIO device, enable function and set block size
*/
int libra_sdio_configure(sdio_irq_handler_t libra_sdio_rxhandler,
void (*func_drv_fn)(int *status),
unsigned int funcdrv_timeout, unsigned int blksize)
{
int err_ret = 0;
struct sdio_func *func = libra_sdio_func;
if (libra_sdio_func == NULL) {
printk(KERN_ERR "%s: Error SDIO card not detected\n", __func__);
goto cfg_error;
}
sdio_claim_host(func);
/* Currently block sizes are set here. */
func->max_blksize = blksize;
if (sdio_set_block_size(func, blksize)) {
printk(KERN_ERR "%s: Unable to set the block size.\n",
__func__);
sdio_release_host(func);
goto cfg_error;
}
/* Function driver specific configuration. */
if (func_drv_fn) {
(*func_drv_fn)(&err_ret);
if (err_ret) {
printk(KERN_ERR "%s: function driver provided configure function error=%d\n",
__func__, err_ret);
sdio_release_host(func);
goto cfg_error;
}
}
/* We set this based on the function card. */
func->enable_timeout = funcdrv_timeout;
err_ret = sdio_enable_func(func);
if (err_ret != 0) {
printk(KERN_ERR "%s: Unable to enable function %d\n",
__func__, err_ret);
sdio_release_host(func);
goto cfg_error;
}
if (sdio_claim_irq(func, libra_sdio_rxhandler)) {
sdio_disable_func(func);
printk(KERN_ERR "%s: Unable to claim irq.\n", __func__);
sdio_release_host(func);
goto cfg_error;
}
libra_enable_sdio_irq_in_chip(func, 0);
sdio_release_host(func);
return 0;
cfg_error:
return -1;
}
EXPORT_SYMBOL(libra_sdio_configure);
int libra_sdio_configure_suspend_resume(
suspend_handler_t *libra_sdio_suspend_hdlr,
resume_handler_t *libra_sdio_resume_hdlr)
{
libra_suspend_hldr = libra_sdio_suspend_hdlr;
libra_resume_hldr = libra_sdio_resume_hdlr;
return 0;
}
EXPORT_SYMBOL(libra_sdio_configure_suspend_resume);
/*
* libra_sdio_deconfigure() - Function to reset the SDIO device param
*/
void libra_sdio_deconfigure(struct sdio_func *func)
{
if (NULL == libra_sdio_func)
return;
sdio_claim_host(func);
sdio_release_irq(func);
sdio_disable_func(func);
sdio_release_host(func);
}
EXPORT_SYMBOL(libra_sdio_deconfigure);
int libra_enable_sdio_irq(struct sdio_func *func, u8 enable)
{
if (libra_mmc_host && libra_mmc_host->ops &&
libra_mmc_host->ops->enable_sdio_irq) {
libra_mmc_host->ops->enable_sdio_irq(libra_mmc_host, enable);
return 0;
}
printk(KERN_ERR "%s: Could not enable disable irq\n", __func__);
return -EINVAL;
}
EXPORT_SYMBOL(libra_enable_sdio_irq);
int libra_disable_sdio_irq_capability(struct sdio_func *func, u8 disable)
{
if (libra_mmc_host) {
if (disable)
libra_mmc_host->caps &= ~MMC_CAP_SDIO_IRQ;
else
libra_mmc_host->caps |= MMC_CAP_SDIO_IRQ;
return 0;
}
printk(KERN_ERR "%s: Could not change sdio capabilities to polling\n",
__func__);
return -EINVAL;
}
EXPORT_SYMBOL(libra_disable_sdio_irq_capability);
/*
* libra_sdio_release_irq() - Function to release IRQ
*/
void libra_sdio_release_irq(struct sdio_func *func)
{
if (NULL == libra_sdio_func)
return;
sdio_release_irq(func);
}
EXPORT_SYMBOL(libra_sdio_release_irq);
/*
* libra_sdio_disable_func() - Function to disable sdio func
*/
void libra_sdio_disable_func(struct sdio_func *func)
{
if (NULL == libra_sdio_func)
return;
sdio_disable_func(func);
}
EXPORT_SYMBOL(libra_sdio_disable_func);
/*
* Return the SDIO Function device
*/
struct sdio_func *libra_getsdio_funcdev(void)
{
return libra_sdio_func;
}
EXPORT_SYMBOL(libra_getsdio_funcdev);
/*
* Set function driver as the private data for the function device
*/
void libra_sdio_setprivdata(struct sdio_func *sdio_func_dev,
void *padapter)
{
if (NULL == libra_sdio_func)
return;
sdio_set_drvdata(sdio_func_dev, padapter);
}
EXPORT_SYMBOL(libra_sdio_setprivdata);
/*
* Return private data of the function device.
*/
void *libra_sdio_getprivdata(struct sdio_func *sdio_func_dev)
{
return sdio_get_drvdata(sdio_func_dev);
}
EXPORT_SYMBOL(libra_sdio_getprivdata);
/*
* Function driver claims the SDIO device
*/
void libra_claim_host(struct sdio_func *sdio_func_dev,
pid_t *curr_claimed, pid_t current_pid, atomic_t *claim_count)
{
if (NULL == libra_sdio_func)
return;
if (*curr_claimed == current_pid) {
atomic_inc(claim_count);
return;
}
/* Go ahead and claim the host if not locked by anybody. */
sdio_claim_host(sdio_func_dev);
*curr_claimed = current_pid;
atomic_inc(claim_count);
}
EXPORT_SYMBOL(libra_claim_host);
/*
* Function driver releases the SDIO device
*/
void libra_release_host(struct sdio_func *sdio_func_dev,
pid_t *curr_claimed, pid_t current_pid, atomic_t *claim_count)
{
if (NULL == libra_sdio_func)
return;
if (*curr_claimed != current_pid) {
/* Dont release */
return;
}
atomic_dec(claim_count);
if (atomic_read(claim_count) == 0) {
*curr_claimed = 0;
sdio_release_host(sdio_func_dev);
}
}
EXPORT_SYMBOL(libra_release_host);
void libra_sdiocmd52(struct sdio_func *sdio_func_dev, unsigned int addr,
u8 *byte_var, int write, int *err_ret)
{
if (write)
sdio_writeb(sdio_func_dev, byte_var[0], addr, err_ret);
else
byte_var[0] = sdio_readb(sdio_func_dev, addr, err_ret);
}
EXPORT_SYMBOL(libra_sdiocmd52);
u8 libra_sdio_readsb(struct sdio_func *func, void *dst,
unsigned int addr, int count)
{
return sdio_readsb(func, dst, addr, count);
}
EXPORT_SYMBOL(libra_sdio_readsb);
int libra_sdio_memcpy_fromio(struct sdio_func *func,
void *dst, unsigned int addr, int count)
{
return sdio_memcpy_fromio(func, dst, addr, count);
}
EXPORT_SYMBOL(libra_sdio_memcpy_fromio);
int libra_sdio_writesb(struct sdio_func *func,
unsigned int addr, void *src, int count)
{
return sdio_writesb(func, addr, src, count);
}
EXPORT_SYMBOL(libra_sdio_writesb);
int libra_sdio_memcpy_toio(struct sdio_func *func,
unsigned int addr, void *src, int count)
{
return sdio_memcpy_toio(func, addr, src, count);
}
EXPORT_SYMBOL(libra_sdio_memcpy_toio);
int libra_detect_card_change(void)
{
if (libra_mmc_host) {
if (!strcmp(libra_mmc_host->class_dev.class->name, "mmc_host")
&& (libra_mmc_host_index == libra_mmc_host->index)) {
mmc_detect_change(libra_mmc_host, 0);
return 0;
}
}
printk(KERN_ERR "%s: Could not trigger card change\n", __func__);
return -EINVAL;
}
EXPORT_SYMBOL(libra_detect_card_change);
int libra_sdio_enable_polling(void)
{
if (libra_mmc_host) {
if (!strcmp(libra_mmc_host->class_dev.class->name, "mmc_host")
&& (libra_mmc_host_index == libra_mmc_host->index)) {
libra_mmc_host->caps |= MMC_CAP_NEEDS_POLL;
mmc_detect_change(libra_mmc_host, 0);
return 0;
}
}
printk(KERN_ERR "%s: Could not trigger SDIO scan\n", __func__);
return -1;
}
EXPORT_SYMBOL(libra_sdio_enable_polling);
void libra_sdio_set_clock(struct sdio_func *func, unsigned int clk_freq)
{
struct mmc_host *host = func->card->host;
host->ios.clock = clk_freq;
host->ops->set_ios(host, &host->ios);
}
EXPORT_SYMBOL(libra_sdio_set_clock);
/*
* API to get SDIO Device Card ID
*/
void libra_sdio_get_card_id(struct sdio_func *func, unsigned short *card_id)
{
if (card_id)
*card_id = libra_sdio_card_id;
}
EXPORT_SYMBOL(libra_sdio_get_card_id);
/*
* SDIO Probe
*/
static int libra_sdio_probe(struct sdio_func *func,
const struct sdio_device_id *sdio_dev_id)
{
libra_mmc_host = func->card->host;
libra_mmc_host_index = libra_mmc_host->index;
libra_sdio_func = func;
libra_sdio_card_id = sdio_dev_id->device;
printk(KERN_INFO "%s: success with block size of %d device_id=0x%x\n",
__func__,
func->cur_blksize,
sdio_dev_id->device);
/* Turn off SDIO polling from now on */
libra_mmc_host->caps &= ~MMC_CAP_NEEDS_POLL;
return 0;
}
static void libra_sdio_remove(struct sdio_func *func)
{
if (libra_notify_card_removal_hdlr)
libra_notify_card_removal_hdlr();
libra_sdio_func = NULL;
printk(KERN_INFO "%s : Module removed.\n", __func__);
}
#ifdef CONFIG_PM
static int libra_sdio_suspend(struct device *dev)
{
struct sdio_func *func = dev_to_sdio_func(dev);
int ret = 0;
ret = sdio_set_host_pm_flags(func, MMC_PM_KEEP_POWER);
if (ret) {
printk(KERN_ERR "%s: Error Host doesn't support the keep power capability\n" ,
__func__);
return ret;
}
if (libra_suspend_hldr) {
/* Disable SDIO IRQ when driver is being suspended */
libra_enable_sdio_irq(func, 0);
ret = libra_suspend_hldr(func);
if (ret) {
printk(KERN_ERR
"%s: Libra driver is not able to suspend\n" , __func__);
/* Error - Restore SDIO IRQ */
libra_enable_sdio_irq(func, 1);
return ret;
}
}
return sdio_set_host_pm_flags(func, MMC_PM_WAKE_SDIO_IRQ);
}
static int libra_sdio_resume(struct device *dev)
{
struct sdio_func *func = dev_to_sdio_func(dev);
if (libra_resume_hldr) {
libra_resume_hldr(func);
/* Restore SDIO IRQ */
libra_enable_sdio_irq(func, 1);
}
return 0;
}
#else
#define libra_sdio_suspend 0
#define libra_sdio_resume 0
#endif
static void libra_sdio_shutdown(struct device *dev)
{
if (libra_sdio_shutdown_hdlr) {
libra_sdio_shutdown_hdlr();
printk(KERN_INFO "%s : Notified shutdown event to Libra driver.\n",
__func__);
}
}
int libra_sdio_register_shutdown_hdlr(
shutdown_handler_t *libra_shutdown_hdlr)
{
libra_sdio_shutdown_hdlr = libra_shutdown_hdlr;
return 0;
}
EXPORT_SYMBOL(libra_sdio_register_shutdown_hdlr);
int libra_sdio_notify_card_removal(
notify_card_removal_t *libra_sdio_notify_card_removal_hdlr)
{
libra_notify_card_removal_hdlr = libra_sdio_notify_card_removal_hdlr;
return 0;
}
EXPORT_SYMBOL(libra_sdio_notify_card_removal);
static struct sdio_device_id libra_sdioid[] = {
{.class = 0, .vendor = LIBRA_MAN_ID, .device = LIBRA_REV_1_0_CARD_ID},
{.class = 0, .vendor = VOLANS_MAN_ID, .device = VOLANS_REV_2_0_CARD_ID},
{}
};
static const struct dev_pm_ops libra_sdio_pm_ops = {
.suspend = libra_sdio_suspend,
.resume = libra_sdio_resume,
};
static struct sdio_driver libra_sdiofn_driver = {
.name = "libra_sdiofn",
.id_table = libra_sdioid,
.probe = libra_sdio_probe,
.remove = libra_sdio_remove,
.drv.pm = &libra_sdio_pm_ops,
.drv.shutdown = libra_sdio_shutdown,
};
static int __init libra_sdioif_init(void)
{
libra_sdio_func = NULL;
libra_mmc_host = NULL;
libra_mmc_host_index = -1;
libra_suspend_hldr = NULL;
libra_resume_hldr = NULL;
libra_notify_card_removal_hdlr = NULL;
libra_sdio_shutdown_hdlr = NULL;
sdio_register_driver(&libra_sdiofn_driver);
printk(KERN_INFO "%s: Loaded Successfully\n", __func__);
return 0;
}
static void __exit libra_sdioif_exit(void)
{
unsigned int attempts = 0;
if (!libra_detect_card_change()) {
do {
++attempts;
msleep(500);
} while (libra_sdio_func != NULL && attempts < 3);
}
if (libra_sdio_func != NULL)
printk(KERN_ERR "%s: Card removal not detected\n", __func__);
sdio_unregister_driver(&libra_sdiofn_driver);
libra_sdio_func = NULL;
libra_mmc_host = NULL;
libra_mmc_host_index = -1;
printk(KERN_INFO "%s: Unloaded Successfully\n", __func__);
}
module_init(libra_sdioif_init);
module_exit(libra_sdioif_exit);
MODULE_LICENSE("GPL v2");
MODULE_VERSION("1.0");
MODULE_DESCRIPTION("WLAN SDIODriver");
| KlinkOnE/caf-port | drivers/net/wireless/libra/libra_sdioif.c | C | gpl-2.0 | 13,417 |
function test() {
return (function foo(){}).name === 'foo' &&
(function(){}).name === '';
}
if (!test())
throw new Error("Test failed");
| Debian/openjfx | modules/web/src/main/native/Source/JavaScriptCore/tests/es6/function_name_property_function_expressions.js | JavaScript | gpl-2.0 | 153 |
FD40.ready(function($) {
var jQuery = $;// Catalan
jQuery.timeago.settings.strings = {
prefixAgo: "fa",
prefixFromNow: "d'aqui a",
suffixAgo: null,
suffixFromNow: null,
seconds: "menys d'1 minut",
minute: "1 minut",
minutes: "uns %d minuts",
hour: "1 hora",
hours: "unes %d hores",
day: "1 dia",
days: "%d dies",
month: "aproximadament un mes",
months: "%d mesos",
year: "aproximadament un any",
years: "%d anys"
};
}); | BetterBetterBetter/WheresWalden | media/foundry/4.0/scripts/timeago/ca.js | JavaScript | gpl-2.0 | 450 |
/*
* Flash partitions described by the OF (or flattened) device tree
*
* Copyright (C) 2006 MontaVista Software Inc.
* Author: Vitaly Wool <vwool@ru.mvista.com>
*
* Revised to handle newer style flash binding by:
* Copyright (C) 2007 David Gibson, IBM Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/of.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
int __devinit of_mtd_parse_partitions(struct device *dev,
struct mtd_info *mtd,
struct device_node *node,
struct mtd_partition **pparts)
{
const char *partname;
struct device_node *pp;
int nr_parts, i;
/* First count the subnodes */
pp = NULL;
nr_parts = 0;
while ((pp = of_get_next_child(node, pp)))
nr_parts++;
if (nr_parts == 0)
return 0;
*pparts = kzalloc(nr_parts * sizeof(**pparts), GFP_KERNEL);
if (!*pparts)
return -ENOMEM;
pp = NULL;
i = 0;
while ((pp = of_get_next_child(node, pp))) {
const u32 *reg;
int len;
reg = of_get_property(pp, "reg", &len);
if (!reg || (len != 2 * sizeof(u32))) {
of_node_put(pp);
dev_err(dev, "Invalid 'reg' on %s\n", node->full_name);
kfree(*pparts);
*pparts = NULL;
return -EINVAL;
}
(*pparts)[i].offset = reg[0];
(*pparts)[i].size = reg[1];
partname = of_get_property(pp, "label", &len);
if (!partname)
partname = of_get_property(pp, "name", &len);
(*pparts)[i].name = (char *)partname;
if (of_get_property(pp, "read-only", &len))
(*pparts)[i].mask_flags = MTD_WRITEABLE;
i++;
}
return nr_parts;
}
EXPORT_SYMBOL(of_mtd_parse_partitions);
| jkoelndorfer/android-kernel-msm | drivers/mtd/ofpart.c | C | gpl-2.0 | 1,941 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="pt">
<head>
<!-- Generated by javadoc (version 1.7.0_11) on Fri Jan 25 09:33:25 BRST 2013 -->
<title>ThemeForm (Cyclos 3 Documentation)</title>
<meta name="date" content="2013-01-25">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ThemeForm (Cyclos 3 Documentation)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../nl/strohalm/cyclos/controls/customization/themes/SelectThemeAction.html" title="class in nl.strohalm.cyclos.controls.customization.themes"><span class="strong">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?nl/strohalm/cyclos/controls/customization/themes/ThemeForm.html" target="_top">Frames</a></li>
<li><a href="ThemeForm.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#fields_inherited_from_class_nl.strohalm.cyclos.controls.BaseBindingForm">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">nl.strohalm.cyclos.controls.customization.themes</div>
<h2 title="Class ThemeForm" class="title">Class ThemeForm</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.apache.struts.action.ActionForm</li>
<li>
<ul class="inheritance">
<li><a href="../../../../../../nl/strohalm/cyclos/controls/BaseBindingForm.html" title="class in nl.strohalm.cyclos.controls">nl.strohalm.cyclos.controls.BaseBindingForm</a></li>
<li>
<ul class="inheritance">
<li>nl.strohalm.cyclos.controls.customization.themes.ThemeForm</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable</dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">ThemeForm</span>
extends <a href="../../../../../../nl/strohalm/cyclos/controls/BaseBindingForm.html" title="class in nl.strohalm.cyclos.controls">BaseBindingForm</a></pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../serialized-form.html#nl.strohalm.cyclos.controls.customization.themes.ThemeForm">Serialized Form</a></dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="fields_inherited_from_class_nl.strohalm.cyclos.controls.BaseBindingForm">
<!-- -->
</a>
<h3>Fields inherited from class nl.strohalm.cyclos.controls.<a href="../../../../../../nl/strohalm/cyclos/controls/BaseBindingForm.html" title="class in nl.strohalm.cyclos.controls">BaseBindingForm</a></h3>
<code><a href="../../../../../../nl/strohalm/cyclos/controls/BaseBindingForm.html#values">values</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="fields_inherited_from_class_org.apache.struts.action.ActionForm">
<!-- -->
</a>
<h3>Fields inherited from class org.apache.struts.action.ActionForm</h3>
<code>multipartRequestHandler, servlet</code></li>
</ul>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../../nl/strohalm/cyclos/controls/customization/themes/ThemeForm.html#ThemeForm()">ThemeForm</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../../nl/strohalm/cyclos/controls/customization/themes/ThemeForm.html#getFilename()">getFilename</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.util.Map<java.lang.String,java.lang.Object></code></td>
<td class="colLast"><code><strong><a href="../../../../../../nl/strohalm/cyclos/controls/customization/themes/ThemeForm.html#getTheme()">getTheme</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.Object</code></td>
<td class="colLast"><code><strong><a href="../../../../../../nl/strohalm/cyclos/controls/customization/themes/ThemeForm.html#getTheme(java.lang.String)">getTheme</a></strong>(java.lang.String key)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../nl/strohalm/cyclos/controls/customization/themes/ThemeForm.html#setFilename(java.lang.String)">setFilename</a></strong>(java.lang.String filename)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../nl/strohalm/cyclos/controls/customization/themes/ThemeForm.html#setTheme(java.util.Map)">setTheme</a></strong>(java.util.Map<java.lang.String,java.lang.Object> map)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../nl/strohalm/cyclos/controls/customization/themes/ThemeForm.html#setTheme(java.lang.String, java.lang.Object)">setTheme</a></strong>(java.lang.String key,
java.lang.Object value)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_nl.strohalm.cyclos.controls.BaseBindingForm">
<!-- -->
</a>
<h3>Methods inherited from class nl.strohalm.cyclos.controls.<a href="../../../../../../nl/strohalm/cyclos/controls/BaseBindingForm.html" title="class in nl.strohalm.cyclos.controls">BaseBindingForm</a></h3>
<code><a href="../../../../../../nl/strohalm/cyclos/controls/BaseBindingForm.html#getValues()">getValues</a>, <a href="../../../../../../nl/strohalm/cyclos/controls/BaseBindingForm.html#setValues(java.util.Map)">setValues</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_org.apache.struts.action.ActionForm">
<!-- -->
</a>
<h3>Methods inherited from class org.apache.struts.action.ActionForm</h3>
<code>getMultipartRequestHandler, getServlet, getServletWrapper, reset, reset, setMultipartRequestHandler, setServlet, validate, validate</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="ThemeForm()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>ThemeForm</h4>
<pre>public ThemeForm()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getFilename()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getFilename</h4>
<pre>public java.lang.String getFilename()</pre>
</li>
</ul>
<a name="getTheme()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getTheme</h4>
<pre>public java.util.Map<java.lang.String,java.lang.Object> getTheme()</pre>
</li>
</ul>
<a name="getTheme(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getTheme</h4>
<pre>public java.lang.Object getTheme(java.lang.String key)</pre>
</li>
</ul>
<a name="setFilename(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setFilename</h4>
<pre>public void setFilename(java.lang.String filename)</pre>
</li>
</ul>
<a name="setTheme(java.util.Map)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setTheme</h4>
<pre>public void setTheme(java.util.Map<java.lang.String,java.lang.Object> map)</pre>
</li>
</ul>
<a name="setTheme(java.lang.String, java.lang.Object)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>setTheme</h4>
<pre>public void setTheme(java.lang.String key,
java.lang.Object value)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../nl/strohalm/cyclos/controls/customization/themes/SelectThemeAction.html" title="class in nl.strohalm.cyclos.controls.customization.themes"><span class="strong">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?nl/strohalm/cyclos/controls/customization/themes/ThemeForm.html" target="_top">Frames</a></li>
<li><a href="ThemeForm.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#fields_inherited_from_class_nl.strohalm.cyclos.controls.BaseBindingForm">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| robertoandrade/cyclos | docs/api/nl/strohalm/cyclos/controls/customization/themes/ThemeForm.html | HTML | gpl-2.0 | 13,674 |
/*
* JCE Editor 2.2.4
* @package JCE
* @url http://www.joomlacontenteditor.net
* @copyright Copyright (C) 2006 - 2012 Ryan Demmer. All rights reserved
* @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html
* @date 16 July 2012
* 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.
*
* NOTE : Javascript files have been compressed for speed and can be uncompressed using http://jsbeautifier.org/
*/
tinyMCEPopup.requireLangPack();var ColorPicker={settings:{},init:function(){var self=this,ed=tinyMCEPopup.editor,color=tinyMCEPopup.getWindowArg('input_color')||'#FFFFFF';$('#tmp_color').val(color).colorpicker($.extend(this.settings,{dialog:false,insert:function(){return ColorPicker.insert();},close:function(){return tinyMCEPopup.close();}}));$('button#insert').button({icons:{primary:'ui-icon-check'}});$('#jce').css('display','block');},insert:function(){var color=$("#colorpicker_color").val(),f=tinyMCEPopup.getWindowArg('func');tinyMCEPopup.restoreSelection();if(f)
f(color);tinyMCEPopup.close();}};tinyMCEPopup.onInit.add(ColorPicker.init,ColorPicker); | ArtificialEX/jwexport | components/com_jce/editor/tiny_mce/themes/advanced/js/colorpicker.js | JavaScript | gpl-2.0 | 1,641 |
<?php
namespace Drupal\webform;
use Drupal\Core\Archiver\ArchiveTar;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\SubformState;
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\webform\Entity\WebformSubmission;
use Drupal\webform\Plugin\WebformElementManagerInterface;
use Drupal\webform\Plugin\WebformExporterManagerInterface;
/**
* Webform submission exporter.
*/
class WebformSubmissionExporter implements WebformSubmissionExporterInterface {
use StringTranslationTrait;
/**
* The configuration object factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* File system service.
*
* @var \Drupal\Core\File\FileSystemInterface
*/
protected $fileSystem;
/**
* Webform submission storage.
*
* @var \Drupal\webform\WebformSubmissionStorageInterface
*/
protected $entityStorage;
/**
* The stream wrapper manager.
*
* @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface
*/
protected $streamWrapperManager;
/**
* Webform element manager.
*
* @var \Drupal\webform\Plugin\WebformElementManagerInterface
*/
protected $elementManager;
/**
* Results exporter manager.
*
* @var \Drupal\webform\Plugin\WebformExporterManagerInterface
*/
protected $exporterManager;
/**
* The webform.
*
* @var \Drupal\webform\WebformInterface
*/
protected $webform;
/**
* The source entity.
*
* @var \Drupal\Core\Entity\EntityInterface
*/
protected $sourceEntity;
/**
* The results exporter.
*
* @var \Drupal\webform\Plugin\WebformExporterInterface
*/
protected $exporter;
/**
* Default export options.
*
* @var array
*/
protected $defaultOptions;
/**
* Webform element types.
*
* @var array
*/
protected $elementTypes;
/**
* Constructs a WebformSubmissionExporter object.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The configuration object factory.
* @param \Drupal\Core\File\FileSystemInterface $file_system
* File system service.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager
* The stream wrapper manager.
* @param \Drupal\webform\Plugin\WebformElementManagerInterface $element_manager
* The webform element manager.
* @param \Drupal\webform\Plugin\WebformExporterManagerInterface $exporter_manager
* The results exporter manager.
*/
public function __construct(ConfigFactoryInterface $config_factory, FileSystemInterface $file_system, EntityTypeManagerInterface $entity_type_manager, StreamWrapperManagerInterface $stream_wrapper_manager, WebformElementManagerInterface $element_manager, WebformExporterManagerInterface $exporter_manager) {
$this->configFactory = $config_factory;
$this->fileSystem = $file_system;
$this->entityStorage = $entity_type_manager->getStorage('webform_submission');
$this->streamWrapperManager = $stream_wrapper_manager;
$this->elementManager = $element_manager;
$this->exporterManager = $exporter_manager;
}
/**
* {@inheritdoc}
*/
public function setWebform(WebformInterface $webform = NULL) {
$this->webform = $webform;
$this->defaultOptions = NULL;
$this->elementTypes = NULL;
}
/**
* {@inheritdoc}
*/
public function getWebform() {
return $this->webform;
}
/**
* {@inheritdoc}
*/
public function setSourceEntity(EntityInterface $entity = NULL) {
$this->sourceEntity = $entity;
}
/**
* {@inheritdoc}
*/
public function getSourceEntity() {
return $this->sourceEntity;
}
/**
* {@inheritdoc}
*/
public function getWebformOptions() {
$name = $this->getWebformOptionsName();
return $this->getWebform()->getState($name, []);
}
/**
* {@inheritdoc}
*/
public function setWebformOptions(array $options = []) {
$name = $this->getWebformOptionsName();
$this->getWebform()->setState($name, $options);
}
/**
* {@inheritdoc}
*/
public function deleteWebformOptions() {
$name = $this->getWebformOptionsName();
$this->getWebform()->deleteState($name);
}
/**
* Get options name for current webform and source entity.
*
* @return string
* Settings name as 'webform.export.{entity_type}.{entity_id}'.
*/
protected function getWebformOptionsName() {
if ($entity = $this->getSourceEntity()) {
return 'results.export.' . $entity->getEntityTypeId() . '.' . $entity->id();
}
else {
return 'results.export';
}
}
/**
* {@inheritdoc}
*/
public function setExporter(array $export_options = []) {
$export_options += $this->getDefaultExportOptions();
$export_options['webform'] = $this->getWebform();
$export_options['source_entity'] = $this->getSourceEntity();
$this->exporter = $this->exporterManager->createInstance($export_options['exporter'], $export_options);
return $this->exporter;
}
/**
* {@inheritdoc}
*/
public function getExporter() {
return $this->exporter;
}
/**
* {@inheritdoc}
*/
public function getExportOptions() {
return $this->getExporter()->getConfiguration();
}
/****************************************************************************/
// Default options and webform.
/****************************************************************************/
/**
* {@inheritdoc}
*/
public function getDefaultExportOptions() {
if (isset($this->defaultOptions)) {
return $this->defaultOptions;
}
$this->defaultOptions = [
'exporter' => 'delimited',
'delimiter' => ',',
'multiple_delimiter' => ';',
'excel' => FALSE,
'file_name' => 'submission-[webform_submission:serial]',
'header_format' => 'label',
'header_prefix' => TRUE,
'header_prefix_label_delimiter' => ': ',
'header_prefix_key_delimiter' => '__',
'excluded_columns' => [
'uuid' => 'uuid',
'token' => 'token',
'webform_id' => 'webform_id',
],
'entity_type' => '',
'entity_id' => '',
'range_type' => 'all',
'range_latest' => '',
'range_start' => '',
'range_end' => '',
'state' => 'all',
'sticky' => '',
'download' => TRUE,
'files' => FALSE,
];
// Append element handler default options.
$element_types = $this->getWebformElementTypes();
$element_handlers = $this->elementManager->getInstances();
foreach ($element_handlers as $element_type => $element_handler) {
if (empty($element_types) || isset($element_types[$element_type])) {
$this->defaultOptions += $element_handler->getExportDefaultOptions();
}
}
return $this->defaultOptions;
}
/**
* {@inheritdoc}
*/
public function buildExportOptionsForm(array &$form, FormStateInterface $form_state, array $export_options = []) {
$export_options += $this->getDefaultExportOptions();
$this->setExporter($export_options);
$webform = $this->getWebform();
// Get exporter and build #states.
$exporter_plugins = $this->exporterManager->getInstances($export_options);
$states_archive = ['invisible' => []];
$states_options = ['invisible' => []];
foreach ($exporter_plugins as $plugin_id => $exporter_plugin) {
if ($exporter_plugin->isArchive()) {
if ($states_archive['invisible']) {
$states_archive['invisible'][] = 'or';
}
$states_archive['invisible'][] = [':input[name="exporter"]' => ['value' => $plugin_id]];
}
if (!$exporter_plugin->hasOptions()) {
if ($states_options['invisible']) {
$states_options['invisible'][] = 'or';
}
$states_options['invisible'][] = [':input[name="exporter"]' => ['value' => $plugin_id]];
}
}
$form['export']['format'] = [
'#type' => 'details',
'#title' => $this->t('Format options'),
'#open' => TRUE,
];
$form['export']['format']['exporter'] = [
'#type' => 'select',
'#title' => $this->t('Export format'),
'#options' => $this->exporterManager->getOptions(),
'#default_value' => $export_options['exporter'],
// Below .js-webform-exporter is used for exporter configuration form
// #states.
// @see \Drupal\webform\Plugin\WebformExporterBase::buildConfigurationForm
'#attributes' => ['class' => ['js-webform-exporter']],
];
foreach ($exporter_plugins as $plugin_id => $exporter) {
$subform_state = SubformState::createForSubform($form['export']['format'], $form, $form_state);
$form['export']['format'] = $exporter->buildConfigurationForm($form['export']['format'], $subform_state);
}
// Element.
$form['export']['element'] = [
'#type' => 'details',
'#title' => $this->t('Element options'),
'#open' => TRUE,
'#states' => $states_options,
];
$form['export']['element']['multiple_delimiter'] = [
'#type' => 'select',
'#title' => $this->t('Element multiple values delimiter'),
'#description' => $this->t('This is the delimiter when an element has multiple values.'),
'#required' => TRUE,
'#options' => [
';' => $this->t('Semicolon (;)'),
',' => $this->t('Comma (,)'),
'|' => $this->t('Pipe (|)'),
'.' => $this->t('Period (.)'),
' ' => $this->t('Space ()'),
],
'#default_value' => $export_options['multiple_delimiter'],
];
// Header.
$form['export']['header'] = [
'#type' => 'details',
'#title' => $this->t('Header options'),
'#open' => TRUE,
'#states' => $states_options,
];
$form['export']['header']['header_format'] = [
'#type' => 'radios',
'#title' => $this->t('Column header format'),
'#description' => $this->t('Choose whether to show the element label or element key in each column header.'),
'#required' => TRUE,
'#options' => [
'label' => $this->t('Element titles (label)'),
'key' => $this->t('Element keys (key)'),
],
'#default_value' => $export_options['header_format'],
];
$form['export']['header']['header_prefix'] = [
'#type' => 'checkbox',
'#title' => $this->t("Include an element's title with all sub elements and values in each column header."),
'#return_value' => TRUE,
'#default_value' => $export_options['header_prefix'],
];
$form['export']['header']['header_prefix_label_delimiter'] = [
'#type' => 'textfield',
'#title' => $this->t('Column header label delimiter'),
'#required' => TRUE,
'#default_value' => $export_options['header_prefix_label_delimiter'],
];
$form['export']['header']['header_prefix_key_delimiter'] = [
'#type' => 'textfield',
'#title' => $this->t('Column header key delimiter'),
'#required' => TRUE,
'#default_value' => $export_options['header_prefix_key_delimiter'],
];
if ($webform) {
$form['export']['header']['header_prefix_label_delimiter']['#states'] = [
'visible' => [
':input[name="header_prefix"]' => ['checked' => TRUE],
':input[name="header_format"]' => ['value' => 'label'],
],
];
$form['export']['header']['header_prefix_key_delimiter']['#states'] = [
'visible' => [
':input[name="header_prefix"]' => ['checked' => TRUE],
':input[name="header_format"]' => ['value' => 'key'],
],
];
}
// Build element specific export webforms.
// Grouping everything in $form['export']['elements'] so that element handlers can
// assign #weight to its export options webform.
$form['export']['elements'] = [
'#type' => 'container',
'#attributes' => ['class' => ['form-item']],
'#states' => $states_options,
];
$element_types = $this->getWebformElementTypes();
$element_handlers = $this->elementManager->getInstances();
foreach ($element_handlers as $element_type => $element_handler) {
if (empty($element_types) || isset($element_types[$element_type])) {
$subform_state = SubformState::createForSubform($form['export']['elements'], $form, $form_state);
$element_handler->buildExportOptionsForm($form['export']['elements'], $subform_state, $export_options);
}
}
// All the remain options are only applicable to a webform's export.
// @see Drupal\webform\Form\WebformResultsExportForm
if (!$webform) {
return;
}
// Elements.
$form['export']['columns'] = [
'#type' => 'details',
'#title' => $this->t('Column options'),
'#description' => $this->t('The selected columns will be included in the export.'),
'#states' => $states_options,
];
$form['export']['columns']['excluded_columns'] = [
'#type' => 'webform_excluded_columns',
'#webform_id' => $webform->id(),
'#default_value' => $export_options['excluded_columns'],
];
// Download options.
$form['export']['download'] = [
'#type' => 'details',
'#title' => $this->t('Download options'),
'#open' => TRUE,
];
$form['export']['download']['download'] = [
'#type' => 'checkbox',
'#title' => $this->t('Download export file'),
'#description' => $this->t('If checked, the export file will be automatically download to your local machine. If unchecked, the export file will be displayed as plain text within your browser.'),
'#return_value' => TRUE,
'#default_value' => $export_options['download'],
'#access' => !$this->requiresBatch(),
'#states' => $states_archive,
];
$form['export']['download']['files'] = [
'#type' => 'checkbox',
'#title' => $this->t('Download uploaded files'),
'#description' => $this->t('If checked, the exported file and any submission file uploads will be download in a gzipped tar file.'),
'#return_value' => TRUE,
'#default_value' => ($webform->hasManagedFile()) ? $export_options['files'] : 0,
'#access' => $webform->hasManagedFile(),
'#states' => [
'invisible' => [
':input[name="download"]' => ['checked' => FALSE],
],
],
];
$source_entity = $this->getSourceEntity();
if (!$source_entity) {
$entity_types = $this->entityStorage->getSourceEntityTypes($webform);
if ($entity_types) {
$form['export']['download']['submitted'] = [
'#type' => 'item',
'#input' => FALSE,
'#title' => $this->t('Submitted to'),
'#description' => $this->t('Select the entity type and then enter the entity id.'),
'#field_prefix' => '<div class="container-inline">',
'#field_suffix' => '</div>',
];
$form['export']['download']['submitted']['entity_type'] = [
'#type' => 'select',
'#title' => $this->t('Entity type'),
'#title_display' => 'Invisible',
'#options' => ['' => $this->t('All')] + $entity_types,
'#default_value' => $export_options['entity_type'],
];
$form['export']['download']['submitted']['entity_id'] = [
'#type' => 'number',
'#title' => $this->t('Entity id'),
'#title_display' => 'Invisible',
'#min' => 1,
'#size' => 10,
'#default_value' => $export_options['entity_id'],
'#states' => [
'invisible' => [
':input[name="entity_type"]' => ['value' => ''],
],
],
];
}
}
$form['export']['download']['range_type'] = [
'#type' => 'select',
'#title' => $this->t('Limit to'),
'#options' => [
'all' => $this->t('All'),
'latest' => $this->t('Latest'),
'serial' => $this->t('Submission number'),
'sid' => $this->t('Submission ID'),
'date' => $this->t('Date'),
],
'#default_value' => $export_options['range_type'],
];
$form['export']['download']['latest'] = [
'#type' => 'container',
'#attributes' => ['class' => ['container-inline']],
'#states' => [
'visible' => [
':input[name="range_type"]' => ['value' => 'latest'],
],
],
'range_latest' => [
'#type' => 'number',
'#title' => $this->t('Number of submissions'),
'#min' => 1,
'#default_value' => $export_options['range_latest'],
],
];
$ranges = [
'serial' => ['#type' => 'number'],
'sid' => ['#type' => 'number'],
'date' => ['#type' => 'date'],
];
foreach ($ranges as $key => $range_element) {
$form['export']['download'][$key] = [
'#type' => 'container',
'#attributes' => ['class' => ['container-inline']],
'#tree' => TRUE,
'#states' => [
'visible' => [
':input[name="range_type"]' => ['value' => $key],
],
],
];
$form['export']['download'][$key]['range_start'] = $range_element + [
'#title' => $this->t('From'),
'#parents' => [$key, 'range_start'],
'#default_value' => $export_options['range_start'],
];
$form['export']['download'][$key]['range_end'] = $range_element + [
'#title' => $this->t('To'),
'#parents' => [$key, 'range_end'],
'#default_value' => $export_options['range_end'],
];
}
$form['export']['download']['sticky'] = [
'#type' => 'checkbox',
'#title' => $this->t('Starred/flagged submissions'),
'#description' => $this->t('If checked, only starred/flagged submissions will be downloaded. If unchecked, all submissions will downloaded.'),
'#return_value' => TRUE,
'#default_value' => $export_options['sticky'],
];
// If drafts are allowed, provide options to filter download based on
// submission state.
$form['export']['download']['state'] = [
'#type' => 'radios',
'#title' => $this->t('Submission state'),
'#default_value' => $export_options['state'],
'#options' => [
'all' => $this->t('Completed and draft submissions'),
'completed' => $this->t('Completed submissions only'),
'draft' => $this->t('Drafts only'),
],
'#access' => ($webform->getSetting('draft') != WebformInterface::DRAFT_NONE),
];
}
/**
* {@inheritdoc}
*/
public function getValuesFromInput(array $values) {
if (isset($values['range_type'])) {
$range_type = $values['range_type'];
$values['range_type'] = $range_type;
if (isset($values[$range_type])) {
$values += $values[$range_type];
}
}
// Make sure only support options are returned.
$values = array_intersect_key($values, $this->getDefaultExportOptions());
return $values;
}
/****************************************************************************/
// Generate and write.
/****************************************************************************/
/**
* {@inheritdoc}
*/
public function generate() {
$entity_ids = $this->getQuery()->execute();
$webform_submissions = WebformSubmission::loadMultiple($entity_ids);
$this->writeHeader();
$this->writeRecords($webform_submissions);
$this->writeFooter();
}
/**
* {@inheritdoc}
*/
public function writeHeader() {
// If building a new archive make sure to delete the exist archive.
if ($this->isArchive()) {
@unlink($this->getArchiveFilePath());
}
$this->getExporter()->createExport();
$this->getExporter()->writeHeader();
$this->getExporter()->closeExport();
}
/**
* {@inheritdoc}
*/
public function writeRecords(array $webform_submissions) {
$export_options = $this->getExportOptions();
$webform = $this->getWebform();
$is_archive = ($this->isArchive() && $export_options['files']);
$files_directories = [];
if ($is_archive) {
$archiver = new ArchiveTar($this->getArchiveFilePath(), 'gz');
$stream_wrappers = array_keys($this->streamWrapperManager->getNames(StreamWrapperInterface::WRITE_VISIBLE));
foreach ($stream_wrappers as $stream_wrapper) {
$files_directory = $this->fileSystem->realpath($stream_wrapper . '://webform/' . $webform->id());
$files_directories[] = $files_directory;
}
}
$this->getExporter()->openExport();
foreach ($webform_submissions as $webform_submission) {
if ($is_archive) {
foreach ($files_directories as $files_directory) {
$submission_directory = $files_directory . '/' . $webform_submission->id();
if (file_exists($submission_directory)) {
$file_name = $this->getSubmissionBaseName($webform_submission);
$archiver->addModify($submission_directory, $file_name, $submission_directory);
}
}
}
$this->getExporter()->writeSubmission($webform_submission);
}
$this->getExporter()->closeExport();
}
/**
* {@inheritdoc}
*/
public function writeFooter() {
$this->getExporter()->openExport();
$this->getExporter()->writeFooter();
$this->getExporter()->closeExport();
}
/**
* {@inheritdoc}
*/
public function writeExportToArchive() {
$export_file_path = $this->getExportFilePath();
if (file_exists($export_file_path)) {
$archive_file_path = $this->getArchiveFilePath();
$archiver = new ArchiveTar($archive_file_path, 'gz');
$archiver->addModify($export_file_path, $this->getBaseFileName(), $this->getFileTempDirectory());
@unlink($export_file_path);
}
}
/**
* {@inheritdoc}
*/
public function getQuery() {
$export_options = $this->getExportOptions();
$webform = $this->getWebform();
$source_entity = $this->getSourceEntity();
$query = $this->entityStorage->getQuery()->condition('webform_id', $webform->id());
// Filter by source entity or submitted to.
if ($source_entity) {
$query->condition('entity_type', $source_entity->getEntityTypeId());
$query->condition('entity_id', $source_entity->id());
}
elseif ($export_options['entity_type']) {
$query->condition('entity_type', $export_options['entity_type']);
if ($export_options['entity_id']) {
$query->condition('entity_id', $export_options['entity_id']);
}
}
// Filter by sid or date range.
switch ($export_options['range_type']) {
case 'serial':
if ($export_options['range_start']) {
$query->condition('serial', $export_options['range_start'], '>=');
}
if ($export_options['range_end']) {
$query->condition('serial', $export_options['range_end'], '<=');
}
break;
case 'sid':
if ($export_options['range_start']) {
$query->condition('sid', $export_options['range_start'], '>=');
}
if ($export_options['range_end']) {
$query->condition('sid', $export_options['range_end'], '<=');
}
break;
case 'date':
if ($export_options['range_start']) {
$query->condition('created', strtotime($export_options['range_start']), '>=');
}
if ($export_options['range_end']) {
$query->condition('created', strtotime('+1 day', strtotime($export_options['range_end'])), '<');
}
break;
}
// Filter by (completion) state.
switch ($export_options['state']) {
case 'draft':
$query->condition('in_draft', 1);
break;
case 'completed':
$query->condition('in_draft', 0);
break;
}
// Filter by sticky.
if ($export_options['sticky']) {
$query->condition('sticky', 1);
}
// Filter by latest.
if ($export_options['range_type'] == 'latest' && $export_options['range_latest']) {
// Clone the query and use it to get latest sid starting sid.
$latest_query = clone $query;
$latest_query->sort('sid', 'DESC');
$latest_query->range(0, (int) $export_options['range_latest']);
if ($latest_query_entity_ids = $latest_query->execute()) {
$query->condition('sid', end($latest_query_entity_ids), '>=');
}
}
// Sort by sid with the oldest one first.
$query->sort('sid', 'ASC');
return $query;
}
/**
* Get element types from a webform.
*
* @return array
* An array of element types from a webform.
*/
protected function getWebformElementTypes() {
if (isset($this->elementTypes)) {
return $this->elementTypes;
}
// If the webform is not set which only occurs on the admin settings webform,
// return an empty array.
if (!isset($this->webform)) {
return [];
}
$this->elementTypes = [];
$elements = $this->webform->getElementsDecodedAndFlattened();
// Always include 'entity_autocomplete' export settings which is used to
// expand a webform submission's entity references.
$this->elementTypes['entity_autocomplete'] = 'entity_autocomplete';
foreach ($elements as $element) {
if (isset($element['#type'])) {
$type = $this->elementManager->getElementPluginId($element);
$this->elementTypes[$type] = $type;
}
}
return $this->elementTypes;
}
/****************************************************************************/
// Summary and download.
/****************************************************************************/
/**
* {@inheritdoc}
*/
public function getTotal() {
return $this->getQuery()->count()->execute();
}
/**
* {@inheritdoc}
*/
public function getBatchLimit() {
return $this->configFactory->get('webform.settings')->get('batch.default_batch_export_size') ?: 500;
}
/**
* {@inheritdoc}
*/
public function requiresBatch() {
return ($this->getTotal() > $this->getBatchLimit()) ? TRUE : FALSE;
}
/**
* {@inheritdoc}
*/
public function getFileTempDirectory() {
return file_directory_temp();
}
/**
* {@inheritdoc}
*/
public function getSubmissionBaseName(WebformSubmissionInterface $webform_submission) {
return $this->getExporter()->getSubmissionBaseName($webform_submission);
}
/**
* {@inheritdoc}
*/
protected function getBaseFileName() {
return $this->getExporter()->getBaseFileName();
}
/**
* {@inheritdoc}
*/
public function getExportFilePath() {
return $this->getExporter()->getExportFilePath();
}
/**
* {@inheritdoc}
*/
public function getExportFileName() {
return $this->getExporter()->getExportFileName();
}
/**
* {@inheritdoc}
*/
public function getArchiveFilePath() {
return $this->getExporter()->getArchiveFilePath();
}
/**
* {@inheritdoc}
*/
public function getArchiveFileName() {
return $this->getExporter()->getArchiveFileName();
}
/**
* {@inheritdoc}
*/
public function isArchive() {
if ($this->getExporter()->isArchive()) {
return TRUE;
}
else {
$export_options = $this->getExportOptions();
return ($export_options['download'] && $export_options['files']);
}
}
/**
* {@inheritdoc}
*/
public function isBatch() {
return ($this->isArchive() || ($this->getTotal() >= $this->getBatchLimit()));
}
}
| msbtterswrth/mdspca-fosters | modules/webform/src/WebformSubmissionExporter.php | PHP | gpl-2.0 | 27,760 |
.size 8000
.text@48
inc a
ldff(45), a
jp lstatint
.text@100
jp lbegin
.data@143
c0
.text@150
lbegin:
ld a, 00
ldff(ff), a
ld a, 30
ldff(00), a
ld a, 01
ldff(4d), a
stop, 00
ld a, ff
ldff(45), a
ld b, 03
call lwaitly_b
ld c, 41
lbegin_waitm0:
ldff a, (c)
and a, b
jrnz lbegin_waitm0
ld a, 80
ldff(68), a
ld a, ff
ld c, 69
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
xor a, a
ldff(c), a
ldff(c), a
ld a, 40
ldff(41), a
ld a, 02
ldff(ff), a
ei
ld a, b
inc a
inc a
ldff(45), a
ld c, 0f
.text@1000
lstatint:
nop
.text@10d2
ld a, ff
ldff(45), a
ldff a, (c)
and a, b
jp lprint_a
.text@7000
lprint_a:
push af
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
pop af
ld(9800), a
ld bc, 7a00
ld hl, 8000
ld d, a0
lprint_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lprint_copytiles
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
lprint_limbo:
jr lprint_limbo
.text@7400
lwaitly_b:
ld c, 44
lwaitly_b_loop:
ldff a, (c)
cmp a, b
jrnz lwaitly_b_loop
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
| bentley/gambatte | testrunner/hwtests/lycEnable/ff45_disable_ds_1_out1.asm | Assembly | gpl-2.0 | 1,715 |
/* $NoKeywords:$ */
/**
* @file
*
* Config FCH HD Audio Controller
*
*
*
* @xrefitem bom "File Content Label" "Release Content"
* @e project: AGESA
* @e sub-project: FCH
* @e \$Revision: 63425 $ @e \$Date: 2011-12-22 11:24:10 -0600 (Thu, 22 Dec 2011) $
*
*/
/*
*****************************************************************************
*
* Copyright 2008 - 2012 ADVANCED MICRO DEVICES, INC. All Rights Reserved.
*
* AMD is granting you permission to use this software (the Materials)
* pursuant to the terms and conditions of your Software License Agreement
* with AMD. This header does *NOT* give you permission to use the Materials
* or any rights under AMD's intellectual property. Your use of any portion
* of these Materials shall constitute your acceptance of those terms and
* conditions. If you do not agree to the terms and conditions of the Software
* License Agreement, please do not use any portion of these Materials.
*
* CONFIDENTIALITY: The Materials and all other information, identified as
* confidential and provided to you by AMD shall be kept confidential in
* accordance with the terms and conditions of the Software License Agreement.
*
* LIMITATION OF LIABILITY: THE MATERIALS AND ANY OTHER RELATED INFORMATION
* PROVIDED TO YOU BY AMD ARE PROVIDED "AS IS" WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTY OF ANY KIND, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
* MERCHANTABILITY, NONINFRINGEMENT, TITLE, FITNESS FOR ANY PARTICULAR PURPOSE,
* OR WARRANTIES ARISING FROM CONDUCT, COURSE OF DEALING, OR USAGE OF TRADE.
* IN NO EVENT SHALL AMD OR ITS LICENSORS BE LIABLE FOR ANY DAMAGES WHATSOEVER
* (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, BUSINESS
* INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF AMD'S NEGLIGENCE,
* GROSS NEGLIGENCE, THE USE OF OR INABILITY TO USE THE MATERIALS OR ANY OTHER
* RELATED INFORMATION PROVIDED TO YOU BY AMD, EVEN IF AMD HAS BEEN ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGES. BECAUSE SOME JURISDICTIONS PROHIBIT THE
* EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES,
* THE ABOVE LIMITATION MAY NOT APPLY TO YOU.
*
* AMD does not assume any responsibility for any errors which may appear in
* the Materials or any other related information provided to you by AMD, or
* result from use of the Materials or any related information.
*
* You agree that you will not reverse engineer or decompile the Materials.
*
* NO SUPPORT OBLIGATION: AMD is not obligated to furnish, support, or make any
* further information, software, technical information, know-how, or show-how
* available to you. Additionally, AMD retains the right to modify the
* Materials at any time, without notice, and is not obligated to provide such
* modified Materials to you.
*
* U.S. GOVERNMENT RESTRICTED RIGHTS: The Materials are provided with
* "RESTRICTED RIGHTS." Use, duplication, or disclosure by the Government is
* subject to the restrictions as set forth in FAR 52.227-14 and
* DFAR252.227-7013, et seq., or its successor. Use of the Materials by the
* Government constitutes acknowledgement of AMD's proprietary rights in them.
*
* EXPORT ASSURANCE: You agree and certify that neither the Materials, nor any
* direct product thereof will be exported directly or indirectly, into any
* country prohibited by the United States Export Administration Act and the
* regulations thereunder, without the required authorization from the U.S.
* government nor will be used for any purpose prohibited by the same.
****************************************************************************
*/
#include "FchPlatform.h"
#define FILECODE (0xB003)
//
// Declaration of local functions
//
VOID
ConfigureAzaliaPinCmd (
IN FCH_DATA_BLOCK *FchDataPtr,
IN UINT32 BAR0,
IN UINT8 ChannelNum
);
VOID
ConfigureAzaliaSetConfigD4Dword (
IN CODEC_ENTRY *TempAzaliaCodecEntryPtr,
IN UINT32 ChannelNumDword,
IN UINT32 BAR0,
IN AMD_CONFIG_PARAMS *StdHeader
);
/**
* FchInitMidAzalia - Config Azalia controller after PCI
* emulation
*
*
*
* @param[in] FchDataPtr Fch configuration structure pointer.
*
*/
VOID
FchInitMidAzalia (
IN VOID *FchDataPtr
)
{
UINT8 Index;
BOOLEAN EnableAzalia;
UINT32 PinRouting;
UINT8 ChannelNum;
UINT8 AzaliaTempVariableByte;
UINT16 AzaliaTempVariableWord;
UINT32 BAR0;
FCH_DATA_BLOCK *LocalCfgPtr;
AMD_CONFIG_PARAMS *StdHeader;
LocalCfgPtr = (FCH_DATA_BLOCK *) FchDataPtr;
StdHeader = LocalCfgPtr->StdHeader;
EnableAzalia = FALSE;
ChannelNum = 0;
AzaliaTempVariableByte = 0;
AzaliaTempVariableWord = 0;
BAR0 = 0;
if ( LocalCfgPtr->Azalia.AzaliaEnable == AzDisable) {
return;
} else {
RwPci ((((0x14<<3)+2) << 16) + 0x04, AccessWidth8, (UINT32)~BIT1, (UINT32)BIT1, StdHeader);
if ( LocalCfgPtr->Azalia.AzaliaSsid != 0 ) {
RwPci ((((0x14<<3)+2) << 16) + 0x2C, AccessWidth32, 0x00, LocalCfgPtr->Azalia.AzaliaSsid, StdHeader);
}
ReadPci ((((0x14<<3)+2) << 16) + 0x10, AccessWidth32, &BAR0, StdHeader);
if ( BAR0 != 0 ) {
if ( BAR0 != 0xFFFFFFFF ) {
BAR0 &= ~(0x03FFF);
EnableAzalia = TRUE;
}
}
}
if ( EnableAzalia ) {
//
// Get SDIN Configuration
//
if ( LocalCfgPtr->Azalia.AzaliaConfig.AzaliaSdin0 == 2 ) {
RwMem (ACPI_MMIO_BASE + GPIO_BASE + FCH_GPIO_REG167, AccessWidth8, 0, 0x3E);
RwMem (ACPI_MMIO_BASE + IOMUX_BASE + FCH_GPIO_REG167, AccessWidth8, 0, 0x00);
} else {
RwMem (ACPI_MMIO_BASE + GPIO_BASE + FCH_GPIO_REG167, AccessWidth8, 0, 0x0);
RwMem (ACPI_MMIO_BASE + IOMUX_BASE + FCH_GPIO_REG167, AccessWidth8, 0, 0x01);
}
if ( LocalCfgPtr->Azalia.AzaliaConfig.AzaliaSdin1 == 2 ) {
RwMem (ACPI_MMIO_BASE + GPIO_BASE + FCH_GPIO_REG168, AccessWidth8, 0, 0x3E);
RwMem (ACPI_MMIO_BASE + IOMUX_BASE + FCH_GPIO_REG168, AccessWidth8, 0, 0x00);
} else {
RwMem (ACPI_MMIO_BASE + GPIO_BASE + FCH_GPIO_REG168, AccessWidth8, 0, 0x0);
RwMem (ACPI_MMIO_BASE + IOMUX_BASE + FCH_GPIO_REG168, AccessWidth8, 0, 0x01);
}
if ( LocalCfgPtr->Azalia.AzaliaConfig.AzaliaSdin2 == 2 ) {
RwMem (ACPI_MMIO_BASE + GPIO_BASE + FCH_GPIO_REG169, AccessWidth8, 0, 0x3E);
RwMem (ACPI_MMIO_BASE + IOMUX_BASE + FCH_GPIO_REG169, AccessWidth8, 0, 0x00);
} else {
RwMem (ACPI_MMIO_BASE + GPIO_BASE + FCH_GPIO_REG169, AccessWidth8, 0, 0x0);
RwMem (ACPI_MMIO_BASE + IOMUX_BASE + FCH_GPIO_REG169, AccessWidth8, 0, 0x01);
}
if ( LocalCfgPtr->Azalia.AzaliaConfig.AzaliaSdin3 == 2 ) {
RwMem (ACPI_MMIO_BASE + GPIO_BASE + FCH_GPIO_REG170, AccessWidth8, 0, 0x3E);
RwMem (ACPI_MMIO_BASE + IOMUX_BASE + FCH_GPIO_REG170, AccessWidth8, 0, 0x00);
} else {
RwMem (ACPI_MMIO_BASE + GPIO_BASE + FCH_GPIO_REG170, AccessWidth8, 0, 0x0);
RwMem (ACPI_MMIO_BASE + IOMUX_BASE + FCH_GPIO_REG170, AccessWidth8, 0, 0x01);
}
Index = 11;
do {
ReadMem ( BAR0 + 0x08, AccessWidth8, &AzaliaTempVariableByte);
AzaliaTempVariableByte |= BIT0;
WriteMem (BAR0 + 0x08, AccessWidth8, &AzaliaTempVariableByte);
FchStall (1000, StdHeader);
ReadMem (BAR0 + 0x08, AccessWidth8, &AzaliaTempVariableByte);
Index--;
} while ((! (AzaliaTempVariableByte & BIT0)) && (Index > 0) );
if ( Index == 0 ) {
return;
}
FchStall (1000, StdHeader);
ReadMem ( BAR0 + 0x0E, AccessWidth16, &AzaliaTempVariableWord);
if ( AzaliaTempVariableWord & 0x0F ) {
//
//at least one azalia codec found
//
//PinRouting = LocalCfgPtr->Azalia.AZALIA_CONFIG.AzaliaSdinPin;
//new structure need make up PinRouting
//need adjust later!!!
//
PinRouting = 0;
PinRouting = (UINT32 )LocalCfgPtr->Azalia.AzaliaConfig.AzaliaSdin3;
PinRouting <<= 8;
PinRouting |= (UINT32 )LocalCfgPtr->Azalia.AzaliaConfig.AzaliaSdin2;
PinRouting <<= 8;
PinRouting |= (UINT32 )LocalCfgPtr->Azalia.AzaliaConfig.AzaliaSdin1;
PinRouting <<= 8;
PinRouting |= (UINT32 )LocalCfgPtr->Azalia.AzaliaConfig.AzaliaSdin0;
do {
if ( ( ! (PinRouting & BIT0) ) && (PinRouting & BIT1) ) {
ConfigureAzaliaPinCmd (LocalCfgPtr, BAR0, ChannelNum);
}
PinRouting >>= 8;
ChannelNum++;
} while ( ChannelNum != 4 );
} else {
//
//No Azalia codec found
//
if ( LocalCfgPtr->Azalia.AzaliaEnable != AzEnable ) {
EnableAzalia = FALSE; ///set flag to disable Azalia
}
}
}
if ( EnableAzalia ) {
if ( LocalCfgPtr->Azalia.AzaliaSnoop == 1 ) {
RwPci ((((0x14<<3)+2) << 16) + 0x42, AccessWidth8, 0xFF, BIT1 + BIT0, StdHeader);
}
} else {
//
//disable Azalia controller
//
RwPci ((((0x14<<3)+2) << 16) + 0x04, AccessWidth16, 0, 0, StdHeader);
RwMem (ACPI_MMIO_BASE + PMIO_BASE + 0xEB , AccessWidth8, (UINT32)~BIT0, 0);
RwMem (ACPI_MMIO_BASE + PMIO_BASE + 0xEB , AccessWidth8, (UINT32)~BIT0, 0);
}
}
/**
* Pin Config for ALC880, ALC882 and ALC883.
*
*
*
*/
CODEC_ENTRY AzaliaCodecAlc882Table[] =
{
{0x14, 0x01014010},
{0x15, 0x01011012},
{0x16, 0x01016011},
{0x17, 0x01012014},
{0x18, 0x01A19030},
{0x19, 0x411111F0},
{0x1a, 0x01813080},
{0x1b, 0x411111F0},
{0x1C, 0x411111F0},
{0x1d, 0x411111F0},
{0x1e, 0x01441150},
{0x1f, 0x01C46160},
{0xff, 0xffffffff}
};
/**
* Pin Config for ALC0262.
*
*
*
*/
CODEC_ENTRY AzaliaCodecAlc262Table[] =
{
{0x14, 0x01014010},
{0x15, 0x411111F0},
{0x16, 0x411111F0},
{0x18, 0x01A19830},
{0x19, 0x02A19C40},
{0x1a, 0x01813031},
{0x1b, 0x02014C20},
{0x1c, 0x411111F0},
{0x1d, 0x411111F0},
{0x1e, 0x0144111E},
{0x1f, 0x01C46150},
{0xff, 0xffffffff}
};
/**
* Pin Config for ALC0269.
*
*
*
*/
CODEC_ENTRY AzaliaCodecAlc269Table[] =
{
{0x12, 0x99A308F0},
{0x14, 0x99130010},
{0x15, 0x0121101F},
{0x16, 0x99036120},
{0x18, 0x01A19850},
{0x19, 0x99A309F0},
{0x1a, 0x01813051},
{0x1b, 0x0181405F},
{0x1d, 0x40134601},
{0x1e, 0x01442130},
{0x11, 0x99430140},
{0x20, 0x0030FFFF},
{0xff, 0xffffffff}
};
/**
* Pin Config for ALC0861.
*
*
*
*/
CODEC_ENTRY AzaliaCodecAlc861Table[] =
{
{0x01, 0x8086C601},
{0x0B, 0x01014110},
{0x0C, 0x01813140},
{0x0D, 0x01A19941},
{0x0E, 0x411111F0},
{0x0F, 0x02214420},
{0x10, 0x02A1994E},
{0x11, 0x99330142},
{0x12, 0x01451130},
{0x1F, 0x411111F0},
{0x20, 0x411111F0},
{0x23, 0x411111F0},
{0xff, 0xffffffff}
};
/**
* Pin Config for ALC0889.
*
*
*
*/
CODEC_ENTRY AzaliaCodecAlc889Table[] =
{
{0x11, 0x411111F0},
{0x14, 0x01014010},
{0x15, 0x01011012},
{0x16, 0x01016011},
{0x17, 0x01013014},
{0x18, 0x01A19030},
{0x19, 0x411111F0},
{0x1a, 0x411111F0},
{0x1b, 0x411111F0},
{0x1C, 0x411111F0},
{0x1d, 0x411111F0},
{0x1e, 0x01442150},
{0x1f, 0x01C42160},
{0xff, 0xffffffff}
};
/**
* Pin Config for ADI1984.
*
*
*
*/
CODEC_ENTRY AzaliaCodecAd1984Table[] =
{
{0x11, 0x0221401F},
{0x12, 0x90170110},
{0x13, 0x511301F0},
{0x14, 0x02A15020},
{0x15, 0x50A301F0},
{0x16, 0x593301F0},
{0x17, 0x55A601F0},
{0x18, 0x55A601F0},
{0x1A, 0x91F311F0},
{0x1B, 0x014511A0},
{0x1C, 0x599301F0},
{0xff, 0xffffffff}
};
/**
* FrontPanel Config table list
*
*
*
*/
CODEC_ENTRY FrontPanelAzaliaCodecTableList[] =
{
{0x19, 0x02A19040},
{0x1b, 0x02214020},
{0xff, 0xffffffff}
};
/**
* Current HD Audio support codec list
*
*
*
*/
CODEC_TBL_LIST AzaliaCodecTableList[] =
{
{0x010ec0880, &AzaliaCodecAlc882Table[0]},
{0x010ec0882, &AzaliaCodecAlc882Table[0]},
{0x010ec0883, &AzaliaCodecAlc882Table[0]},
{0x010ec0885, &AzaliaCodecAlc882Table[0]},
{0x010ec0889, &AzaliaCodecAlc889Table[0]},
{0x010ec0262, &AzaliaCodecAlc262Table[0]},
{0x010ec0269, &AzaliaCodecAlc269Table[0]},
{0x010ec0861, &AzaliaCodecAlc861Table[0]},
{0x011d41984, &AzaliaCodecAd1984Table[0]},
{ (UINT32) 0x0FFFFFFFF, (CODEC_ENTRY*) (UINTN)0x0FFFFFFFF}
};
/**
* ConfigureAzaliaPinCmd - Configuration HD Audio PIN Command
*
*
* @param[in] FchDataPtr Fch configuration structure pointer.
* @param[in] BAR0 HD Audio BAR0 base address.
* @param[in] ChannelNum Channel Number.
*
*/
VOID
ConfigureAzaliaPinCmd (
IN FCH_DATA_BLOCK *FchDataPtr,
IN UINT32 BAR0,
IN UINT8 ChannelNum
)
{
UINT32 AzaliaTempVariable;
UINT32 ChannelNumDword;
CODEC_TBL_LIST *TempAzaliaOemCodecTablePtr;
CODEC_ENTRY *TempAzaliaCodecEntryPtr;
if ( (FchDataPtr->Azalia.AzaliaPinCfg) != 1 ) {
return;
}
ChannelNumDword = ChannelNum << 28;
AzaliaTempVariable = 0xF0000;
AzaliaTempVariable |= ChannelNumDword;
WriteMem (BAR0 + 0x60, AccessWidth32, &AzaliaTempVariable);
FchStall (600, FchDataPtr->StdHeader);
ReadMem (BAR0 + 0x64, AccessWidth32, &AzaliaTempVariable);
if ( ((FchDataPtr->Azalia.AzaliaOemCodecTablePtr) == NULL) || ((FchDataPtr->Azalia.AzaliaOemCodecTablePtr) == ((CODEC_TBL_LIST*) (UINTN)0xFFFFFFFF))) {
TempAzaliaOemCodecTablePtr = (CODEC_TBL_LIST*) (&AzaliaCodecTableList[0]);
} else {
TempAzaliaOemCodecTablePtr = (CODEC_TBL_LIST*) FchDataPtr->Azalia.AzaliaOemCodecTablePtr;
}
while ( TempAzaliaOemCodecTablePtr->CodecId != 0xFFFFFFFF ) {
if ( TempAzaliaOemCodecTablePtr->CodecId == AzaliaTempVariable ) {
break;
} else {
++TempAzaliaOemCodecTablePtr;
}
}
if ( TempAzaliaOemCodecTablePtr->CodecId != 0xFFFFFFFF ) {
TempAzaliaCodecEntryPtr = (CODEC_ENTRY*) TempAzaliaOemCodecTablePtr->CodecTablePtr;
if ( ((FchDataPtr->Azalia.AzaliaOemCodecTablePtr) == NULL) || ((FchDataPtr->Azalia.AzaliaOemCodecTablePtr) == ((CODEC_TBL_LIST*) (UINTN)0xFFFFFFFF)) ) {
TempAzaliaCodecEntryPtr = (CODEC_ENTRY*) (TempAzaliaCodecEntryPtr);
}
ConfigureAzaliaSetConfigD4Dword (TempAzaliaCodecEntryPtr, ChannelNumDword, BAR0, FchDataPtr->StdHeader);
if ( FchDataPtr->Azalia.AzaliaFrontPanel != 1 ) {
if ( (FchDataPtr->Azalia.AzaliaFrontPanel == 2) || (FchDataPtr->Azalia.FrontPanelDetected == 1) ) {
if ( ((FchDataPtr->Azalia.AzaliaOemFpCodecTablePtr) == NULL) || ((FchDataPtr->Azalia.AzaliaOemFpCodecTablePtr) == (VOID*) (UINTN)0xFFFFFFFF) ) {
TempAzaliaCodecEntryPtr = (CODEC_ENTRY*) (&FrontPanelAzaliaCodecTableList[0]);
} else {
TempAzaliaCodecEntryPtr = (CODEC_ENTRY*) FchDataPtr->Azalia.AzaliaOemFpCodecTablePtr;
}
ConfigureAzaliaSetConfigD4Dword (TempAzaliaCodecEntryPtr, ChannelNumDword, BAR0, FchDataPtr->StdHeader);
}
}
}
}
/**
* ConfigureAzaliaSetConfigD4Dword - Configuration HD Audio Codec table
*
*
* @param[in] TempAzaliaCodecEntryPtr HD Audio Codec table structure pointer.
* @param[in] ChannelNumDword HD Audio Channel Number.
* @param[in] BAR0 HD Audio BAR0 base address.
* @param[in] StdHeader
*
*/
VOID
ConfigureAzaliaSetConfigD4Dword (
IN CODEC_ENTRY *TempAzaliaCodecEntryPtr,
IN UINT32 ChannelNumDword,
IN UINT32 BAR0,
IN AMD_CONFIG_PARAMS *StdHeader
)
{
UINT8 TempByte1;
UINT8 TempByte2;
UINT8 Index;
UINT32 TempDword1;
UINT32 TempDword2;
TempDword1 = 0;
TempDword2 = 0;
while ( (TempAzaliaCodecEntryPtr->Nid) != 0xFF ) {
TempByte1 = 0x20;
if ( (TempAzaliaCodecEntryPtr->Nid) == 0x1 ) {
TempByte1 = 0x24;
}
TempDword1 = TempAzaliaCodecEntryPtr->Nid;
TempDword1 &= 0xff;
TempDword1 <<= 20;
TempDword1 |= ChannelNumDword;
TempDword1 |= (0x700 << 8);
for ( Index = 4; Index > 0; Index-- ) {
do {
ReadMem (BAR0 + 0x68, AccessWidth32, &TempDword2);
} while ( (TempDword2 & BIT0) != 0 );
TempByte2 = (UINT8) (( (TempAzaliaCodecEntryPtr->Byte40) >> ((4 - Index) * 8 ) ) & 0xff);
TempDword1 = (TempDword1 & 0xFFFF0000) + ((TempByte1 - Index) << 8) + TempByte2;
WriteMem (BAR0 + 0x60, AccessWidth32, &TempDword1);
FchStall (60, StdHeader);
}
++TempAzaliaCodecEntryPtr;
}
}
| hustcalm/coreboot-hacking | src/vendorcode/amd/agesa/f15tn/Proc/Fch/Azalia/AzaliaMid.c | C | gpl-2.0 | 16,108 |
//-----------------------------------------------------------------------------
// Class: DummyAnimInstance
// Authors: Li, Xizhi
// Emails: LiXizhi@yeah.net
// Company: ParaEngine
// Date: 2014.9.21
//-----------------------------------------------------------------------------
#include "ParaEngine.h"
#include "ParaXModel/AnimTable.h"
#include "DummyAnimInstance.h"
/** @def default walking speed when no model is found. */
#define DEFAULT_WALK_SPEED 4.f
using namespace ParaEngine;
ParaEngine::CDummyAnimInstance::CDummyAnimInstance()
{
// since it is a singleton, we will never reference count it.
addref();
}
CDummyAnimInstance* ParaEngine::CDummyAnimInstance::GetInstance()
{
static CDummyAnimInstance s_instance;
return &s_instance;
}
void ParaEngine::CDummyAnimInstance::LoadAnimation(int nAnimID, float * fSpeed, bool bAppend /*= false*/)
{
if (fSpeed)
{
if (nAnimID == ANIM_STAND)
*fSpeed = 0.f;
else if (nAnimID == ANIM_WALK)
*fSpeed = DEFAULT_WALK_SPEED;
else if (nAnimID == ANIM_RUN)
*fSpeed = DEFAULT_WALK_SPEED*1.5f;
else if (nAnimID == ANIM_FLY)
*fSpeed = DEFAULT_WALK_SPEED*2.f;
else
*fSpeed = 0.f;
}
}
bool ParaEngine::CDummyAnimInstance::HasAnimId(int nAnimID)
{
return (nAnimID == ANIM_STAND || nAnimID == ANIM_WALK || nAnimID == ANIM_RUN || nAnimID == ANIM_FLY);
}
void ParaEngine::CDummyAnimInstance::GetSpeedOf(const char * sName, float * fSpeed)
{
int nAnimID = CAnimTable::GetAnimIDByName(sName);
if (fSpeed)
{
if (nAnimID == ANIM_STAND)
*fSpeed = 0.f;
else if (nAnimID == ANIM_WALK)
*fSpeed = DEFAULT_WALK_SPEED;
else if (nAnimID == ANIM_RUN)
*fSpeed = DEFAULT_WALK_SPEED*1.5f;
else if (nAnimID == ANIM_FLY)
*fSpeed = DEFAULT_WALK_SPEED*2.f;
else
*fSpeed = 0.f;
}
}
| hetter/NPLRuntime | Client/trunk/ParaEngineClient/3dengine/DummyAnimInstance.cpp | C++ | gpl-2.0 | 1,763 |
package emu.project64.input;
import java.util.Set;
import emu.project64.AndroidDevice;
import emu.project64.input.map.TouchMap;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.graphics.Point;
import android.os.Vibrator;
import android.util.SparseIntArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
/**
* A class for generating N64 controller commands from a touchscreen.
*/
public class TouchController extends AbstractController implements OnTouchListener
{
public interface OnStateChangedListener
{
/**
* Called after the analog stick values have changed.
*
* @param axisFractionX The x-axis fraction, between -1 and 1, inclusive.
* @param axisFractionY The y-axis fraction, between -1 and 1, inclusive.
*/
public void onAnalogChanged( float axisFractionX, float axisFractionY );
/**
* Called after auto-hold button state changed.
*
* @param pressed The auto-hold state.
* @param index The index of the auto-hold mask.
*/
public void onAutoHold( boolean pressed, int index );
}
public static final int AUTOHOLD_METHOD_DISABLED = 0;
public static final int AUTOHOLD_METHOD_LONGPRESS = 1;
public static final int AUTOHOLD_METHOD_SLIDEOUT = 2;
/** The number of milliseconds to wait before auto-holding (long-press method). */
private static final int AUTOHOLD_LONGPRESS_TIME = 1000;
/** The pattern vibration when auto-hold is engaged. */
private static final long[] AUTOHOLD_VIBRATE_PATTERN = { 0, 50, 50, 50 };
/** The number of milliseconds of vibration when pressing a key. */
private static final int FEEDBACK_VIBRATE_TIME = 50;
/** The maximum number of pointers to query. */
private static final int MAX_POINTER_IDS = 256;
/** The state change listener. */
private final OnStateChangedListener mListener;
/** The map from screen coordinates to N64 controls. */
private final TouchMap mTouchMap;
/** The map from pointer ids to N64 controls. */
private final SparseIntArray mPointerMap = new SparseIntArray();
/** The method used for auto-holding buttons. */
private final int mAutoHoldMethod;
/** The set of auto-holdable buttons. */
private final Set<Integer> mAutoHoldables;
/** Whether touchscreen feedback is enabled. */
private final boolean mTouchscreenFeedback;
/** The touch state of each pointer. True indicates down, false indicates up. */
private final boolean[] mTouchState = new boolean[MAX_POINTER_IDS];
/** The x-coordinate of each pointer, between 0 and (screenwidth-1), inclusive. */
private final int[] mPointerX = new int[MAX_POINTER_IDS];
/** The y-coordinate of each pointer, between 0 and (screenheight-1), inclusive. */
private final int[] mPointerY = new int[MAX_POINTER_IDS];
/** The pressed start time of each pointer. */
private final long[] mStartTime = new long[MAX_POINTER_IDS];
/** The time between press and release of each pointer. */
private final long[] mElapsedTime = new long[MAX_POINTER_IDS];
/**
* The identifier of the pointer associated with the analog stick. -1 indicates the stick has
* been released.
*/
private int mAnalogPid = -1;
/** The touch event source to listen to, or 0 to listen to all sources. */
private int mSourceFilter = 0;
private Vibrator mVibrator = null;
/**
* Instantiates a new touch controller.
*
* @param touchMap The map from touch coordinates to N64 controls.
* @param view The view receiving touch event data.
* @param listener The listener for controller state changes.
* @param vibrator The haptic feedback device. MUST BE NULL if vibrate permission not granted.
* @param autoHoldMethod The method for auto-holding buttons.
* @param touchscreenFeedback True if haptic feedback should be used.
* @param autoHoldableButtons The N64 commands that correspond to auto-holdable buttons.
*/
public TouchController( TouchMap touchMap, View view, OnStateChangedListener listener,
Vibrator vibrator, int autoHoldMethod, boolean touchscreenFeedback,
Set<Integer> autoHoldableButtons )
{
mListener = listener;
mTouchMap = touchMap;
mVibrator = vibrator;
mAutoHoldMethod = autoHoldMethod;
mTouchscreenFeedback = touchscreenFeedback;
mAutoHoldables = autoHoldableButtons;
view.setOnTouchListener( this );
}
/**
* Sets the touch event source filter.
*
* @param source The source to listen to, or 0 to listen to all sources.
*/
public void setSourceFilter( int source )
{
mSourceFilter = source;
}
/*
* (non-Javadoc)
*
* @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent)
*/
@SuppressLint( "ClickableViewAccessibility" )
@Override
@TargetApi( 9 )
public boolean onTouch( View view, MotionEvent event )
{
// Filter by source, if applicable
int source = AndroidDevice.IS_GINGERBREAD ? event.getSource() : 0;
if( mSourceFilter != 0 && mSourceFilter != source )
return false;
int action = event.getAction();
int actionCode = action & MotionEvent.ACTION_MASK;
int pid = -1;
switch( actionCode )
{
case MotionEvent.ACTION_POINTER_DOWN:
// A non-primary touch has been made
pid = event.getPointerId( action >> MotionEvent.ACTION_POINTER_INDEX_SHIFT );
mStartTime[pid] = System.currentTimeMillis();
mTouchState[pid] = true;
break;
case MotionEvent.ACTION_POINTER_UP:
// A non-primary touch has been released
pid = event.getPointerId( action >> MotionEvent.ACTION_POINTER_INDEX_SHIFT );
mElapsedTime[pid] = System.currentTimeMillis() - mStartTime[pid];
mTouchState[pid] = false;
break;
case MotionEvent.ACTION_DOWN:
// A touch gesture has started (e.g. analog stick movement)
for( int i = 0; i < event.getPointerCount(); i++ )
{
pid = event.getPointerId( i );
mStartTime[pid] = System.currentTimeMillis();
mTouchState[pid] = true;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
// A touch gesture has ended or canceled (e.g. analog stick movement)
for( int i = 0; i < event.getPointerCount(); i++ )
{
pid = event.getPointerId( i );
mElapsedTime[pid] = System.currentTimeMillis() - mStartTime[pid];
mTouchState[pid] = false;
}
break;
default:
break;
}
// Update the coordinates of down pointers and record max PID for speed
int maxPid = -1;
for( int i = 0; i < event.getPointerCount(); i++ )
{
pid = event.getPointerId( i );
if( pid > maxPid )
maxPid = pid;
if( mTouchState[pid] )
{
mPointerX[pid] = (int) event.getX( i );
mPointerY[pid] = (int) event.getY( i );
}
}
// Process each touch
processTouches( mTouchState, mPointerX, mPointerY, mElapsedTime, maxPid );
return true;
}
/**
* Sets the N64 controller state based on where the screen is (multi-) touched. Values outside
* the ranges listed below are safe.
*
* @param touchstate The touch state of each pointer. True indicates down, false indicates up.
* @param pointerX The x-coordinate of each pointer, between 0 and (screenwidth-1), inclusive.
* @param pointerY The y-coordinate of each pointer, between 0 and (screenheight-1), inclusive.
* @param maxPid Maximum ID of the pointers that have changed (speed optimization).
*/
private void processTouches( boolean[] touchstate, int[] pointerX, int[] pointerY,
long[] elapsedTime, int maxPid )
{
boolean analogMoved = false;
// Process each pointer in sequence
for( int pid = 0; pid <= maxPid; pid++ )
{
// Release analog if its pointer is not touching the screen
if( pid == mAnalogPid && !touchstate[pid] )
{
analogMoved = true;
mAnalogPid = -1;
mState.axisFractionX = 0;
mState.axisFractionY = 0;
}
// Process button inputs
if( pid != mAnalogPid )
processButtonTouch( touchstate[pid], pointerX[pid], pointerY[pid],
elapsedTime[pid], pid );
// Process analog inputs
if( touchstate[pid] && processAnalogTouch( pid, pointerX[pid], pointerY[pid] ) )
analogMoved = true;
}
// Call the super method to send the input to the core
notifyChanged();
// Update the skin if the virtual analog stick moved
if( analogMoved && mListener != null )
mListener.onAnalogChanged( mState.axisFractionX, mState.axisFractionY );
}
/**
* Process a touch as if intended for a button. Values outside the ranges listed below are safe.
*
* @param touched Whether the button is pressed or not.
* @param xLocation The x-coordinate of the touch, between 0 and (screenwidth-1), inclusive.
* @param yLocation The y-coordinate of the touch, between 0 and (screenheight-1), inclusive.
* @param pid The identifier of the touch pointer.
*/
private void processButtonTouch( boolean touched, int xLocation, int yLocation,
long timeElapsed, int pid )
{
// Determine the index of the button that was pressed
int index = touched
? mTouchMap.getButtonPress( xLocation, yLocation )
: mPointerMap.get( pid, TouchMap.UNMAPPED );
// Update the pointer map
if( !touched )
{
// Finger lifted off screen, forget what this pointer was touching
mPointerMap.delete( pid );
}
else
{
// Determine where the finger came from if is was slid
int prevIndex = mPointerMap.get( pid, TouchMap.UNMAPPED );
// Finger touched somewhere on screen, remember what this pointer is touching
mPointerMap.put( pid, index );
if( prevIndex != index )
{
// Finger slid from somewhere else, act accordingly
// There are three possibilities:
// - old button --> new button
// - nothing --> new button
// - old button --> nothing
// Reset this pointer's start time
mStartTime[pid] = System.currentTimeMillis();
if( prevIndex != TouchMap.UNMAPPED )
{
// Slid off a valid button
if( !isAutoHoldable( prevIndex ) || mAutoHoldMethod == AUTOHOLD_METHOD_DISABLED )
{
// Slid off a non-auto-hold button
setTouchState( prevIndex, false );
}
else
{
// Slid off an auto-hold button
switch( mAutoHoldMethod )
{
case AUTOHOLD_METHOD_LONGPRESS:
// Using long-press method, release auto-hold button
if( mListener != null )
mListener.onAutoHold( false, prevIndex );
setTouchState( prevIndex, false );
break;
case AUTOHOLD_METHOD_SLIDEOUT:
// Using slide-off method, engage auto-hold button
if( mVibrator != null )
{
mVibrator.cancel();
mVibrator.vibrate( AUTOHOLD_VIBRATE_PATTERN, -1 );
}
if( mListener != null )
mListener.onAutoHold( true, prevIndex );
setTouchState( prevIndex, true );
break;
}
}
}
}
}
if( index != TouchMap.UNMAPPED )
{
// Finger is on a valid button
// Provide simple vibration feedback for any valid button when first touched
if( touched && mTouchscreenFeedback && mVibrator != null )
{
boolean firstTouched;
if( index < NUM_N64_BUTTONS )
{
// Single button pressed
firstTouched = !mState.buttons[index];
}
else
{
// Two d-pad buttons pressed simultaneously
switch( index )
{
case TouchMap.DPD_RU:
firstTouched = !( mState.buttons[DPD_R] && mState.buttons[DPD_U] );
break;
case TouchMap.DPD_RD:
firstTouched = !( mState.buttons[DPD_R] && mState.buttons[DPD_D] );
break;
case TouchMap.DPD_LD:
firstTouched = !( mState.buttons[DPD_L] && mState.buttons[DPD_D] );
break;
case TouchMap.DPD_LU:
firstTouched = !( mState.buttons[DPD_L] && mState.buttons[DPD_U] );
break;
default:
firstTouched = false;
break;
}
}
if( firstTouched )
{
mVibrator.cancel();
mVibrator.vibrate( FEEDBACK_VIBRATE_TIME );
}
}
// Set the controller state accordingly
if( touched || !isAutoHoldable( index ) || mAutoHoldMethod == AUTOHOLD_METHOD_DISABLED )
{
// Finger just touched a button (any kind) OR
// Finger just lifted off non-auto-holdable button
setTouchState( index, touched );
// Do not provide auto-hold feedback yet
}
else
{
// Finger just lifted off an auto-holdable button
switch( mAutoHoldMethod )
{
case AUTOHOLD_METHOD_SLIDEOUT:
// Release auto-hold button if using slide-off method
if( mListener != null )
mListener.onAutoHold( false, index );
setTouchState( index, false );
break;
case AUTOHOLD_METHOD_LONGPRESS:
if( timeElapsed < AUTOHOLD_LONGPRESS_TIME )
{
// Release auto-hold if short-pressed
if( mListener != null )
mListener.onAutoHold( false, index );
setTouchState( index, false );
}
else
{
// Engage auto-hold if long-pressed
if( mVibrator != null )
{
mVibrator.cancel();
mVibrator.vibrate( AUTOHOLD_VIBRATE_PATTERN, -1 );
}
if( mListener != null )
mListener.onAutoHold( true, index );
setTouchState( index, true );
}
break;
}
}
}
}
/**
* Checks if the button mapped to an N64 command is auto-holdable.
*
* @param commandIndex The index to the N64 command.
*
* @return True if the button mapped to the command is auto-holdable.
*/
private boolean isAutoHoldable( int commandIndex )
{
return mAutoHoldables != null && mAutoHoldables.contains( commandIndex );
}
/**
* Sets the state of a button, and handles the D-Pad diagonals.
*
* @param index Which button is affected.
* @param touched Whether the button is pressed or not.
*/
private void setTouchState( int index, boolean touched )
{
// Set the button state
if( index < AbstractController.NUM_N64_BUTTONS )
{
// A single button was pressed
mState.buttons[index] = touched;
}
else
{
// Two d-pad buttons pressed simultaneously
switch( index )
{
case TouchMap.DPD_RU:
mState.buttons[DPD_R] = touched;
mState.buttons[DPD_U] = touched;
break;
case TouchMap.DPD_RD:
mState.buttons[DPD_R] = touched;
mState.buttons[DPD_D] = touched;
break;
case TouchMap.DPD_LD:
mState.buttons[DPD_L] = touched;
mState.buttons[DPD_D] = touched;
break;
case TouchMap.DPD_LU:
mState.buttons[DPD_L] = touched;
mState.buttons[DPD_U] = touched;
break;
default:
break;
}
}
}
/**
* Process a touch as if intended for the analog stick. Values outside the ranges listed below
* are safe.
*
* @param pointerId The pointer identifier.
* @param xLocation The x-coordinate of the touch, between 0 and (screenwidth-1), inclusive.
* @param yLocation The y-coordinate of the touch, between 0 and (screenheight-1), inclusive.
*
* @return True, if the analog state changed.
*/
private boolean processAnalogTouch( int pointerId, int xLocation, int yLocation )
{
// Get the cartesian displacement of the analog stick
Point point = mTouchMap.getAnalogDisplacement( xLocation, yLocation );
// Compute the pythagorean displacement of the stick
int dX = point.x;
int dY = point.y;
float displacement = (float) Math.sqrt( ( dX * dX ) + ( dY * dY ) );
// "Capture" the analog control
if( mTouchMap.isInCaptureRange( displacement ) )
mAnalogPid = pointerId;
if( pointerId == mAnalogPid )
{
// User is controlling the analog stick
// Limit range of motion to an octagon (like the real N64 controller)
point = mTouchMap.getConstrainedDisplacement( dX, dY );
dX = point.x;
dY = point.y;
displacement = (float) Math.sqrt( ( dX * dX ) + ( dY * dY ) );
// Fraction of full-throttle, between 0 and 1, inclusive
float p = mTouchMap.getAnalogStrength( displacement );
// Store the axis values in the super fields (screen y is inverted)
mState.axisFractionX = p * dX / displacement;
mState.axisFractionY = -p * dY / displacement;
// Analog state changed
return true;
}
// Analog state did not change
return false;
}
}
| shygoo/project64 | Android/app/src/main/java/emu/project64/input/TouchController.java | Java | gpl-2.0 | 20,746 |
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.aztec;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.common.AbstractBlackBoxTestCase;
/**
* @author David Olivier
*/
public final class AztecBlackBox1TestCase extends AbstractBlackBoxTestCase {
public AztecBlackBox1TestCase() {
super("test/data/blackbox/aztec-1", new AztecReader(), BarcodeFormat.AZTEC);
addTest(12, 12, 0.0f);
addTest(12, 12, 90.0f);
addTest(12, 12, 180.0f);
addTest(12, 12, 270.0f);
}
} | faarwa/EngSocP5 | zxing/core/test/src/com/google/zxing/aztec/AztecBlackBox1TestCase.java | Java | gpl-3.0 | 1,076 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace src\loader\utils;
defined('MOODLE_INTERNAL') || die();
class curl {
// This is just a dummy file to avoid failures in CI.
}
| CinecaElearning/moodle-logstore_xapi | src/loader/utils/filelib.php | PHP | gpl-3.0 | 830 |
/*
===========================================================================
Copyright (c) 2010-2014 Darkstar Dev Teams
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 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 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/
This file is part of DarkStar-server source code.
===========================================================================
*/
#include "../../common/socket.h"
#include <string.h>
#include "char_jobs.h"
#include "../entities/charentity.h"
CCharJobsPacket::CCharJobsPacket(CCharEntity * PChar)
{
this->type = 0x1B;
this->size = 0x32;
WBUFB(data,(0x04)-4) = PChar->look.race;
WBUFB(data,(0x08)-4) = PChar->GetMJob(); // подсвечиваем желтым главную профессию
WBUFB(data,(0x0B)-4) = PChar->GetSJob(); // подсвечиваем синим дополнительную профессию
memcpy(data+(0x0C)-4, &PChar->jobs, 22);
memcpy(data+(0x20)-4, &PChar->stats,14);
memcpy(data+(0x44)-4, &PChar->jobs, 27);
WBUFL(data,(0x3C)-4) = PChar->health.hp;
WBUFL(data,(0x40)-4) = PChar->health.mp;
WBUFL(data,(0x44)-4) = PChar->jobs.unlocked & 1; // первый бит в unlocked отвечает за дополнительную профессию
WBUFW(data,(0x60)-4) = PChar->m_EquipBlock; // заблокированные ячейки экипировки
//WBUFW(data,(0x62)-4) = blok; // битовое поле. занижение физических характеристик, характеристика становится красной и рядом появляется красная стрелка.
}
| FFXIOrgins/FFXIOrgins | src/map/packets/char_jobs.cpp | C++ | gpl-3.0 | 2,247 |
int r;
void turn(int i, int j, int x, int y, int z,int x0, int y0, int L, int W, int H) {
if (z==0) { int R = x*x+y*y; if (R<r) r=R;
} else {
if(i>=0 && i< 2) turn(i+1, j, x0+L+z, y, x0+L-x, x0+L, y0, H, W, L);
if(j>=0 && j< 2) turn(i, j+1, x, y0+W+z, y0+W-y, x0, y0+W, L, H, W);
if(i<=0 && i>-2) turn(i-1, j, x0-z, y, x-x0, x0-H, y0, H, W, L);
if(j<=0 && j>-2) turn(i, j-1, x, y0-z, y-y0, x0, y0-H, L, H, W);
}
}
int main(){
int L, H, W, x1, y1, z1, x2, y2, z2;
cin >> L >> W >> H >> x1 >> y1 >> z1 >> x2 >> y2 >> z2;
if (z1!=0 && z1!=H) if (y1==0 || y1==W)
swap(y1,z1), std::swap(y2,z2), std::swap(W,H);
else swap(x1,z1), std::swap(x2,z2), std::swap(L,H);
if (z1==H) z1=0, z2=H-z2;
r=0x3fffffff;
turn(0,0,x2-x1,y2-y1,z2,-x1,-y1,L,W,H);
cout<<r<<endl;
}
| kzoacn/Grimoire | Template/source/hints/长方体表面两点最短距离.cpp | C++ | gpl-3.0 | 802 |
//=================================================================
// common.h
//=================================================================
// This file is part of a Software Defined Radio.
// Copyright (C) 2006, 2007 FlexRadio Systems
//
// 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.
//
// You may contact us via email at: sales@flex-radio.com.
// Paper mail may be sent to:
// FlexRadio Systems
// 12100 Technology Blvd.
// Austin, TX 78727
// USA
//=================================================================
#ifndef _common_h
#define _common_h
#ifndef BOOLEAN
typedef unsigned char BOOLEAN;
#endif
#ifndef TRUE
#define TRUE 1
#define true 1
#endif
#ifndef FALSE
#define FALSE 0
#define false 0
#endif
typedef unsigned char uint8;
typedef char int8;
typedef unsigned short uint16;
typedef short int16;
typedef unsigned int uint32;
typedef int int32;
typedef unsigned long long uint64;
typedef long long int64;
#endif // _common_h
| kusi581/bda | trunk/src/sdr1000/src/common/common.h | C | gpl-3.0 | 1,691 |
/* testsuite.h - failif */
process test_addargs(bool8);
process test_bigargs(bool8);
process test_schedule(bool8 verbose);
process test_preempt(bool8 verbose);
process test_recursion(bool8 verbose);
process test_semaphore(bool8 verbose);
process test_semaphore2(bool8 verbose);
process test_semaphore3(bool8 verbose);
process test_semaphore4(bool8 verbose);
process test_semaphore5(bool8 verbose);
process test_libStdio(bool8 verbose);
void testPass(bool8, const char *);
void testFail(bool8, const char *);
void testSkip(bool8, const char *);
void testPrint(bool8, const char *);
/*------------------------------------------------------------------------
* failif - report failure by displaying a message is condition is met
*------------------------------------------------------------------------
*/
#define failif(cond, failmsg) \
if ( cond ) { testFail(verbose, failmsg); passed = FALSE; } \
else { testPass(verbose, ""); }
/* Define the strcuture of an entry in the table of test cases */
struct testcase {
char *name; /* Name of test case */
process (*test) (bool8);/* Test case function */
};
extern int ntests; /* total number of tests */
extern struct testcase testtab[]; /* table of test cases */
#define TESTSTK 8192 /* size of process stack used for test */
| rhexsel/xinu-cMIPS | xinu/include/testsuite.h | C | gpl-3.0 | 1,300 |
/*
* 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.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.io.IOCase;
/**
* Filters filenames for a certain prefix.
* <p>
* For example, to print all files and directories in the
* current directory whose name starts with <code>Test</code>:
*
* <pre>
* File dir = new File(".");
* String[] files = dir.list( new PrefixFileFilter("Test") );
* for ( int i = 0; i < files.length; i++ ) {
* System.out.println(files[i]);
* }
* </pre>
*
* @since Commons IO 1.0
* @version $Revision: 1005099 $ $Date: 2010-10-06 17:13:01 +0100 (Wed, 06 Oct 2010) $
*
* @author Stephen Colebourne
* @author Federico Barbieri
* @author Serge Knystautas
* @author Peter Donald
* @see FileFilterUtils#prefixFileFilter(String)
* @see FileFilterUtils#prefixFileFilter(String, IOCase)
*/
public class PrefixFileFilter extends AbstractFileFilter implements Serializable {
/** The filename prefixes to search for */
private final String[] prefixes;
/** Whether the comparison is case sensitive. */
private final IOCase caseSensitivity;
/**
* Constructs a new Prefix file filter for a single prefix.
*
* @param prefix the prefix to allow, must not be null
* @throws IllegalArgumentException if the prefix is null
*/
public PrefixFileFilter(String prefix) {
this(prefix, IOCase.SENSITIVE);
}
/**
* Constructs a new Prefix file filter for a single prefix
* specifying case-sensitivity.
*
* @param prefix the prefix to allow, must not be null
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the prefix is null
* @since Commons IO 1.4
*/
public PrefixFileFilter(String prefix, IOCase caseSensitivity) {
if (prefix == null) {
throw new IllegalArgumentException("The prefix must not be null");
}
this.prefixes = new String[] {prefix};
this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
}
/**
* Constructs a new Prefix file filter for any of an array of prefixes.
* <p>
* The array is not cloned, so could be changed after constructing the
* instance. This would be inadvisable however.
*
* @param prefixes the prefixes to allow, must not be null
* @throws IllegalArgumentException if the prefix array is null
*/
public PrefixFileFilter(String[] prefixes) {
this(prefixes, IOCase.SENSITIVE);
}
/**
* Constructs a new Prefix file filter for any of an array of prefixes
* specifying case-sensitivity.
* <p>
* The array is not cloned, so could be changed after constructing the
* instance. This would be inadvisable however.
*
* @param prefixes the prefixes to allow, must not be null
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the prefix is null
* @since Commons IO 1.4
*/
public PrefixFileFilter(String[] prefixes, IOCase caseSensitivity) {
if (prefixes == null) {
throw new IllegalArgumentException("The array of prefixes must not be null");
}
this.prefixes = new String[prefixes.length];
System.arraycopy(prefixes, 0, this.prefixes, 0, prefixes.length);
this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
}
/**
* Constructs a new Prefix file filter for a list of prefixes.
*
* @param prefixes the prefixes to allow, must not be null
* @throws IllegalArgumentException if the prefix list is null
* @throws ClassCastException if the list does not contain Strings
*/
public PrefixFileFilter(List<String> prefixes) {
this(prefixes, IOCase.SENSITIVE);
}
/**
* Constructs a new Prefix file filter for a list of prefixes
* specifying case-sensitivity.
*
* @param prefixes the prefixes to allow, must not be null
* @param caseSensitivity how to handle case sensitivity, null means case-sensitive
* @throws IllegalArgumentException if the prefix list is null
* @throws ClassCastException if the list does not contain Strings
* @since Commons IO 1.4
*/
public PrefixFileFilter(List<String> prefixes, IOCase caseSensitivity) {
if (prefixes == null) {
throw new IllegalArgumentException("The list of prefixes must not be null");
}
this.prefixes = prefixes.toArray(new String[prefixes.size()]);
this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
}
/**
* Checks to see if the filename starts with the prefix.
*
* @param file the File to check
* @return true if the filename starts with one of our prefixes
*/
@Override
public boolean accept(File file) {
String name = file.getName();
for (String prefix : this.prefixes) {
if (caseSensitivity.checkStartsWith(name, prefix)) {
return true;
}
}
return false;
}
/**
* Checks to see if the filename starts with the prefix.
*
* @param file the File directory
* @param name the filename
* @return true if the filename starts with one of our prefixes
*/
@Override
public boolean accept(File file, String name) {
for (String prefix : prefixes) {
if (caseSensitivity.checkStartsWith(name, prefix)) {
return true;
}
}
return false;
}
/**
* Provide a String representaion of this file filter.
*
* @return a String representaion
*/
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(super.toString());
buffer.append("(");
if (prefixes != null) {
for (int i = 0; i < prefixes.length; i++) {
if (i > 0) {
buffer.append(",");
}
buffer.append(prefixes[i]);
}
}
buffer.append(")");
return buffer.toString();
}
}
| tr4656/Hungry | src/org/apache/commons/io/filefilter/PrefixFileFilter.java | Java | gpl-3.0 | 7,155 |
/**
* This file is part of muCommander, http://www.mucommander.com
* Copyright (C) 2002-2010 Maxence Bernard
*
* muCommander 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.
*
* muCommander is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mucommander.commons.file.filter;
/**
* <code>PathFilter</code> is a {@link FileFilter} that operates on absolute file paths.
*
* @see AbstractPathFilter
* @author Maxence Bernard
*/
public interface PathFilter extends StringCriterionFilter {
}
| jorgevasquezp/mucommander | src/main/com/mucommander/commons/file/filter/PathFilter.java | Java | gpl-3.0 | 1,047 |
<?php
// Text
$_['text_title'] = 'Credit or Debit Card (Processed securely by Perpetual Payments)';
$_['text_credit_card'] = 'Credit Card Details';
$_['text_transaction'] = 'Transaction ID:';
$_['text_avs'] = 'AVS/CVV:';
$_['text_avs_full_match'] = 'Full match';
$_['text_avs_not_match'] = 'Not matched';
$_['text_authorisation'] = 'Authorisation code:';
// Entry
$_['entry_cc_number'] = 'Card Number';
$_['entry_cc_start_date'] = 'Card Valid From Date';
$_['entry_cc_expire_date'] = 'Card Expiry Date';
$_['entry_cc_cvv2'] = 'Card Security Code (CVV2)';
$_['entry_cc_issue'] = 'Card Issue Number';
// Help
$_['help_start_date'] = '(if available)';
$_['help_issue'] = '(for Maestro and Solo cards only)';
| mgraph/opencart | upload/catalog/language/english/payment/perpetual_payments.php | PHP | gpl-3.0 | 776 |
/**
* @file Visual mapping.
*/
define(function (require) {
var zrUtil = require('zrender/core/util');
var zrColor = require('zrender/tool/color');
var linearMap = require('../util/number').linearMap;
var each = zrUtil.each;
var isObject = zrUtil.isObject;
var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
/**
* @param {Object} option
* @param {string} [option.type] See visualHandlers.
* @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed'
* @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent],
* required when mappingMethod is 'linear'
* @param {Array.<Object>=} [option.pieceList] [
* {value: someValue},
* {interval: [min1, max1], visual: {...}},
* {interval: [min2, max2]}
* ],
* required when mappingMethod is 'piecewise'.
* Visual for only each piece can be specified.
* @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2']
* required when mappingMethod is 'category'.
* If no option.categories, categories is set
* as [0, 1, 2, ...].
* @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'.
* @param {(Array|Object|*)} [option.visual] Visual data.
* when mappingMethod is 'category',
* visual data can be array or object
* (like: {cate1: '#222', none: '#fff'})
* or primary types (which represents
* defualt category visual), otherwise visual
* can be array or primary (which will be
* normalized to array).
*
*/
var VisualMapping = function (option) {
var mappingMethod = option.mappingMethod;
var visualType = option.type;
/**
* @readOnly
* @type {Object}
*/
var thisOption = this.option = zrUtil.clone(option);
/**
* @readOnly
* @type {string}
*/
this.type = visualType;
/**
* @readOnly
* @type {string}
*/
this.mappingMethod = mappingMethod;
/**
* @private
* @type {Function}
*/
this._normalizeData = normalizers[mappingMethod];
var visualHandler = visualHandlers[visualType];
/**
* @public
* @type {Function}
*/
this.applyVisual = visualHandler.applyVisual;
/**
* @public
* @type {Function}
*/
this.getColorMapper = visualHandler.getColorMapper;
/**
* @private
* @type {Function}
*/
this._doMap = visualHandler._doMap[mappingMethod];
if (mappingMethod === 'piecewise') {
normalizeVisualRange(thisOption);
preprocessForPiecewise(thisOption);
}
else if (mappingMethod === 'category') {
thisOption.categories
? preprocessForSpecifiedCategory(thisOption)
// categories is ordinal when thisOption.categories not specified,
// which need no more preprocess except normalize visual.
: normalizeVisualRange(thisOption, true);
}
else { // mappingMethod === 'linear' or 'fixed'
zrUtil.assert(mappingMethod !== 'linear' || thisOption.dataExtent);
normalizeVisualRange(thisOption);
}
};
VisualMapping.prototype = {
constructor: VisualMapping,
mapValueToVisual: function (value) {
var normalized = this._normalizeData(value);
return this._doMap(normalized, value);
},
getNormalizer: function () {
return zrUtil.bind(this._normalizeData, this);
}
};
var visualHandlers = VisualMapping.visualHandlers = {
color: {
applyVisual: makeApplyVisual('color'),
/**
* Create a mapper function
* @return {Function}
*/
getColorMapper: function () {
var thisOption = this.option;
return zrUtil.bind(
thisOption.mappingMethod === 'category'
? function (value, isNormalized) {
!isNormalized && (value = this._normalizeData(value));
return doMapCategory.call(this, value);
}
: function (value, isNormalized, out) {
// If output rgb array
// which will be much faster and useful in pixel manipulation
var returnRGBArray = !!out;
!isNormalized && (value = this._normalizeData(value));
out = zrColor.fastMapToColor(value, thisOption.parsedVisual, out);
return returnRGBArray ? out : zrColor.stringify(out, 'rgba');
},
this
);
},
_doMap: {
linear: function (normalized) {
return zrColor.stringify(
zrColor.fastMapToColor(normalized, this.option.parsedVisual),
'rgba'
);
},
category: doMapCategory,
piecewise: function (normalized, value) {
var result = getSpecifiedVisual.call(this, value);
if (result == null) {
result = zrColor.stringify(
zrColor.fastMapToColor(normalized, this.option.parsedVisual),
'rgba'
);
}
return result;
},
fixed: doMapFixed
}
},
colorHue: makePartialColorVisualHandler(function (color, value) {
return zrColor.modifyHSL(color, value);
}),
colorSaturation: makePartialColorVisualHandler(function (color, value) {
return zrColor.modifyHSL(color, null, value);
}),
colorLightness: makePartialColorVisualHandler(function (color, value) {
return zrColor.modifyHSL(color, null, null, value);
}),
colorAlpha: makePartialColorVisualHandler(function (color, value) {
return zrColor.modifyAlpha(color, value);
}),
opacity: {
applyVisual: makeApplyVisual('opacity'),
_doMap: makeDoMap([0, 1])
},
symbol: {
applyVisual: function (value, getter, setter) {
var symbolCfg = this.mapValueToVisual(value);
if (zrUtil.isString(symbolCfg)) {
setter('symbol', symbolCfg);
}
else if (isObject(symbolCfg)) {
for (var name in symbolCfg) {
if (symbolCfg.hasOwnProperty(name)) {
setter(name, symbolCfg[name]);
}
}
}
},
_doMap: {
linear: doMapToArray,
category: doMapCategory,
piecewise: function (normalized, value) {
var result = getSpecifiedVisual.call(this, value);
if (result == null) {
result = doMapToArray.call(this, normalized);
}
return result;
},
fixed: doMapFixed
}
},
symbolSize: {
applyVisual: makeApplyVisual('symbolSize'),
_doMap: makeDoMap([0, 1])
}
};
function preprocessForPiecewise(thisOption) {
var pieceList = thisOption.pieceList;
thisOption.hasSpecialVisual = false;
zrUtil.each(pieceList, function (piece, index) {
piece.originIndex = index;
// piece.visual is "result visual value" but not
// a visual range, so it does not need to be normalized.
if (piece.visual != null) {
thisOption.hasSpecialVisual = true;
}
});
}
function preprocessForSpecifiedCategory(thisOption) {
// Hash categories.
var categories = thisOption.categories;
var visual = thisOption.visual;
var categoryMap = thisOption.categoryMap = {};
each(categories, function (cate, index) {
categoryMap[cate] = index;
});
// Process visual map input.
if (!zrUtil.isArray(visual)) {
var visualArr = [];
if (zrUtil.isObject(visual)) {
each(visual, function (v, cate) {
var index = categoryMap[cate];
visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
});
}
else { // Is primary type, represents default visual.
visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
}
visual = setVisualToOption(thisOption, visualArr);
}
// Remove categories that has no visual,
// then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
for (var i = categories.length - 1; i >= 0; i--) {
if (visual[i] == null) {
delete categoryMap[categories[i]];
categories.pop();
}
}
}
function normalizeVisualRange(thisOption, isCategory) {
var visual = thisOption.visual;
var visualArr = [];
if (zrUtil.isObject(visual)) {
each(visual, function (v) {
visualArr.push(v);
});
}
else if (visual != null) {
visualArr.push(visual);
}
var doNotNeedPair = {color: 1, symbol: 1};
if (!isCategory
&& visualArr.length === 1
&& !doNotNeedPair.hasOwnProperty(thisOption.type)
) {
// Do not care visualArr.length === 0, which is illegal.
visualArr[1] = visualArr[0];
}
setVisualToOption(thisOption, visualArr);
}
function makePartialColorVisualHandler(applyValue) {
return {
applyVisual: function (value, getter, setter) {
value = this.mapValueToVisual(value);
// Must not be array value
setter('color', applyValue(getter('color'), value));
},
_doMap: makeDoMap([0, 1])
};
}
function doMapToArray(normalized) {
var visual = this.option.visual;
return visual[
Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))
] || {};
}
function makeApplyVisual(visualType) {
return function (value, getter, setter) {
setter(visualType, this.mapValueToVisual(value));
};
}
function doMapCategory(normalized) {
var visual = this.option.visual;
return visual[
(this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX)
? normalized % visual.length
: normalized
];
}
function doMapFixed() {
return this.option.visual[0];
}
function makeDoMap(sourceExtent) {
return {
linear: function (normalized) {
return linearMap(normalized, sourceExtent, this.option.visual, true);
},
category: doMapCategory,
piecewise: function (normalized, value) {
var result = getSpecifiedVisual.call(this, value);
if (result == null) {
result = linearMap(normalized, sourceExtent, this.option.visual, true);
}
return result;
},
fixed: doMapFixed
};
}
function getSpecifiedVisual(value) {
var thisOption = this.option;
var pieceList = thisOption.pieceList;
if (thisOption.hasSpecialVisual) {
var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
var piece = pieceList[pieceIndex];
if (piece && piece.visual) {
return piece.visual[this.type];
}
}
}
function setVisualToOption(thisOption, visualArr) {
thisOption.visual = visualArr;
if (thisOption.type === 'color') {
thisOption.parsedVisual = zrUtil.map(visualArr, function (item) {
return zrColor.parse(item);
});
}
return visualArr;
}
/**
* Normalizers by mapping methods.
*/
var normalizers = {
linear: function (value) {
return linearMap(value, this.option.dataExtent, [0, 1], true);
},
piecewise: function (value) {
var pieceList = this.option.pieceList;
var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
if (pieceIndex != null) {
return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
}
},
category: function (value) {
var index = this.option.categories
? this.option.categoryMap[value]
: value; // ordinal
return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
},
fixed: zrUtil.noop
};
/**
* List available visual types.
*
* @public
* @return {Array.<string>}
*/
VisualMapping.listVisualTypes = function () {
var visualTypes = [];
zrUtil.each(visualHandlers, function (handler, key) {
visualTypes.push(key);
});
return visualTypes;
};
/**
* @public
*/
VisualMapping.addVisualHandler = function (name, handler) {
visualHandlers[name] = handler;
};
/**
* @public
*/
VisualMapping.isValidType = function (visualType) {
return visualHandlers.hasOwnProperty(visualType);
};
/**
* Convinent method.
* Visual can be Object or Array or primary type.
*
* @public
*/
VisualMapping.eachVisual = function (visual, callback, context) {
if (zrUtil.isObject(visual)) {
zrUtil.each(visual, callback, context);
}
else {
callback.call(context, visual);
}
};
VisualMapping.mapVisual = function (visual, callback, context) {
var isPrimary;
var newVisual = zrUtil.isArray(visual)
? []
: zrUtil.isObject(visual)
? {}
: (isPrimary = true, null);
VisualMapping.eachVisual(visual, function (v, key) {
var newVal = callback.call(context, v, key);
isPrimary ? (newVisual = newVal) : (newVisual[key] = newVal);
});
return newVisual;
};
/**
* @public
* @param {Object} obj
* @return {Oject} new object containers visual values.
* If no visuals, return null.
*/
VisualMapping.retrieveVisuals = function (obj) {
var ret = {};
var hasVisual;
obj && each(visualHandlers, function (h, visualType) {
if (obj.hasOwnProperty(visualType)) {
ret[visualType] = obj[visualType];
hasVisual = true;
}
});
return hasVisual ? ret : null;
};
/**
* Give order to visual types, considering colorSaturation, colorAlpha depends on color.
*
* @public
* @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
* IF Array, like: ['color', 'symbol', 'colorSaturation']
* @return {Array.<string>} Sorted visual types.
*/
VisualMapping.prepareVisualTypes = function (visualTypes) {
if (isObject(visualTypes)) {
var types = [];
each(visualTypes, function (item, type) {
types.push(type);
});
visualTypes = types;
}
else if (zrUtil.isArray(visualTypes)) {
visualTypes = visualTypes.slice();
}
else {
return [];
}
visualTypes.sort(function (type1, type2) {
// color should be front of colorSaturation, colorAlpha, ...
// symbol and symbolSize do not matter.
return (type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0)
? 1 : -1;
});
return visualTypes;
};
/**
* 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
* Other visuals are only depends on themself.
*
* @public
* @param {string} visualType1
* @param {string} visualType2
* @return {boolean}
*/
VisualMapping.dependsOn = function (visualType1, visualType2) {
return visualType2 === 'color'
? !!(visualType1 && visualType1.indexOf(visualType2) === 0)
: visualType1 === visualType2;
};
/**
* @param {number} value
* @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...]
* Always from small to big.
* @param {boolean} [findClosestWhenOutside=false]
* @return {number} index
*/
VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
var possibleI;
var abs = Infinity;
// value has the higher priority.
for (var i = 0, len = pieceList.length; i < len; i++) {
var pieceValue = pieceList[i].value;
if (pieceValue != null) {
if (pieceValue === value
// FIXME
// It is supposed to compare value according to value type of dimension,
// but currently value type can exactly be string or number.
// Compromise for numeric-like string (like '12'), especially
// in the case that visualMap.categories is ['22', '33'].
|| (typeof pieceValue === 'string' && pieceValue === value + '')
) {
return i;
}
findClosestWhenOutside && updatePossible(pieceValue, i);
}
}
for (var i = 0, len = pieceList.length; i < len; i++) {
var piece = pieceList[i];
var interval = piece.interval;
var close = piece.close;
if (interval) {
if (interval[0] === -Infinity) {
if (littleThan(close[1], value, interval[1])) {
return i;
}
}
else if (interval[1] === Infinity) {
if (littleThan(close[0], interval[0], value)) {
return i;
}
}
else if (
littleThan(close[0], interval[0], value)
&& littleThan(close[1], value, interval[1])
) {
return i;
}
findClosestWhenOutside && updatePossible(interval[0], i);
findClosestWhenOutside && updatePossible(interval[1], i);
}
}
if (findClosestWhenOutside) {
return value === Infinity
? pieceList.length - 1
: value === -Infinity
? 0
: possibleI;
}
function updatePossible(val, index) {
var newAbs = Math.abs(val - value);
if (newAbs < abs) {
abs = newAbs;
possibleI = index;
}
}
};
function littleThan(close, a, b) {
return close ? a <= b : a < b;
}
return VisualMapping;
}); | mo-norant/FinHeartBel | website/node_modules/echarts/src/visual/VisualMapping.js | JavaScript | gpl-3.0 | 20,627 |
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.codeassist.impl;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.jdt.core.compiler.CharOperation;
public class AssistOptions {
/**
* Option IDs
*/
public static final String OPTION_PerformVisibilityCheck =
"org.eclipse.jdt.core.codeComplete.visibilityCheck"; //$NON-NLS-1$
public static final String OPTION_ForceImplicitQualification =
"org.eclipse.jdt.core.codeComplete.forceImplicitQualification"; //$NON-NLS-1$
public static final String OPTION_FieldPrefixes =
"org.eclipse.jdt.core.codeComplete.fieldPrefixes"; //$NON-NLS-1$
public static final String OPTION_StaticFieldPrefixes =
"org.eclipse.jdt.core.codeComplete.staticFieldPrefixes"; //$NON-NLS-1$
public static final String OPTION_LocalPrefixes =
"org.eclipse.jdt.core.codeComplete.localPrefixes"; //$NON-NLS-1$
public static final String OPTION_ArgumentPrefixes =
"org.eclipse.jdt.core.codeComplete.argumentPrefixes"; //$NON-NLS-1$
public static final String OPTION_FieldSuffixes =
"org.eclipse.jdt.core.codeComplete.fieldSuffixes"; //$NON-NLS-1$
public static final String OPTION_StaticFieldSuffixes =
"org.eclipse.jdt.core.codeComplete.staticFieldSuffixes"; //$NON-NLS-1$
public static final String OPTION_LocalSuffixes =
"org.eclipse.jdt.core.codeComplete.localSuffixes"; //$NON-NLS-1$
public static final String OPTION_ArgumentSuffixes =
"org.eclipse.jdt.core.codeComplete.argumentSuffixes"; //$NON-NLS-1$
public static final String ENABLED = "enabled"; //$NON-NLS-1$
public static final String DISABLED = "disabled"; //$NON-NLS-1$
public boolean checkVisibility = false;
public boolean forceImplicitQualification = false;
public char[][] fieldPrefixes = null;
public char[][] staticFieldPrefixes = null;
public char[][] localPrefixes = null;
public char[][] argumentPrefixes = null;
public char[][] fieldSuffixes = null;
public char[][] staticFieldSuffixes = null;
public char[][] localSuffixes = null;
public char[][] argumentSuffixes = null;
/**
* Initializing the assist options with default settings
*/
public AssistOptions() {
// Initializing the assist options with default settings
}
/**
* Initializing the assist options with external settings
*/
public AssistOptions(Map settings) {
if (settings == null)
return;
// filter options which are related to the assist component
Iterator entries = settings.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry)entries.next();
if (!(entry.getKey() instanceof String))
continue;
if (!(entry.getValue() instanceof String))
continue;
String optionID = (String) entry.getKey();
String optionValue = (String) entry.getValue();
if (optionID.equals(OPTION_PerformVisibilityCheck)) {
if (optionValue.equals(ENABLED)) {
this.checkVisibility = true;
} else
if (optionValue.equals(DISABLED)) {
this.checkVisibility = false;
}
continue;
} else if (optionID.equals(OPTION_ForceImplicitQualification)) {
if (optionValue.equals(ENABLED)) {
this.forceImplicitQualification = true;
} else
if (optionValue.equals(DISABLED)) {
this.forceImplicitQualification = false;
}
continue;
} else if(optionID.equals(OPTION_FieldPrefixes)){
if (optionValue.length() == 0) {
this.fieldPrefixes = null;
} else {
this.fieldPrefixes = CharOperation.splitAndTrimOn(',', optionValue.toCharArray());
}
continue;
} else if(optionID.equals(OPTION_StaticFieldPrefixes)){
if (optionValue.length() == 0) {
this.staticFieldPrefixes = null;
} else {
this.staticFieldPrefixes = CharOperation.splitAndTrimOn(',', optionValue.toCharArray());
}
continue;
} else if(optionID.equals(OPTION_LocalPrefixes)){
if (optionValue.length() == 0) {
this.localPrefixes = null;
} else {
this.localPrefixes = CharOperation.splitAndTrimOn(',', optionValue.toCharArray());
}
continue;
} else if(optionID.equals(OPTION_ArgumentPrefixes)){
if (optionValue.length() == 0) {
this.argumentPrefixes = null;
} else {
this.argumentPrefixes = CharOperation.splitAndTrimOn(',', optionValue.toCharArray());
}
continue;
} else if(optionID.equals(OPTION_FieldSuffixes)){
if (optionValue.length() == 0) {
this.fieldSuffixes = null;
} else {
this.fieldSuffixes = CharOperation.splitAndTrimOn(',', optionValue.toCharArray());
}
continue;
} else if(optionID.equals(OPTION_StaticFieldSuffixes)){
if (optionValue.length() == 0) {
this.staticFieldSuffixes = null;
} else {
this.staticFieldSuffixes = CharOperation.splitAndTrimOn(',', optionValue.toCharArray());
}
continue;
} else if(optionID.equals(OPTION_LocalSuffixes)){
if (optionValue.length() == 0) {
this.localSuffixes = null;
} else {
this.localSuffixes = CharOperation.splitAndTrimOn(',', optionValue.toCharArray());
}
continue;
} else if(optionID.equals(OPTION_ArgumentSuffixes)){
if (optionValue.length() == 0) {
this.argumentSuffixes = null;
} else {
this.argumentSuffixes = CharOperation.splitAndTrimOn(',', optionValue.toCharArray());
}
continue;
}
}
}
} | Niky4000/UsefulUtils | projects/others/eclipse-platform-parent/eclipse.jdt.core-master/org.eclipse.jdt.core.tests.model/workspace/Formatter/test133/A_in.java | Java | gpl-3.0 | 5,799 |
/*
This 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.
Deviation 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 Deviation. If not, see <http://www.gnu.org/licenses/>.
*/
#include <libopencm3/cm3/systick.h>
#include <libopencm3/stm32/timer.h>
#include <libopencm3/stm32/usart.h>
#include <libopencm3/stm32/pwr.h>
#include <libopencm3/stm32/f2/rcc.h>
#include <libopencm3/stm32/f2/rtc.h>
#include <libopencm3/cm3/nvic.h>
#include <libopencm3/stm32/iwdg.h>
#include "common.h"
#include "rtc.h"
#include "../common/devo/devo.h"
//The following is from an unreleased libopencm3
//We should remove it eventually
#if 1
void iwdg_start(void);
void iwdg_set_period_ms(u32 period);
bool iwdg_reload_busy(void);
bool iwdg_prescaler_busy(void);
void iwdg_reset(void);
#endif
volatile u32 msecs;
volatile u32 msecTimer1;
volatile u32 msecTimer2;
volatile u32 wdg_time;
u16 (*timer_callback)(void);
volatile u8 msec_callbacks;
volatile u32 msec_cbtime[NUM_MSEC_CALLBACKS];
void CLOCK_Init()
{
/* 60MHz / 8 => 7500000 counts per second */
systick_set_clocksource(STK_CTRL_CLKSOURCE_AHB_DIV8);
/* 7500000/7500 = 1000 overflows per second - every 1ms one interrupt */
systick_set_reload(7500);
nvic_set_priority(NVIC_SYSTICK_IRQ, 0x0); //Highest priority
/* We trigger exti2 right before the watchdog fires to do a stack dump */
nvic_set_priority(NVIC_EXTI2_IRQ, 0x01); //Highest priority
systick_interrupt_enable();
msecs = 0;
msec_callbacks = 0;
/* Start counting. */
systick_counter_enable();
/* Setup timer for Transmitter */
timer_callback = NULL;
/* Enable TIM5 clock. */
rcc_peripheral_enable_clock(&RCC_APB1ENR, RCC_APB1ENR_TIM5EN);
/* Enable TIM5 interrupt. */
nvic_enable_irq(NVIC_TIM5_IRQ);
nvic_set_priority(NVIC_TIM5_IRQ, 16); //High priority
timer_disable_counter(TIM5);
/* Reset TIM5 peripheral. */
timer_reset(TIM5);
/* Timer global mode:
* - No divider
* - Alignment edge
* - Direction up
*/
timer_set_mode(TIM5, TIM_CR1_CKD_CK_INT,
TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP);
/* timer updates each microsecond */
timer_set_prescaler(TIM5, 60 - 1);
timer_set_period(TIM5, 65535);
/* Disable preload. */
timer_disable_preload(TIM5);
/* Continous mode. */
timer_continuous_mode(TIM5);
/* Disable outputs. */
timer_disable_oc_output(TIM5, TIM_OC1);
timer_disable_oc_output(TIM5, TIM_OC2);
timer_disable_oc_output(TIM5, TIM_OC3);
timer_disable_oc_output(TIM5, TIM_OC4);
/* Enable CCP1 */
timer_disable_oc_clear(TIM5, TIM_OC1);
timer_disable_oc_preload(TIM5, TIM_OC1);
timer_set_oc_slow_mode(TIM5, TIM_OC1);
timer_set_oc_mode(TIM5, TIM_OC1, TIM_OCM_FROZEN);
/* Disable CCP1 interrupt. */
timer_disable_irq(TIM5, TIM_DIER_CC1IE);
timer_enable_counter(TIM5);
/* Enable EXTI1 interrupt. */
/* We are enabling only the interrupt
* We'll manually trigger this via set_pending_interrupt
*/
nvic_enable_irq(NVIC_EXTI1_IRQ);
nvic_set_priority(NVIC_EXTI1_IRQ, 64); //Medium priority
/* Enable DMA Channel1 with same priority as EXTI1 */
//FIXME
//nvic_enable_irq(NVIC_DMA1_STREAM1_IRQ);
//nvic_set_priority(NVIC_DMA1_STREAM1_IRQ, 65); //Medium priority
/* wait for system to start up and stabilize */
while(msecs < 100)
;
}
void CLOCK_StartTimer(unsigned us, u16 (*cb)(void))
{
if(! cb)
return;
timer_callback = cb;
/* Counter enable. */
u16 t = timer_get_counter(TIM5);
/* Set the capture compare value for OC1. */
timer_set_oc_value(TIM5, TIM_OC1, us + t);
timer_clear_flag(TIM5, TIM_SR_CC1IF);
timer_enable_irq(TIM5, TIM_DIER_CC1IE);
}
void CLOCK_StartWatchdog()
{
iwdg_set_period_ms(3000);
iwdg_start();
wdg_time = msecs;
nvic_clear_pending_irq(NVIC_EXTI2_IRQ);
nvic_enable_irq(NVIC_EXTI2_IRQ);
}
void CLOCK_ResetWatchdog()
{
iwdg_reset();
wdg_time = msecs;
}
void CLOCK_StopTimer() {
timer_disable_irq(TIM5, TIM_DIER_CC1IE);
timer_callback = NULL;
}
void tim5_isr()
{
if(timer_callback) {
#ifdef TIMING_DEBUG
debug_timing(4, 0);
#endif
u16 us = timer_callback();
#ifdef TIMING_DEBUG
debug_timing(4, 1);
#endif
timer_clear_flag(TIM5, TIM_SR_CC1IF);
if (us) {
timer_set_oc_value(TIM5, TIM_OC1, us + TIM_CCR1(TIM5));
return;
}
}
CLOCK_StopTimer();
}
u32 CLOCK_getms()
{
return msecs;
}
void CLOCK_SetMsecCallback(int cb, u32 msec)
{
msec_cbtime[cb] = msecs + msec;
msec_callbacks |= (1 << cb);
}
void CLOCK_ClearMsecCallback(int cb)
{
msec_callbacks &= ~(1 << cb);
}
void exti1_isr()
{
//ADC_StartCapture();
//ADC completion will trigger update
ADC_Filter();
medium_priority_cb();
}
void sys_tick_handler(void)
{
msecs++;
if(msecTimer1)
msecTimer1--;
if(msecTimer2)
msecTimer2--;
if(msecs - wdg_time > 2000) {
nvic_set_pending_irq(NVIC_EXTI2_IRQ);
return;
}
if(msec_callbacks & (1 << MEDIUM_PRIORITY)) {
if (msecs == msec_cbtime[MEDIUM_PRIORITY]) {
//medium priority tasks execute in interrupt and main loop context
nvic_set_pending_irq(NVIC_EXTI1_IRQ);
priority_ready |= 1 << MEDIUM_PRIORITY;
msec_cbtime[MEDIUM_PRIORITY] = msecs + MEDIUM_PRIORITY_MSEC;
}
}
if(msec_callbacks & (1 << LOW_PRIORITY)) {
if (msecs == msec_cbtime[LOW_PRIORITY]) {
//Low priority tasks execute in the main loop
priority_ready |= 1 << LOW_PRIORITY;
msec_cbtime[LOW_PRIORITY] = msecs + LOW_PRIORITY_MSEC;
}
}
if(msec_callbacks & (1 << TIMER_SOUND)) {
if (msecs == msec_cbtime[TIMER_SOUND]) {
u16 ms = SOUND_Callback();
if(! ms)
msec_callbacks &= ~(1 << TIMER_SOUND);
else
msec_cbtime[TIMER_SOUND] = msecs + ms;
}
}
}
// initialize RTC
void RTC_Init()
{
rcc_peripheral_enable_clock(&RCC_APB1ENR, RCC_APB1ENR_PWREN);
pwr_disable_backup_domain_write_protect();
rcc_osc_on(LSE);
rcc_wait_for_osc_ready(LSE);
RCC_BDCR |= RCC_BDCR_SRC_LSE; //Set source to LSE
RCC_BDCR |= RCC_BDCR_RTCEN; //Enable RTC
rtc_wait_for_synchro();
rtc_set_prescaler(255, 127);
}
static const u16 daysInYear[2][13] = { { 0,31,59,90,120,151,181,212,243,273,304,334,365},
{ 0,31,60,91,121,152,182,213,244,274,305,335,366} };
// set date value (deviation epoch = seconds since 1.1.2012, 00:00:00)
void RTC_SetValue(u32 value)
{
value += 4382 * 60 * 60 * 24; //convert date from 1.1.2012, 00:00:00 to 1.1.2000, 00:00:00
uint32_t date = 0, time = 0;
const uint32_t SEC = value % 60;
const uint32_t MIN = (value / 60) % 60;
const uint32_t HR = (value / 60 / 60) % 24;
uint32_t DAYS = (value / 60 / 60 / 24);
uint32_t DAY = 0;
uint32_t YEAR = (4*DAYS) / 1461; // = days/365.25
uint32_t LEAP = (YEAR % 4 == 0) ? 1 : 0;
uint32_t WEEKDAY = DAYS / 7 + 7; //1/1/2000 was a Saturday
uint32_t MONTH = 0;
//Convert time to bcd
time |= (SEC % 10) << 0; //seconds ones
time |= (SEC / 10) << 4; //seconds tens
time |= (MIN % 10) << 8; //minutes ones
time |= (MIN / 10) << 12; //minutes tens
time |= (HR % 10) << 16; //hours ones
time |= (HR / 10) << 20; //hours tens
//Convert date to bcd
DAYS -= (uint32_t)(YEAR * 365 + YEAR / 4);
DAYS -= (DAYS > daysInYear[LEAP][2]) ? 1 : 0; //leap year correction for RTC_STARTYEAR
for (MONTH=0; MONTH<12; MONTH++) {
if (DAYS < daysInYear[LEAP][MONTH + 1]) break;
}
DAY = DAYS - daysInYear[LEAP][MONTH];
date |= (DAY % 10) << 0; //date in ones
date |= (DAY / 10) << 4; //date in tens
date |= (MONTH % 10) << 8; //month in ones
date |= (MONTH / 10) << 12; //month in tens
date |= (WEEKDAY) << 13; //weekday
date |= (YEAR % 10) << 16; //year in ones
date |= (YEAR / 10) << 20; //year in tens
//Unlock
rtc_unlock();
//Enter Init mode
RTC_ISR = 0xFFFFFFFF;
for(int i = 0; i < 0x10000; i++)
if((RTC_ISR & RTC_ISR_INITF) == 0)
break;
//SetDate
RTC_DR = date;
RTC_TR = time;
// Exit Init mode
RTC_ISR &= (uint32_t)~RTC_ISR_INIT;
//Wait for synch
rtc_wait_for_synchro();
//Lock
rtc_lock();
}
// get date value (deviation epoch = seconds since 1.1.2012, 00:00:00)
u32 RTC_GetValue()
{
u32 value = 0;
uint32_t time = RTC_TR;
uint32_t date = RTC_DR;
const uint32_t YEAR = (((date >> 20) & 0x0f) * 10) + ((date >> 16) & 0x0f) - 12;
const uint32_t MONTH = (((date >> 12) & 0x01) * 10) + ((date >> 8) & 0x0f);
const uint32_t DAY = (((date >> 4) & 0x03) * 10) + ((date >> 0) & 0x0f);
const uint32_t HOUR = (((time >> 20) & 0x03) * 10) + ((time >> 16) & 0x0f);
const uint32_t MIN = (((time >> 12) & 0x07) * 10) + ((time >> 8) & 0x0f);
const uint32_t SEC = (((time >> 4) & 0x07) * 10) + ((time >> 0) & 0x0f);
value += (DAY-1 + daysInYear[YEAR%4 == 0 ? 1 : 0][MONTH-1] + YEAR * 365 + YEAR/4 + ((YEAR != 0 && MONTH > 2) ? 1 : 0)) * (60*60*24);
value += HOUR*60*60 + MIN*60+SEC;
return value;
}
void rtc_gettime(struct gtm * t)
{
uint32_t time = RTC_TR;
uint32_t date = RTC_DR;
const uint32_t YEAR = (((date >> 20) & 0x0f) * 10) + ((date >> 16) & 0x0f);
const uint32_t MONTH = (((date >> 12) & 0x01) * 10) + ((date >> 8) & 0x0f);
const uint32_t DAY = (((date >> 4) & 0x03) * 10) + ((date >> 0) & 0x0f);
const uint32_t HOUR = (((time >> 20) & 0x03) * 10) + ((time >> 16) & 0x0f);
const uint32_t MIN = (((time >> 12) & 0x07) * 10) + ((time >> 8) & 0x0f);
const uint32_t SEC = (((time >> 4) & 0x07) * 10) + ((time >> 0) & 0x0f);
t->tm_hour = HOUR;
t->tm_min = MIN;
t->tm_sec = SEC;
t->tm_year = YEAR + 100;
t->tm_mon = MONTH;
t->tm_mday = DAY;
}
| cctsao1008/deviation | src/target/x9d/clock.c | C | gpl-3.0 | 10,674 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_29) on Wed Jan 11 13:02:06 MST 2012 -->
<TITLE>
Uses of Class org.imgscalr.Scalr.Mode (imgscalr v4.2 - Java Image Scaling Library)
</TITLE>
<META NAME="date" CONTENT="2012-01-11">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.imgscalr.Scalr.Mode (imgscalr v4.2 - Java Image Scaling Library)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../org/imgscalr/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/imgscalr/\class-useScalr.Mode.html" target="_top"><B>FRAMES</B></A>
<A HREF="Scalr.Mode.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.imgscalr.Scalr.Mode</B></H2>
</CENTER>
<A NAME="org.imgscalr"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr">Scalr.Mode</A> in <A HREF="../../../org/imgscalr/package-summary.html">org.imgscalr</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../org/imgscalr/package-summary.html">org.imgscalr</A> that return <A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr">Scalr.Mode</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr">Scalr.Mode</A></CODE></FONT></TD>
<TD><CODE><B>Scalr.Mode.</B><B><A HREF="../../../org/imgscalr/Scalr.Mode.html#valueOf(java.lang.String)">valueOf</A></B>(<A HREF="http://download.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> name)</CODE>
<BR>
Returns the enum constant of this type with the specified name.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr">Scalr.Mode</A>[]</CODE></FONT></TD>
<TD><CODE><B>Scalr.Mode.</B><B><A HREF="../../../org/imgscalr/Scalr.Mode.html#values()">values</A></B>()</CODE>
<BR>
Returns an array containing the constants of this enum type, in
the order they are declared.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../org/imgscalr/package-summary.html">org.imgscalr</A> with parameters of type <A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr">Scalr.Mode</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html?is-external=true" title="class or interface in java.awt.image">BufferedImage</A></CODE></FONT></TD>
<TD><CODE><B>Scalr.</B><B><A HREF="../../../org/imgscalr/Scalr.html#resize(java.awt.image.BufferedImage, org.imgscalr.Scalr.Method, org.imgscalr.Scalr.Mode, int, java.awt.image.BufferedImageOp...)">resize</A></B>(<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html?is-external=true" title="class or interface in java.awt.image">BufferedImage</A> src,
<A HREF="../../../org/imgscalr/Scalr.Method.html" title="enum in org.imgscalr">Scalr.Method</A> scalingMethod,
<A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr">Scalr.Mode</A> resizeMode,
int targetSize,
<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImageOp.html?is-external=true" title="class or interface in java.awt.image">BufferedImageOp</A>... ops)</CODE>
<BR>
Resize a given image (maintaining its original proportion) to a width and
height no bigger than <code>targetSize</code> (or fitting the image to
the given WIDTH or HEIGHT explicitly, depending on the <A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr"><CODE>Scalr.Mode</CODE></A>
specified) using the given scaling method and apply the given
<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImageOp.html?is-external=true" title="class or interface in java.awt.image"><CODE>BufferedImageOp</CODE></A>s (if any) to the result before returning it.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html?is-external=true" title="class or interface in java.util.concurrent">Future</A><<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html?is-external=true" title="class or interface in java.awt.image">BufferedImage</A>></CODE></FONT></TD>
<TD><CODE><B>AsyncScalr.</B><B><A HREF="../../../org/imgscalr/AsyncScalr.html#resize(java.awt.image.BufferedImage, org.imgscalr.Scalr.Method, org.imgscalr.Scalr.Mode, int, java.awt.image.BufferedImageOp...)">resize</A></B>(<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html?is-external=true" title="class or interface in java.awt.image">BufferedImage</A> src,
<A HREF="../../../org/imgscalr/Scalr.Method.html" title="enum in org.imgscalr">Scalr.Method</A> scalingMethod,
<A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr">Scalr.Mode</A> resizeMode,
int targetSize,
<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImageOp.html?is-external=true" title="class or interface in java.awt.image">BufferedImageOp</A>... ops)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html?is-external=true" title="class or interface in java.awt.image">BufferedImage</A></CODE></FONT></TD>
<TD><CODE><B>Scalr.</B><B><A HREF="../../../org/imgscalr/Scalr.html#resize(java.awt.image.BufferedImage, org.imgscalr.Scalr.Method, org.imgscalr.Scalr.Mode, int, int, java.awt.image.BufferedImageOp...)">resize</A></B>(<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html?is-external=true" title="class or interface in java.awt.image">BufferedImage</A> src,
<A HREF="../../../org/imgscalr/Scalr.Method.html" title="enum in org.imgscalr">Scalr.Method</A> scalingMethod,
<A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr">Scalr.Mode</A> resizeMode,
int targetWidth,
int targetHeight,
<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImageOp.html?is-external=true" title="class or interface in java.awt.image">BufferedImageOp</A>... ops)</CODE>
<BR>
Resize a given image (maintaining its original proportion) to the target
width and height (or fitting the image to the given WIDTH or HEIGHT
explicitly, depending on the <A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr"><CODE>Scalr.Mode</CODE></A> specified) using the given
scaling method and apply the given <A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImageOp.html?is-external=true" title="class or interface in java.awt.image"><CODE>BufferedImageOp</CODE></A>s (if any) to
the result before returning it.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html?is-external=true" title="class or interface in java.util.concurrent">Future</A><<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html?is-external=true" title="class or interface in java.awt.image">BufferedImage</A>></CODE></FONT></TD>
<TD><CODE><B>AsyncScalr.</B><B><A HREF="../../../org/imgscalr/AsyncScalr.html#resize(java.awt.image.BufferedImage, org.imgscalr.Scalr.Method, org.imgscalr.Scalr.Mode, int, int, java.awt.image.BufferedImageOp...)">resize</A></B>(<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html?is-external=true" title="class or interface in java.awt.image">BufferedImage</A> src,
<A HREF="../../../org/imgscalr/Scalr.Method.html" title="enum in org.imgscalr">Scalr.Method</A> scalingMethod,
<A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr">Scalr.Mode</A> resizeMode,
int targetWidth,
int targetHeight,
<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImageOp.html?is-external=true" title="class or interface in java.awt.image">BufferedImageOp</A>... ops)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html?is-external=true" title="class or interface in java.awt.image">BufferedImage</A></CODE></FONT></TD>
<TD><CODE><B>Scalr.</B><B><A HREF="../../../org/imgscalr/Scalr.html#resize(java.awt.image.BufferedImage, org.imgscalr.Scalr.Mode, int, java.awt.image.BufferedImageOp...)">resize</A></B>(<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html?is-external=true" title="class or interface in java.awt.image">BufferedImage</A> src,
<A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr">Scalr.Mode</A> resizeMode,
int targetSize,
<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImageOp.html?is-external=true" title="class or interface in java.awt.image">BufferedImageOp</A>... ops)</CODE>
<BR>
Resize a given image (maintaining its original proportion) to a width and
height no bigger than <code>targetSize</code> (or fitting the image to
the given WIDTH or HEIGHT explicitly, depending on the <A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr"><CODE>Scalr.Mode</CODE></A>
specified) and apply the given <A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImageOp.html?is-external=true" title="class or interface in java.awt.image"><CODE>BufferedImageOp</CODE></A>s (if any) to the
result before returning it.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html?is-external=true" title="class or interface in java.util.concurrent">Future</A><<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html?is-external=true" title="class or interface in java.awt.image">BufferedImage</A>></CODE></FONT></TD>
<TD><CODE><B>AsyncScalr.</B><B><A HREF="../../../org/imgscalr/AsyncScalr.html#resize(java.awt.image.BufferedImage, org.imgscalr.Scalr.Mode, int, java.awt.image.BufferedImageOp...)">resize</A></B>(<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html?is-external=true" title="class or interface in java.awt.image">BufferedImage</A> src,
<A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr">Scalr.Mode</A> resizeMode,
int targetSize,
<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImageOp.html?is-external=true" title="class or interface in java.awt.image">BufferedImageOp</A>... ops)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html?is-external=true" title="class or interface in java.awt.image">BufferedImage</A></CODE></FONT></TD>
<TD><CODE><B>Scalr.</B><B><A HREF="../../../org/imgscalr/Scalr.html#resize(java.awt.image.BufferedImage, org.imgscalr.Scalr.Mode, int, int, java.awt.image.BufferedImageOp...)">resize</A></B>(<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html?is-external=true" title="class or interface in java.awt.image">BufferedImage</A> src,
<A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr">Scalr.Mode</A> resizeMode,
int targetWidth,
int targetHeight,
<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImageOp.html?is-external=true" title="class or interface in java.awt.image">BufferedImageOp</A>... ops)</CODE>
<BR>
Resize a given image (maintaining its original proportion) to the target
width and height (or fitting the image to the given WIDTH or HEIGHT
explicitly, depending on the <A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr"><CODE>Scalr.Mode</CODE></A> specified) and apply the given
<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImageOp.html?is-external=true" title="class or interface in java.awt.image"><CODE>BufferedImageOp</CODE></A>s (if any) to the result before returning it.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html?is-external=true" title="class or interface in java.util.concurrent">Future</A><<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html?is-external=true" title="class or interface in java.awt.image">BufferedImage</A>></CODE></FONT></TD>
<TD><CODE><B>AsyncScalr.</B><B><A HREF="../../../org/imgscalr/AsyncScalr.html#resize(java.awt.image.BufferedImage, org.imgscalr.Scalr.Mode, int, int, java.awt.image.BufferedImageOp...)">resize</A></B>(<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html?is-external=true" title="class or interface in java.awt.image">BufferedImage</A> src,
<A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr">Scalr.Mode</A> resizeMode,
int targetWidth,
int targetHeight,
<A HREF="http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImageOp.html?is-external=true" title="class or interface in java.awt.image">BufferedImageOp</A>... ops)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../org/imgscalr/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../org/imgscalr/Scalr.Mode.html" title="enum in org.imgscalr"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
Copyright 2011 The Buzz Media, LLC</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/imgscalr/\class-useScalr.Mode.html" target="_top"><B>FRAMES</B></A>
<A HREF="Scalr.Mode.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| manaris/jythonMusic | library/imgscalr-lib-4.2/javadoc/org/imgscalr/class-use/Scalr.Mode.html | HTML | gpl-3.0 | 20,840 |
var express = require('express')
var app = module.exports = express()
app.get('/404', require('lib/site/layout'))
app.get('*', function (req, res) {
res.redirect('/404')
})
| democracy-os-fr/democracyos | lib/site/error-pages/not-found/index.js | JavaScript | gpl-3.0 | 176 |
/**
* Copyright (C) 2013 - 2016 Johannes Taelman
*
* This file is part of Axoloti.
*
* Axoloti 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.
*
* Axoloti 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
* Axoloti. If not, see <http://www.gnu.org/licenses/>.
*/
package axoloti.menus;
import axoloti.MainFrame;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
/**
*
* @author jtaelman
*/
public class PopulatePatchMenu {
static void PopulatePatchMenu(JMenu parent, String path, String ext) {
File dir = new File(path);
if (!dir.isDirectory()) {
JMenuItem mi = new JMenuItem("no help patches found");
mi.setEnabled(false);
parent.add(mi);
return;
}
final String extension = ext;
File[] files = dir.listFiles(new java.io.FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
Arrays.sort(files);
for (File subdir : files) {
JMenu fm = new JMenu(subdir.getName());
PopulatePatchMenu(fm, subdir.getPath(), extension);
if (fm.getItemCount() > 0) {
parent.add(fm);
}
}
String filenames[] = dir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return (name.endsWith(extension));
}
});
Arrays.sort(filenames);
for (String fn : filenames) {
String fn2 = fn.substring(0, fn.length() - 4);
JMenuItem fm = new JMenuItem(fn2);
fm.setActionCommand("open:" + path + File.separator + fn);
fm.addActionListener(MainFrame.mainframe);
parent.add(fm);
}
}
}
| dkmorb/axoloti | src/main/java/axoloti/menus/PopulatePatchMenu.java | Java | gpl-3.0 | 2,367 |
#define PETSCMAT_DLL
#include "src/mat/impls/aij/seq/aij.h"
EXTERN PetscErrorCode Mat_CheckInode(Mat,PetscTruth);
EXTERN_C_BEGIN
EXTERN PetscErrorCode PETSCMAT_DLLEXPORT MatInodeAdjustForInodes_Inode(Mat,IS*,IS*);
EXTERN PetscErrorCode PETSCMAT_DLLEXPORT MatInodeGetInodeSizes_Inode(Mat,PetscInt*,PetscInt*[],PetscInt*);
EXTERN_C_END
#undef __FUNCT__
#define __FUNCT__ "MatView_Inode"
PetscErrorCode MatView_Inode(Mat A,PetscViewer viewer)
{
Mat_SeqAIJ *a=(Mat_SeqAIJ*)A->data;
PetscErrorCode ierr;
PetscTruth iascii;
PetscViewerFormat format;
PetscFunctionBegin;
ierr = PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_ASCII,&iascii);CHKERRQ(ierr);
if (iascii) {
ierr = PetscViewerGetFormat(viewer,&format);CHKERRQ(ierr);
if (format == PETSC_VIEWER_ASCII_INFO_DETAIL || format == PETSC_VIEWER_ASCII_INFO) {
if (a->inode.size) {
ierr = PetscViewerASCIIPrintf(viewer,"using I-node routines: found %D nodes, limit used is %D\n",
a->inode.node_count,a->inode.limit);CHKERRQ(ierr);
} else {
ierr = PetscViewerASCIIPrintf(viewer,"not using I-node routines\n");CHKERRQ(ierr);
}
}
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "MatAssemblyEnd_Inode"
PetscErrorCode MatAssemblyEnd_Inode(Mat A, MatAssemblyType mode)
{
Mat_SeqAIJ *a = (Mat_SeqAIJ*)A->data;
PetscErrorCode ierr;
PetscTruth samestructure;
PetscFunctionBegin;
/* info.nz_unneeded of zero denotes no structural change was made to the matrix during Assembly */
samestructure = (PetscTruth)(!A->info.nz_unneeded);
/* check for identical nodes. If found, use inode functions */
ierr = Mat_CheckInode(A,samestructure);CHKERRQ(ierr);
a->inode.ibdiagvalid = PETSC_FALSE;
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "MatDestroy_Inode"
PetscErrorCode MatDestroy_Inode(Mat A)
{
PetscErrorCode ierr;
Mat_SeqAIJ *a=(Mat_SeqAIJ*)A->data;
PetscFunctionBegin;
ierr = PetscFree(a->inode.size);CHKERRQ(ierr);
ierr = PetscFree2(a->inode.ibdiag,a->inode.bdiag);CHKERRQ(ierr);
ierr = PetscObjectComposeFunctionDynamic((PetscObject)A,"MatInodeAdjustForInodes_C","",PETSC_NULL);CHKERRQ(ierr);
ierr = PetscObjectComposeFunctionDynamic((PetscObject)A,"MatInodeGetInodeSizes_C","",PETSC_NULL);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
/* MatCreate_Inode is not DLLEXPORTed because it is not a constructor for a complete type. */
/* It is also not registered as a type for use within MatSetType. */
/* It is intended as a helper for the MATSEQAIJ class, so classes which desire Inodes should */
/* inherit off of MATSEQAIJ instead by calling MatSetType(MATSEQAIJ) in their constructor. */
/* Maybe this is a bad idea. (?) */
#undef __FUNCT__
#define __FUNCT__ "MatCreate_Inode"
PetscErrorCode MatCreate_Inode(Mat B)
{
Mat_SeqAIJ *b=(Mat_SeqAIJ*)B->data;
PetscErrorCode ierr;
PetscTruth no_inode,no_unroll;
PetscFunctionBegin;
no_inode = PETSC_FALSE;
no_unroll = PETSC_FALSE;
b->inode.node_count = 0;
b->inode.size = 0;
b->inode.limit = 5;
b->inode.max_limit = 5;
b->inode.ibdiagvalid = PETSC_FALSE;
b->inode.ibdiag = 0;
b->inode.bdiag = 0;
ierr = PetscOptionsBegin(((PetscObject)B)->comm,((PetscObject)B)->prefix,"Options for SEQAIJ matrix","Mat");CHKERRQ(ierr);
ierr = PetscOptionsTruth("-mat_no_unroll","Do not optimize for inodes (slower)",PETSC_NULL,no_unroll,&no_unroll,PETSC_NULL);CHKERRQ(ierr);
if (no_unroll) {ierr = PetscInfo(B,"Not using Inode routines due to -mat_no_unroll\n");CHKERRQ(ierr);}
ierr = PetscOptionsTruth("-mat_no_inode","Do not optimize for inodes (slower)",PETSC_NULL,no_inode,&no_inode,PETSC_NULL);CHKERRQ(ierr);
if (no_inode) {ierr = PetscInfo(B,"Not using Inode routines due to -mat_no_inode\n");CHKERRQ(ierr);}
ierr = PetscOptionsInt("-mat_inode_limit","Do not use inodes larger then this value",PETSC_NULL,b->inode.limit,&b->inode.limit,PETSC_NULL);CHKERRQ(ierr);
ierr = PetscOptionsEnd();CHKERRQ(ierr);
b->inode.use = (PetscTruth)(!(no_unroll || no_inode));
if (b->inode.limit > b->inode.max_limit) b->inode.limit = b->inode.max_limit;
ierr = PetscObjectComposeFunctionDynamic((PetscObject)B,"MatInodeAdjustForInodes_C",
"MatInodeAdjustForInodes_Inode",
MatInodeAdjustForInodes_Inode);CHKERRQ(ierr);
ierr = PetscObjectComposeFunctionDynamic((PetscObject)B,"MatInodeGetInodeSizes_C",
"MatInodeGetInodeSizes_Inode",
MatInodeGetInodeSizes_Inode);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "MatSetOption_Inode"
PetscErrorCode MatSetOption_Inode(Mat A,MatOption op,PetscTruth flg)
{
Mat_SeqAIJ *a=(Mat_SeqAIJ*)A->data;
PetscFunctionBegin;
switch(op) {
case MAT_USE_INODES:
a->inode.use = flg;
break;
default:
break;
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "MatDuplicate_Inode"
PetscErrorCode MatDuplicate_Inode(Mat A,MatDuplicateOption cpvalues,Mat *C)
{
Mat B=*C;
Mat_SeqAIJ *c=(Mat_SeqAIJ*)B->data,*a=(Mat_SeqAIJ*)A->data;
PetscErrorCode ierr;
PetscInt m=A->rmap.n;
PetscFunctionBegin;
c->inode.use = a->inode.use;
c->inode.limit = a->inode.limit;
c->inode.max_limit = a->inode.max_limit;
if (a->inode.size){
ierr = PetscMalloc((m+1)*sizeof(PetscInt),&c->inode.size);CHKERRQ(ierr);
c->inode.node_count = a->inode.node_count;
ierr = PetscMemcpy(c->inode.size,a->inode.size,(m+1)*sizeof(PetscInt));CHKERRQ(ierr);
} else {
c->inode.size = 0;
c->inode.node_count = 0;
}
c->inode.ibdiagvalid = PETSC_FALSE;
c->inode.ibdiag = 0;
c->inode.bdiag = 0;
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "MatILUDTFactor_Inode"
PetscErrorCode MatILUDTFactor_Inode(Mat A,IS isrow,IS iscol,MatFactorInfo *info,Mat *fact)
{
PetscErrorCode ierr;
PetscFunctionBegin;
/* check for identical nodes. If found, use inode functions */
ierr = Mat_CheckInode(*fact,PETSC_FALSE);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "MatLUFactorSymbolic_Inode"
PetscErrorCode MatLUFactorSymbolic_Inode(Mat A,IS isrow,IS iscol,MatFactorInfo *info,Mat *fact)
{
PetscErrorCode ierr;
PetscFunctionBegin;
/* check for identical nodes. If found, use inode functions */
ierr = Mat_CheckInode(*fact,PETSC_FALSE);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "MatILUFactorSymbolic_Inode"
PetscErrorCode MatILUFactorSymbolic_Inode(Mat A,IS isrow,IS iscol,MatFactorInfo *info,Mat *fact)
{
PetscErrorCode ierr;
PetscFunctionBegin;
/* check for identical nodes. If found, use inode functions */
ierr = Mat_CheckInode(*fact,PETSC_FALSE);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
| realincubus/pluto_clang | orio-0.1.0/testsuite/petsc/inode2.c | C | gpl-3.0 | 7,068 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_34) on Thu Jan 07 14:13:59 GMT 2016 -->
<TITLE>
Uses of Class org.apache.fop.render.pdf.PDFDocumentHandlerMaker (Apache FOP 2.1 API)
</TITLE>
<META NAME="date" CONTENT="2016-01-07">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.fop.render.pdf.PDFDocumentHandlerMaker (Apache FOP 2.1 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/fop/render/pdf/PDFDocumentHandlerMaker.html" title="class in org.apache.fop.render.pdf"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 2.1</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/fop/render/pdf//class-usePDFDocumentHandlerMaker.html" target="_top"><B>FRAMES</B></A>
<A HREF="PDFDocumentHandlerMaker.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.fop.render.pdf.PDFDocumentHandlerMaker</B></H2>
</CENTER>
No usage of org.apache.fop.render.pdf.PDFDocumentHandlerMaker
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/fop/render/pdf/PDFDocumentHandlerMaker.html" title="class in org.apache.fop.render.pdf"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 2.1</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/fop/render/pdf//class-usePDFDocumentHandlerMaker.html" target="_top"><B>FRAMES</B></A>
<A HREF="PDFDocumentHandlerMaker.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright 1999-2016 The Apache Software Foundation. All Rights Reserved.
</BODY>
</HTML>
| jbampton/eclipse-cheatsheets-to-dita-to-pdf | src/libs/fop-2.1/javadocs/org/apache/fop/render/pdf/class-use/PDFDocumentHandlerMaker.html | HTML | gpl-3.0 | 6,193 |
/* pmlastmsg.c
* This is a parser module specifically for those horrible
* "<PRI>last message repeated n times" messages notoriously generated
* by some syslog implementations. Note that this parser should be placed
* on top of the parser stack -- it takes out only these messages and
* leaves all others for processing by the other parsers.
*
* NOTE: read comments in module-template.h to understand how this file
* works!
*
* File begun on 2010-07-13 by RGerhards
*
* Copyright 2014-2016 Rainer Gerhards and Adiscon GmbH.
*
* This file is part of rsyslog.
*
* 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
* -or-
* see COPYING.ASL20 in the source distribution
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include "rsyslog.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include "conf.h"
#include "syslogd-types.h"
#include "template.h"
#include "msg.h"
#include "module-template.h"
#include "glbl.h"
#include "errmsg.h"
#include "parser.h"
#include "datetime.h"
#include "unicode-helper.h"
MODULE_TYPE_PARSER
MODULE_TYPE_NOKEEP
PARSER_NAME("rsyslog.lastline")
/* internal structures
*/
DEF_PMOD_STATIC_DATA
DEFobjCurrIf(errmsg)
DEFobjCurrIf(glbl)
DEFobjCurrIf(parser)
DEFobjCurrIf(datetime)
/* static data */
static int bParseHOSTNAMEandTAG; /* cache for the equally-named global param - performance enhancement */
BEGINisCompatibleWithFeature
CODESTARTisCompatibleWithFeature
if(eFeat == sFEATUREAutomaticSanitazion)
iRet = RS_RET_OK;
if(eFeat == sFEATUREAutomaticPRIParsing)
iRet = RS_RET_OK;
ENDisCompatibleWithFeature
/* parse a legay-formatted syslog message.
*/
BEGINparse
uchar *p2parse;
int lenMsg;
#define OpeningText "last message repeated "
#define ClosingText " times"
CODESTARTparse
dbgprintf("Message will now be parsed by \"last message repated n times\" parser.\n");
assert(pMsg != NULL);
assert(pMsg->pszRawMsg != NULL);
lenMsg = pMsg->iLenRawMsg - pMsg->offAfterPRI; /* note: offAfterPRI is already the number of PRI chars (do not add one!) */
p2parse = pMsg->pszRawMsg + pMsg->offAfterPRI; /* point to start of text, after PRI */
/* check if this message is of the type we handle in this (very limited) parser */
/* first, we permit SP */
while(lenMsg && *p2parse == ' ') {
--lenMsg;
++p2parse;
}
if((unsigned) lenMsg < sizeof(OpeningText)-1 + sizeof(ClosingText)-1 + 1) {
/* too short, can not be "our" message */
ABORT_FINALIZE(RS_RET_COULD_NOT_PARSE);
}
if(strncasecmp((char*) p2parse, OpeningText, sizeof(OpeningText)-1) != 0) {
/* wrong opening text */
ABORT_FINALIZE(RS_RET_COULD_NOT_PARSE);
}
lenMsg -= sizeof(OpeningText) - 1;
p2parse += sizeof(OpeningText) - 1;
/* now we need an integer --> digits */
while(lenMsg && isdigit(*p2parse)) {
--lenMsg;
++p2parse;
}
if(lenMsg != sizeof(ClosingText)-1) {
/* size must fit, else it is not "our" message... */
ABORT_FINALIZE(RS_RET_COULD_NOT_PARSE);
}
if(strncasecmp((char*) p2parse, ClosingText, lenMsg) != 0) {
/* wrong closing text */
ABORT_FINALIZE(RS_RET_COULD_NOT_PARSE);
}
/* OK, now we know we need to process this message, so we do that
* (and it is fairly simple in our case...)
*/
DBGPRINTF("pmlastmsg detected a \"last message repeated n times\" message\n");
setProtocolVersion(pMsg, MSG_LEGACY_PROTOCOL);
memcpy(&pMsg->tTIMESTAMP, &pMsg->tRcvdAt, sizeof(struct syslogTime));
MsgSetMSGoffs(pMsg, pMsg->offAfterPRI); /* we don't have a header! */
MsgSetTAG(pMsg, (uchar*)"", 0);
finalize_it:
ENDparse
BEGINmodExit
CODESTARTmodExit
/* release what we no longer need */
objRelease(errmsg, CORE_COMPONENT);
objRelease(glbl, CORE_COMPONENT);
objRelease(parser, CORE_COMPONENT);
objRelease(datetime, CORE_COMPONENT);
ENDmodExit
BEGINqueryEtryPt
CODESTARTqueryEtryPt
CODEqueryEtryPt_STD_PMOD_QUERIES
CODEqueryEtryPt_IsCompatibleWithFeature_IF_OMOD_QUERIES
ENDqueryEtryPt
BEGINmodInit()
CODESTARTmodInit
*ipIFVersProvided = CURR_MOD_IF_VERSION; /* we only support the current interface specification */
CODEmodInit_QueryRegCFSLineHdlr
CHKiRet(objUse(glbl, CORE_COMPONENT));
CHKiRet(objUse(errmsg, CORE_COMPONENT));
CHKiRet(objUse(parser, CORE_COMPONENT));
CHKiRet(objUse(datetime, CORE_COMPONENT));
dbgprintf("lastmsg parser init called, compiled with version %s\n", VERSION);
bParseHOSTNAMEandTAG = glbl.GetParseHOSTNAMEandTAG(); /* cache value, is set only during rsyslogd option processing */
ENDmodInit
/* vim:set ai:
*/
| aturetta/rsyslog | plugins/pmlastmsg/pmlastmsg.c | C | gpl-3.0 | 4,969 |
<div id="configForm">
<ul>
<li><a href="#general">General</a></li>
<li><a href="#content">Downloaders</a></li>
<li><a href="#providers">Providers</a></li>
<li><a href="#quality">Quality</a></li>
<li><a href="#renaming">Renaming</a></li>
<li><a href="#extra">Extras</a></li>
<li><a href="#notifications">Notifications</a></li>
<li><a href="#userscript">Userscript</a></li>
<li><a href="#iphone">iPhone</a></li>
<li><a href="#about">About</a></li>
</ul>
<form class="uniForm" action="${url(controller="config", action="save")}" method="post">
<div class="group general">
<fieldset class="inlineLabels">
<h3>General (need manual restart)</h3>
<div class="ctrlHolder">
<label>Host</label>
<input type="text" name="global.host" value="${config.get('global', 'host')}" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Port</label>
<input type="text" name="global.port" value="${config.get('global', 'port')}" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Username</label>
<input type="text" name="global.username" value="${config.get('global', 'username')}" autocomplete="off" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Password</label>
<input type="password" name="global.password" value="${config.get('global', 'password')}" autocomplete="off" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Launch browser</label>
<input type="checkbox" name="global.launchbrowser" value="True" ${' checked="checked"' if config.get('global', 'launchbrowser') else ''} />
</div>
<div class="ctrlHolder checkbox">
<label>Use updater</label>
<input type="checkbox" name="global.updater" value="True" ${' checked="checked"' if config.get('global', 'updater') else ''} />
</div>
</fieldset>
<fieldset class="inlineLabels">
<h3>Search</h3>
<div class="ctrlHolder">
<label>Search every</label>
<input type="text" name="Intervals.search" value="${config.get('Intervals', 'search')}" class="textInput xsmall"/> hour(s)
</div>
<div class="ctrlHolder">
<label>Ignore words</label>
<input type="text" name="global.ignoreWords" value="${config.get('global', 'ignoreWords')}" class="textInput large"/>
<p class="formHint">
Comma seperated. NZB/Torrents containing these words are ignored. Example: GERMAN, DUBBED, HDTV
</p>
</div>
<div class="ctrlHolder">
<label>Preferred words</label>
<input type="text" name="global.preferredWords" value="${config.get('global', 'preferredWords')}" class="textInput large"/>
<p class="formHint">
Comma seperated. NZB/Torrents containing these words are preferred. Example: Diamond, BluRay, DTS
</p>
</div>
<div class="ctrlHolder">
<label>Required words</label>
<input type="text" name="global.requiredWords" value="${config.get('global', 'requiredWords')}" class="textInput large"/>
<p class="formHint">
Comma seperated. NZB/Torrents must contain these words. Example: GERMAN, DTS
</p>
</div>
</fieldset>
</div>
<div class="group content">
<fieldset class="inlineLabels" id="nzbsFieldset">
<h3>NZBs</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="NZB.enabled" value="True" ${' checked="checked"' if config.get('NZB', 'enabled') else ''} />
</div>
<div class="ctrlHolder">
<label>Retention</label>
<input type="text" name="NZB.retention" value="${config.get('NZB', 'retention')}" class="textInput xsmall"/> day(s)
</div>
<div class="ctrlHolder">
<label for="nzbSendTo">Download to</label>
<select name="NZB.sendTo" id="nzbSendTo" class="textInput large">
% for sendTo in ['Sabnzbd','Blackhole','Nzbget']:
<option value="${sendTo}"${' selected="selected"' if str(sendTo) == config.get('NZB', 'sendTo') else ''}>${sendTo}</option>
% endfor
</select>
</div>
<div class="sabnzbd sendTonzb">
<div class="ctrlHolder">
<label>Host</label>
<input type="text" name="Sabnzbd.host" value="${config.get('Sabnzbd', 'host')}" class="textInput large"/>
<p class="formHint">
Where does SABnzbd run? Usually <i>localhost:8080</i>
</p>
</div>
<div class="ctrlHolder">
<label>Apikey</label>
<input type="text" name="Sabnzbd.apikey" value="${config.get('Sabnzbd', 'apikey')}" class="textInput large"/>
<p class="formHint">
Can be found in general config on SABnzbd
</p>
</div>
<div class="ctrlHolder">
<label>Username</label>
<input type="text" name="Sabnzbd.username" value="${config.get('Sabnzbd', 'username')}" autocomplete="off" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Password</label>
<input type="password" name="Sabnzbd.password" value="${config.get('Sabnzbd', 'password')}" autocomplete="off" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Category</label>
<input type="text" name="Sabnzbd.category" value="${config.get('Sabnzbd', 'category')}" class="textInput large"/>
<p class="formHint">
Category where NZBs should be put.
</p>
</div>
</div>
<div class="nzbblackhole sendTonzb">
<div class="ctrlHolder">
<label>NZB Directory</label>
<input type="text" name="NZB.blackhole" value="${config.get('NZB', 'blackhole')}" class="textInput large"/>
<p class="formHint">
Folder your download program watches for new .nzb files.
</p>
</div>
</div>
<div class="nzbget sendTonzb">
<div class="ctrlHolder">
<label>Host</label>
<input type="text" name="Nzbget.host" value="${config.get('Nzbget', 'host')}" class="textInput large" />
<p class="formHint">
Hostname with port. Usually <i>localhost:6789</i>
</p>
</div>
<div class="ctrlHolder">
<label>Password</label>
<input type="password" name="Nzbget.password" value="${config.get('Nzbget', 'password')}" autocomplete="off" class="textInput large"/>
<p class="formHint">
nzbGet password. Default is <i>tegbzn6789</i>
</p>
</div>
<div class="ctrlHolder">
<label>Category</label>
<input type="text" name="Nzbget.category" value="${config.get('Nzbget', 'category')}" class="textInput large"/>
<p class="formHint">
Category where NZBs should be put.
</p>
</div>
</div>
</fieldset>
<fieldset class="inlineLabels" id="torrentsFieldset">
<h3>Torrents</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="Torrents.enabled" value="True" ${' checked="checked"' if config.get('Torrents', 'enabled') else ''} />
</div>
<div class="ctrlHolder">
<label for="torrentsSendTo">Download to</label>
<select name="Torrents.sendTo" id="torrentsSendTo" class="textInput large">
% for sendTo in ['Transmission','Blackhole']:
<option value="${sendTo}"${' selected="selected"' if str(sendTo) == config.get('Torrents', 'sendTo') else ''}>${sendTo}</option>
% endfor
</select>
</div>
<div class="transmission sendTotorrents">
<div class="ctrlHolder">
<label>Host</label>
<input type="text" name="Transmission.host" value="${config.get('Transmission', 'host')}" class="textInput large"/>
<p class="formHint">
Where does Transmission run? Usually <i>localhost:9091</i>
</p>
</div>
<div class="ctrlHolder">
<label>Username</label>
<input type="text" name="Transmission.username" value="${config.get('Transmission', 'username')}" autocomplete="off" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Password</label>
<input type="password" name="Transmission.password" value="${config.get('Transmission', 'password')}" autocomplete="off" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Download Directory</label>
<input type="text" name="Transmission.directory" value="${config.get('Transmission', 'directory')}" autocomplete="off" class="textInput large"/>
<p class="formHint">
Where should Transmission saved the downloaded files?
</p>
</div>
<div class="ctrlHolder">
<label>Seeding ratio</label>
<input type="text" name="Transmission.ratio" value="${config.get('Transmission', 'ratio')}" autocomplete="off" class="textInput xsmall"/>
<p class="formHint">
Stop transfer when reaching ratio
</p>
</div>
</div>
<div class="torrentsblackhole sendTotorrents">
<div class="ctrlHolder">
<label>Torrent Directory</label>
<input type="text" name="Torrents.blackhole" value="${config.get('Torrents', 'blackhole')}" class="textInput large"/>
<p class="formHint">
Your .torrent watch folder
</p>
</div>
</div>
<div class="ctrlHolder">
<label>Wait</label>
<input type="text" name="Torrents.wait" value="${config.get('Torrents', 'wait')}" class="textInput xsmall"/> hour(s) for nzb
<p class="formHint">
Only if NZB download is enabled.
</p>
</div>
</fieldset>
</div>
<div class="group renaming" id="renamingFieldset">
<fieldset class="inlineLabels">
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="Renamer.enabled" value="True" ${' checked="checked"' if config.get('Renamer', 'enabled') else ''} />
</div>
<div class="ctrlHolder">
<label>Download folder</label>
<input type="text" name="Renamer.download" value="${config.get('Renamer', 'download')}" class="textInput large"/>
<p class="formHint">
Your SABnzbd movie download folder
</p>
</div>
<div class="ctrlHolder">
<label>Movie destination</label>
<input type="text" name="Renamer.destination" value="${config.get('Renamer', 'destination')}" class="textInput large"/>
<p class="formHint">
Where the movies should be moved to. <br />
Should NOT be the same as the "Download folder".
</p>
</div>
<div class="ctrlHolder">
<label>Folder naming</label>
<input type="text" name="Renamer.foldernaming" value="${config.get('Renamer', 'foldernaming').replace('<', '<').replace('>', '>')}" class="textInput large"/>
<p class="formHint">
<span id="foldernameResult"><strong>Result</strong>: ${foldernameResult}</span>
<span style="color:red;">Use <strong>at least</strong> the movie name like <thename>/<namethe> in your foldername, or the world is going to end and lots of movies might get deleted..</span>
</p>
</div>
<div class="ctrlHolder">
<label>File naming</label>
<input type="text" name="Renamer.filenaming" value="${config.get('Renamer', 'filenaming').replace('<', '<').replace('>', '>')}" class="textInput large"/>
<p class="formHint">
<span id="filenameResult"><strong>Result</strong>: ${filenameResult}</span><br />
<a href="#" onclick="return false" id="showHideFileRenameOptions">Show naming-options</a>
</p>
<p class="formHint" id="fileRenameOptions" style="display: none">
<span><strong>original</strong>: The.Big.Lebowski.1998.1080p.BluRay.x264.DTS-GROUP</span><br />
<span><strong>thename</strong>: The Big Lebowski</span><br />
<span><strong>namethe</strong>: Big Lebowski, The</span><br />
<span><strong>ext</strong>: mkv</span><br />
<span><strong>year</strong>: 2008</span><br />
<span><strong>quality</strong>: 1080p</span><br />
<span><strong>group</strong>: GROUP</span><br />
<span><strong>audio</strong>: DTS</span><br />
<span><strong>video</strong>: x264</span><br />
<span><strong>sourcemedia</strong>: BluRay</span><br />
<span><strong>resolution</strong>: 1920x1080</span><br />
<span><strong>first</strong>: B (First character of movie (without "The"))</span><br />
Only with multiple files:
<span><strong>cd</strong>: cd1</span>
<span><strong>cdNr</strong>: 1</span>
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Post-Processing Script</label>
<input type="checkbox" name="Renamer.script_enabled" value="True" ${' checked="checked"' if config.get('Renamer', 'script_enabled') else ''} />
</div>
<div class="ctrlHolder">
<label>File Path</label>
<input type="text" name="Renamer.file_path" value="${config.get('Renamer','file_path')}" class="textInput large"/>
<p class="formHint">
Relative file path to your extra script (starting from CouchPotato install folder)
</p>
</div>
</fieldset>
</fieldset>
<fieldset class="inlineLabels">
<div class="ctrlHolder">
<label>Name separator</label>
<select name="Renamer.separator" class="textInput large">
% for sep, label in {' ':'space', '.':'dot', '-':'dash'}.iteritems():
<option value="${sep}"${' selected="selected"' if sep == config.get('Renamer', 'separator') else ''}>${label}</option>
% endfor
</select>
<p class="formHint">
Replace all the spaces with dots or dashes.
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Cleanup</label>
<input type="checkbox" name="Renamer.cleanup" value="True" ${' checked="checked"' if config.get('Renamer', 'cleanup') else ''} />
<p class="formHint">
Remove leftover files/folders in the Download folder.
</p>
</div>
</fieldset>
</div>
<div class="group providers">
<fieldset class="inlineLabels" id="newzbinFieldset">
<h3>Newzbin</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="newzbin.enabled" value="True" ${' checked="checked"' if config.get('newzbin', 'enabled') else ''} />
</div>
<div class="ctrlHolder">
<label>Username</label>
<input type="text" name="newzbin.username" value="${config.get('newzbin', 'username')}" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Password</label>
<input type="password" name="newzbin.password" value="${config.get('newzbin', 'password')}" class="textInput large"/>
</div>
</fieldset>
<fieldset class="inlineLabels" id="nzbmatrixFieldset">
<h3>NZBMatrix.com</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="NZBMatrix.enabled" value="True" ${' checked="checked"' if config.get('NZBMatrix', 'enabled') else ''} />
</div>
<div class="ctrlHolder">
<label>Username</label>
<input type="text" name="NZBMatrix.username" value="${config.get('NZBMatrix', 'username')}" autocomplete="off" class="textInput large"/>
<p class="formHint">
Can be found <a href="http://nzbmatrix.com/account.php" target="_blank">here</a>, "User Name"
</p>
</div>
<div class="ctrlHolder">
<label>Apikey</label>
<input type="text" name="NZBMatrix.apikey" value="${config.get('NZBMatrix', 'apikey')}" class="textInput large"/>
<p class="formHint">
Can be found <a href="http://nzbmatrix.com/account.php" target="_blank">here</a>, "Current API Key" <br />
You have to be VIP to get an API Key (Hey, that rhymes!).
</p>
</div>
<div class="ctrlHolder checkbox">
<label>English only</label>
<input type="checkbox" name="NZBMatrix.english" value="True" ${' checked="checked"' if config.get('NZBMatrix', 'english') else ''} />
<p class="formHint">
Restrict search to English or unknown NZBs.
</p>
</div>
</fieldset>
<fieldset class="inlineLabels" id="newznabFieldset">
<h3>Newznab</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="newznab.enabled" value="True" ${' checked="checked"' if config.get('newznab', 'enabled') else ''} />
</div>
<div class="ctrlHolder">
<label>Host</label>
<input type="text" name="newznab.host" value="${config.get('newznab', 'host')}" class="textInput large"/>
<p class="formHint">
The hostname of your newznab provider. Example: "provider.com" or "provider.com/newznab".
</p>
</div>
<div class="ctrlHolder">
<label>Apikey</label>
<input type="text" name="newznab.apikey" value="${config.get('newznab', 'apikey')}" class="textInput large"/>
<p class="formHint">
Can be found after login on the "API" page, bottom left. The string after "&apikey=".
</p>
</div>
<p class="formHint">
More info can be found at <a href="http://newznab.com" target="_blank">Newznab.com</a>.
</p>
</fieldset>
<fieldset class="inlineLabels" id="nzbsorgFieldset">
<h3>NZBs.org</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="NZBsorg.enabled" value="True" ${' checked="checked"' if config.get('NZBsorg', 'enabled') else ''} />
</div>
<div class="ctrlHolder">
<label>Id</label>
<input type="text" name="NZBsorg.id" value="${config.get('NZBsorg', 'id')}" class="textInput large"/>
<p class="formHint">
Can be found <a href="http://nzbs.org/index.php?action=rss" target="_blank">here</a>, number after "&i="
</p>
</div>
<div class="ctrlHolder">
<label>Key</label>
<input type="text" name="NZBsorg.key" value="${config.get('NZBsorg', 'key')}" class="textInput large"/>
<p class="formHint">
Can be found <a href="http://nzbs.org/index.php?action=rss" target="_blank">here</a>, string after "&h="
</p>
</div>
</fieldset>
<fieldset class="inlineLabels" id="nzbsrusFieldset">
<h3>NZBsRus.com</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="NZBsRUS.enabled" value="True" ${' checked="checked"' if config.get('NZBsRUS','enabled') else''} />
</div>
<div class="ctrlHolder">
<label>Id</label>
<input type="text" name="NZBsRUS.userid" value="${config.get('NZBsRUS', 'userid')}" class="textInput large" />
<p class="formHint">
Can be found at the bottom of <a href="https://www.nzbsrus.com/rss.php" target="_blank">this</a> page, number after "&i="
</p>
</div>
<div class="ctrlHolder">
<label>Hash</label>
<input type="text" name="NZBsRUS.userhash" value="${config.get('NZBsRUS', 'userhash')}" class="textInput large" />
<p class="formHint">
Can be found at the bottom of <a href="https://www.nzbsrus.com/rss.php" target="_blank">this</a> page, number after "&h="
</p>
</div>
</fieldset>
<fieldset class="inlineLabels">
<h3>#alt.binaries.hdtv.x264@EFnet</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="x264.enabled" value="True" ${' checked="checked"' if config.get('x264','enabled') else''} />
<p class="formHint">
HD movies only
</p>
</div>
</fieldset>
<fieldset class="inlineLabels" style="float: right!important;"> <!--Temp layout fix-->
<h3>MysterBin</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="mysterbin.enabled" value="True" ${' checked="checked"' if config.get('mysterbin','enabled') else''} />
<p class="formHint">
Web Search provider
</p>
</div>
</fieldset>
</div>
<div class="group userscript">
<fieldset class="inlineLabels">
<a href="${baseUrl}CouchPotato.user.js" class="submit userscriptInstall"><img src="${baseUrl}media/images/userscriptPreview.png" /><br />Install UserScript</a>
<p style="font-size:11px">
To use this UserScript, you need <a href="http://www.google.com/chrome/" target="_blank">Google Chrome</a> or the <a href="https://addons.mozilla.org/en-US/firefox/addon/748/" target="_blank">Greasemonkey addon</a> when using Firefox.
</p>
<p style="font-size:11px">If you're on Safari, see <a href="http://couchpotato.fafoulon.fr/" target="_blank">this (unsupported) Safari extension by Fafoulon</a></p>
</fieldset>
</div>
<div class="group iphone">
<fieldset class="inlineLabels">
<div>Got a jailbroken iPhone? Get the iCouchPotato app on Cydia! <span>(Add our Cydia repo: "<strong>http://cydia.myrepospace.com/couchpotato/</strong>" and search for "<strong>iCouchPotato</strong>")</span></div>
<img src="${baseUrl}media/images/iphone1.png" /><img src="${baseUrl}media/images/iphone2.png" /><img src="${baseUrl}media/images/iphone3.png" />
<div>Why isn't it in the normal Appstore you ask? Because Apple is being a bitch!</div>
</fieldset>
</div>
<div class="group about">
<fieldset class="inlineLabels">
<div>
<a href="${url(controller='config',action='exit')}" class="submit">Shutdown</a><span class="or">or</span>
<a href="${url(controller='config',action='restart')}" class="submit restart">Restart</a>
</div>
<div class="site">
<p>
Need help, got a question or problem?<br />
<a href="http://couchpotato.tenderapp.com/" target="_blank">Find help on the Support Forum</a>
</p>
</div>
<div class="site" style="margin:40px 0 0; font-size: 20px;">
<div>Don't have a usenet account yet? Check these out: </div>
<a href="https://usenetserver.com/partners/?a_aid=couchpotato&a_bid=3f357c6f">UsenetServer</a>,
<a href="http://www.newshosting.com/partners/?a_aid=couchpotato&a_bid=a0b022df">Newshosting</a><!-- or
<a href="http://easynews.com/free-account?a_aid=couchpotato&a_bid=443b8133">14 day free Easynews trial</a> -->
<span style="color:#aaa; font-size: 15px;">Help support CouchPotato and save some money for yourself by signing up for an account!</span>
</div>
<div id="donate">
<div>I'm building CouchPotato in my spare time, so if you want to buy me a coke while I'm coding, that would be awesome!</div>
<div>PayPal is playing internet police and blocked my account. But you can send me an awesome 'thank you' email instead ;)</div>
</div>
<div class="site">
<a href="http://couchpotatoapp.com" target="_blank">CouchPotatoApp.com</a>
</div>
<div id="versionInfo">
<h3>Version ${updater.getVersion()}</h3>
% if updater.useUpdater():
<a href="${url(controller='config', action='checkForUpdate')}">Check for new version</a>
% endif
</div>
</fieldset>
</div>
<div class="group quality">
<fieldset class="inlineLabels qualityTemplates">
<h3>Quality Profile</h3>
<div>
<a href="#" id="newTemplate">Create a new quality profile.</a>
</div>
<p class="formHint">
Create a list of qualities CouchPotato should go through when searching for a movie.
It will try and download from top to bottom. Using the finish-checkbox will mark the movie as "completed" when this quality is found.
<img src="${baseUrl}media/images/qualityProfileExample.png"><br />
When adding a movie, you have to select this profile inside the quality list, so give it a nice name.
</p>
<div class="customList"></div>
</fieldset>
<fieldset class="inlineLabels">
<h3>Default Qualities</h3>
<div class="ctrlHolder">
<label>Default quality</label>
<select name="Quality.default" class="textInput large">
% for qualityItem in Qualities.all():
<option value="${qualityItem.name}"${' selected="selected"' if qualityItem.name == config.get('Quality', 'default') else ''}>${qualityItem.label}</option>
% endfor
</select>
</div>
<div class="ctrlHolder">
<label>Order & hide</label>
<div class="standardQualities">
<% hide = Qualities.conf('hide') %>
<input type="hidden" name="Quality.order" value="" />
<input type="hidden" name="Quality.hide" value="" />
% for template in Qualities.all():
<div class="item" data-id="${template.id}" data-name="${template.name}">
<input type="checkbox" ${' checked="checked"' if not str(template.name) in hide else ''} />
<span class="label">${template.label}</span>
<span class="handle"></span>
</div>
% endfor
</div>
</div>
</fieldset>
<fieldset class="inlineLabels qualitySizes right">
<h3>Quality sizes</h3>
<p class="formHint">
Only download the quality that is between these two sizes.<br />
All that are outside these sizes, will be ignored.
</p>
<div class="ctrlHolder">
<span class="size header">
<span>Minimum</span>
<span>Maximum</span>
</span>
</div>
% for key, quality in Qualities.getTypes():
<div class="ctrlHolder">
<label>${quality['label']}</label>
<span class="size">
<span><input type="text" name="Quality.sMin-${key}" value="${config.get('Quality', 'sMin-'+key)}" class="textInput small"/>MB</span>
<span><input type="text" name="Quality.sMax-${key}" value="${config.get('Quality', 'sMax-'+key)}" class="textInput small"/>MB</span>
</span>
</div>
% endfor
</fieldset>
</div>
<div class="group extra">
<fieldset class="inlineLabels">
<h3>Blu-Ray.com RSS</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="MovieRSS.enabled" value="True" ${' checked="checked"' if config.get('MovieRSS', 'enabled') else ''} />
<p class="formHint">
This will magically add movies to your wanted list that match the options below.
</p>
</div>
<div class="ctrlHolder">
<label>Minimum movie year</label>
<input type="text" name="MovieRSS.minyear" value="${config.get('MovieRSS', 'minyear')}" class="textInput large"/>
<p class="formHint">
Movies released after and including this year will be added to the wanted list
</p>
</div>
<div class="ctrlHolder">
<label>Minimum IMDB rating</label>
<input type="text" name="MovieRSS.minrating" value="${config.get('MovieRSS','minrating')}" class="textInput large"/>
<p class="formHint">
The minimum IMDB rating for a movie to be added
</p>
</div>
<div class="ctrlHolder">
<label>Minimum IMDB votes</label>
<input type="text" name="MovieRSS.minvotes" value="${config.get('MovieRSS','minvotes')}" class="textInput large"/>
<p class="formHint">
The minimum IMDB votes for a movie to be added
</p>
</div>
</fieldset>
<fieldset class="inlineLabels">
<h3>Kinepolis.com RSS</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="KinepolisRSS.enabled" value="True" ${' checked="checked"' if config.get('KinepolisRSS', 'enabled') else ''} />
<p class="formHint">
This will magically add movies to your wanted list that match the options below.
</p>
</div>
<div class="ctrlHolder">
<label>Minimum movie year</label>
<input type="text" name="KinepolisRSS.minyear" value="${config.get('KinepolisRSS', 'minyear')}" class="textInput large"/>
<p class="formHint">
Movies released after and including this year will be added to the wanted list
</p>
</div>
<div class="ctrlHolder">
<label>Minimum IMDB rating</label>
<input type="text" name="KinepolisRSS.minrating" value="${config.get('KinepolisRSS','minrating')}" class="textInput large"/>
<p class="formHint">
The minimum IMDB rating for a movie to be added
</p>
</div>
<div class="ctrlHolder">
<label>Minimum IMDB Votes</label>
<input type="text" name="KinepolisRSS.minvotes" value="${config.get('KinepolisRSS','minvotes')}" class="textInput large"/>
<p class="formHint">
The minimum IMDB votes for a movie to be added
</p>
</div>
</fieldset>
<fieldset class="inlineLabels" id="subtitleFieldset">
<h3>Subtitles</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="Subtitles.enabled" value="True" ${' checked="checked"' if config.get('Subtitles', 'enabled') else ''} />
</div>
<div class="ctrlHolder">
<label>Language</label>
<input type="text" name="Subtitles.languages" value="${config.get('Subtitles', 'languages')}" class="textInput large"/>
<p class="formHint">
Comma seperated 2-letter language code (<a href="http://en.wikipedia.org/wiki/ISO_639-1_language_matrix" target="_blank">ISO 639-1</a>). <br />
Example: "en, nl". Most importent first.
</p>
</div>
<div class="ctrlHolder">
<label>Naming</label>
<select name="Subtitles.name" class="textInput large">
<option value="filename"${' selected="selected"' if 'filename' == config.get('Subtitles', 'name') else ''}>filename.ext</option>
<option value="subtitle"${' selected="selected"' if 'subtitle' == config.get('Subtitles', 'name') else ''}>subtitle.ext</option>
</select>
<p class="formHint">
"There Will Be Blood.srt" or "Subtitle.srt"
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Add language to name</label>
<input type="checkbox" name="Subtitles.addLanguage" value="True" ${' checked="checked"' if config.get('Subtitles', 'addLanguage') else ''} />
<p class="formHint">
Add language shortcode to end of subtitle name. Example: "There Will Be Blood.en.srt"
</p>
</div>
</fieldset>
<fieldset class="inlineLabels">
<h3>Trailers</h3>
<div class="ctrlHolder">
<label>Download trailer</label>
<select name="Trailer.quality" class="textInput large">
<option value="">None</option>
% for format in trailerFormats:
<option value="${format}"${' selected="selected"' if format == config.get('Trailer', 'quality') else ''}>${format}</option>
% endfor
</select>
<p class="formHint">
If None, no trailer will be downloaded.
</p>
</div>
<div class="ctrlHolder">
<label>Naming</label>
<select name="Trailer.name" class="textInput large">
<option value="movie-trailer"${' selected="selected"' if 'movie-trailer' == config.get('Trailer', 'name') else ''}>movie-trailer.ext</option>
<option value="moviename-trailer"${' selected="selected"' if 'moviename-trailer' == config.get('Trailer', 'name') else ''}><filename>-trailer.ext</option>
</select>
</div>
</fieldset>
<fieldset class="inlineLabels" id="traktFieldset">
<h3>Trakt</h3>
<div class="ctrlHolder">
<label>Trakt Username</label>
<input type="text" name="Trakt.username" value="${config.get('Trakt','username')}" class="textInput large"/>
<p class="formHint">
Your Trakt username
</p>
</div>
<div class="ctrlHolder">
<label>Trakt Password</label>
<input type="password" name="Trakt.password" value="${config.get('Trakt', 'password')}" class="textInput large"/>
<p class="formHint">
Your Trakt Password
</p>
</div>
<div class="ctrlHolder">
<label>Trakt API Key</label>
<input type="text" name="Trakt.apikey" value="${config.get('Trakt', 'apikey')}" class="textInput large"/>
<p class="formHint">
Get your key at: <a href="http://trakt.tv/settings/api" onclick="window.open(this.href, '_blank'); return false;">http://trakt.tv/settings/api</a>
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Grab movies from watchlist</label>
<input type="checkbox" name="Trakt.watchlist_enabled" value="True" ${' checked="checked"' if config.get('Trakt', 'watchlist_enabled') else ''} />
<p class="formHint">
This will add movies from your Trakt watchlist.
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Ignore Movies in Trakt Collection</label>
<input type="checkbox" name="Trakt.dontaddcollection" value="True" ${' checked="checked"' if config.get('Trakt', 'dontaddcollection') else ''} />
<p class="formHint">
Don't add movies to CouchPotato from watchlist that are already in Trakt collection
</p>
</div>
<div class="ctrlHolder">
<a href="#traktTest" id="traktTest" class="testNotification">Send a message to Trakt, see if it works.</a>
</div>
</fieldset>
<fieldset class="inlineLabels">
<h3>Metadata</h3>
<div class="ctrlHolder checkbox">
<label>Save metadata</label>
<input type="checkbox" name="Meta.enabled" value="True" ${' checked="checked"' if config.get('Meta', 'enabled') else ''} />
<p class="formHint">
Thumbnail, poster and .nfo file.
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Save URL Only</label>
<input type="checkbox" name="Meta.urlonly" value="True" ${' checked="checked"' if config.get('Meta', 'urlonly') else ''} />
<p class="formHint">Save only the IMBD Url in the nfo file
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Fanart Filename</label>
<input type="text" name="Meta.fanartfilename" value="${config.get('Meta','fanartfilename')}" class="textInput large"/>
</div>
<div class="ctrlHolder checkbox">
<label>Poster Filename</label>
<input type="text" name="Meta.posterfilename" value="${config.get('Meta','posterfilename')}" class="textInput large"/>
</div>
<div class="ctrlHolder checkbox">
<label>NFO Filename</label>
<input type="text" name="Meta.nfofilename" value="${config.get('Meta','nfofilename')}" class="textInput large"/>
</div>
</fieldset>
<fieldset class="inlineLabels">
<h3>MovieETA</h3>
<div class="ctrlHolder checkbox">
<label>Check VideoETA</label>
<input type="checkbox" name="MovieETA.enabled" value="True" ${' checked="checked"' if config.get('MovieETA', 'enabled') else ''} />
</div>
</fieldset>
<fieldset class="inlineLabels">
<h3>IMDB Watchlists</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="IMDBWatchlist.enabled" value="True" ${' checked="checked"' if config.get('IMDBWatchlist', 'enabled') else ''} />
<p class="formHint">
This will magically add movies to your wanted list that appear in public IMDB Watchlist(s) specified below.
</p>
</div>
<div class="ctrlHolder">
<label>IMDB Watchlist URL(s)</label>
<textarea name="IMDBWatchlist.url" cols="50" rows="5" class="textInput large">${config.get('IMDBWatchlist', 'url')}</textarea>
<p class="formHint">
Comma separated list of 'Export this list' links from the public IMDB Watchlist pages
</p>
</div>
</fieldset>
</div>
<div class="group notifications">
<fieldset class="inlineLabels" id="xbmcFieldset">
<h3>XBMC</h3>
<div class="ctrlHolder checkbox">
<label>Update library</label>
<input type="checkbox" name="XBMC.enabled" value="True" ${' checked="checked"' if config.get('XBMC', 'enabled') else ''} />
<p class="formHint">
Sends a notification and updates your XBMC library.
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Also on snatched</label>
<input type="checkbox" name="XBMC.onSnatch" value="True" ${' checked="checked"' if config.get('XBMC', 'onSnatch') else ''} />
<p class="formHint">
Also send a notification when a movie is snatched.
</p>
</div>
<div class="ctrlHolder">
<label>Host</label>
<input type="text" name="XBMC.host" value="${config.get('XBMC', 'host')}" class="textInput large"/>
<p class="formHint">
Including port. Example: 192.168.1.20:8080
</p>
</div>
<div class="ctrlHolder">
<label>Username</label>
<input type="text" name="XBMC.username" value="${config.get('XBMC', 'username')}" autocomplete="off" class="textInput large"/>
</div>
<div class="ctrlHolder">
<label>Password</label>
<input type="password" name="XBMC.password" value="${config.get('XBMC', 'password')}" autocomplete="off" class="textInput large"/>
</div>
<div class="ctrlHolder">
<a href="#xbmcTest" id="xbmcTest" class="testNotification">Send a message to XBMC, see if it works.</a>
</div>
<div class="ctrlHolder">
<label>DB Path</label>
<input type="text" name="XBMC.dbpath" value="${config.get('XBMC', 'dbpath')}" autocomplete="off" class="textInput large"/>
<p class="formHint">
Used for checking if you already have a movie in your library, before adding it to your wanted list.
Example: C:\Users\Username\AppData\Roaming\XBMC\userdata\Database
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Use web API</label>
<input type="checkbox" name="XBMC.useWebAPIExistingCheck" value="True" ${' checked="checked"' if config.get('XBMC', 'useWebAPIExistingCheck') else ''} />
<p class="formHint">
Whether to use web API against XBMC hosts to check if you have a movie in your library before adding it to your wanted list.
</p>
</div>
</fieldset>
<fieldset class="inlineLabels" id="nmjFieldset">
<h3>Networked Media Jukebox</h3>
<div class="ctrlHolder checkbox">
<label>Update library</label>
<input type="checkbox" name="NMJ.enabled" value="True" ${' checked="checked"' if config.get('NMJ', 'enabled') else ''} />
<p class="formHint">
Updates your NMJ library.
</p>
</div>
<div class="ctrlHolder">
<label>Host</label>
<input type="text" name="NMJ.host" value="${config.get('NMJ', 'host')}" class="textInput large NMJhost"/>
<p class="formHint">
Example: 192.168.1.20
</p>
</div>
<div class="ctrlHolder">
<a href="#nmjAuto" id="nmjAuto" class="testNotification">Autodetect NMJ Database and mount</a>
<p class="formHint">
Popcorn Hour needs to be on, and NMJ must be running.
</p>
</div>
<div class="ctrlHolder">
<label>NMJ Database</label>
<input type="text" name="NMJ.database" value="${config.get('NMJ', 'database')}" autocomplete="off" class="textInput large NMJdatabase" />
<p class="formHint">
Path to the NMJ Database.
</p>
</div>
<div class="ctrlHolder">
<label>NMJ Mount URL</label>
<input type="text" name="NMJ.mount" value="${config.get('NMJ', 'mount')}" autocomplete="off" class="textInput large NMJmount"/>
<p class="formHint">
Only needed when the database is on a network path.
</p>
</div>
<div class="ctrlHolder">
<a href="#nmjTest" id="nmjTest" class="testNotification">Update the NMJ database, see if it works.</a>
</div>
</fieldset>
<fieldset class="inlineLabels" id="plexFieldset">
<h3>Plex Media Server</h3>
<div class="ctrlHolder checkbox">
<label>Update library</label>
<input type="checkbox" name="PLEX.enabled" value="True" ${' checked="checked"' if config.get('PLEX', 'enabled') else ''} />
<p class="formHint">
Updates your Plex library.
</p>
</div>
<div class="ctrlHolder">
<label>Host</label>
<input type="text" name="PLEX.host" value="${config.get('PLEX', 'host')}" class="textInput large PLEXhost"/>
<p class="formHint">
Including port. Example: 192.168.1.20:32400
</p>
</div>
<div class="ctrlHolder">
<a href="#plexTest" id="plexTest" class="testNotification">Update the Plex database, see if it works.</a>
</div>
</fieldset>
<fieldset class="inlineLabels" id="prowlFieldset">
<h3>Prowl</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="PROWL.enabled" value="True" ${' checked="checked"' if config.get('PROWL', 'enabled') else ''} />
<p class="formHint">
Sends a notification to Prowl
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Also on snatched</label>
<input type="checkbox" name="PROWL.onSnatch" value="True" ${' checked="checked"' if config.get('PROWL', 'onSnatch') else ''} />
<p class="formHint">
Also send a notification when a movie is snatched.
</p>
</div>
<div class="ctrlHolder">
<label>Keys</label>
<input type="text" name="PROWL.keys" value="${config.get('PROWL', 'keys')}" class="textInput large"/>
<p class="ctrlHolder">
<a href="https://www.prowlapp.com/api_settings.php" target="_blank" class="testNotification">Get your Prowl api key here</a>
</p>
</div>
<div class="ctrlHolder">
<label>Priority</label>
<select name="PROWL.priority" class="textInput large">
<option value="-2"${' selected="selected"' if config.get('PROWL', 'priority') == '-2' else ''}>Very Low</option>
<option value="-1"${' selected="selected"' if config.get('PROWL', 'priority') == '-1' else ''}>Moderate</option>
<option value="0"${' selected="selected"' if config.get('PROWL', 'priority') == '0' else ''}>Normal</option>
<option value="1"${' selected="selected"' if config.get('PROWL', 'priority') == '1' else ''}>High</option>
<option value="2"${' selected="selected"' if config.get('PROWL', 'priority') == '2' else ''}>Emergency</option>
</select>
</div>
<div class="ctrlHolder">
<a href="#prowlTest" id="prowlTest" class="testNotification">Send a message to Prowl, see if it works.</a>
</div>
</fieldset>
<fieldset class="inlineLabels" id="growlFieldset">
<h3>Growl</h3>
<div class="ctrlHolder checkbox">
<label>Enable</label>
<input type="checkbox" name="GROWL.enabled" value="True" ${' checked="checked"' if config.get('GROWL', 'enabled') else ''} />
<p class="formHint">
Sends a notification to Growl.
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Also on snatched</label>
<input type="checkbox" name="GROWL.onSnatch" value="True" ${' checked="checked"' if config.get('GROWL', 'onSnatch') else ''} />
<p class="formHint">
Also send a notification when a movie is snatched.
</p>
</div>
<div class="ctrlHolder">
<label>Host</label>
<input type="text" name="GROWL.host" value="${config.get('GROWL', 'host')}" class="textInput large"/>
<p class="formHint">
Example: 192.168.1.20
</p>
</div>
<div class="ctrlHolder">
<label>Password</label>
<input type="password" name="GROWL.password" value="${config.get('GROWL', 'password')}" autocomplete="off" class="textInput large"/>
</div>
<div class="ctrlHolder">
<a href="#growlTest" id="growlTest" class="testNotification">Send a message to Growl, see if it works.</a>
</div>
<p class="ctrlHolder formHint">
Be sure to enable "Listen for incoming notifications" in your Growl Settings, under Network.
</p>
</fieldset>
<fieldset class="inlineLabels" id="notifoFieldset">
<h3>Notifo</h3>
<div class="ctrlHolder checkbox">
<label>Enabled</label>
<input type="checkbox" name="Notifo.enabled" value="True" ${' checked="checked"' if config.get('Notifo', 'enabled') else ''} />
<p class="formHint">
Sends a notification to Notifo
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Also on snatched</label>
<input type="checkbox" name="Notifo.onSnatch" value="True" ${' checked="checked"' if config.get('Notifo', 'onSnatch') else ''} />
<p class="formHint">
Also send a notification when a movie is snatched.
</p>
</div>
<div class="ctrlHolder">
<label>Username</label>
<input type="text" name="Notifo.username" value="${config.get('Notifo', 'username')}" class="textInput large" />
</div>
<div class="ctrlHolder">
<label>API Secret</label>
<input type="text" name="Notifo.key" value="${config.get('Notifo', 'key')}" class="textInput large" />
<p class="formHint">
Get your API secret at:
<a href="http://notifo.com/user/settings" target="blank">http://notifo.com/user/settings</a>
</p>
</div>
<div class="ctrlHolder">
<a href="#notifoTest" id="notifoTest" class="testNotification">Send a message to Notifo, see if it works.</a>
</div>
</fieldset>
<fieldset class="inlineLabels" id="boxcarFieldset">
<h3>Boxcar</h3>
<div class="ctrlHolder checkbox">
<label>Enabled</label>
<input type="checkbox" name="Boxcar.enabled" value="True" ${' checked="checked"' if config.get('Boxcar', 'enabled') else ''} />
<p class="formHint">
Sends a notification to <a href="http://boxcar.io/" target="blank">Boxcar</a>
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Also on snatched</label>
<input type="checkbox" name="Boxcar.onSnatch" value="True" ${' checked="checked"' if config.get('Boxcar', 'onSnatch') else ''} />
<p class="formHint">
Also send a notification when a movie is snatched.
</p>
</div>
<div class="ctrlHolder">
<label>Username</label>
<input type="text" name="Boxcar.username" value="${config.get('Boxcar', 'username')}" class="textInput large" />
</div>
<div class="ctrlHolder">
<a href="#boxcarTest" id="boxcarTest" class="testNotification">Send a message to Boxcar, see if it works.</a>
</div>
</fieldset>
<fieldset class="inlineLabels" id="nmaFieldset">
<h3>NotifyMyAndroid</h3>
<div class="ctrlHolder checkbox">
<label>Enabled</label>
<input type="checkbox" name="NMA.enabled" value="True" ${' checked="checked"' if config.get('NMA', 'enabled') else ''} />
<p class="formHint">
Sends a notification to NotifyMyAndroid
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Also on snatched</label>
<input type="checkbox" name="NMA.onSnatch" value="True" ${' checked="checked"' if config.get('NMA', 'onSnatch') else ''} />
<p class="formHint">
Also send a notification when a movie is snatched.
</p>
</div>
<div class="ctrlHolder">
<label>API Key</label>
<input type="text" name="NMA.apikey" value="${config.get('NMA', 'apikey')}" class="textInput large" />
<p class="formHint">
Multiple keys must be seperated by a , (comma). Up to a maximum of 5
</p>
</div>
<div class="ctrlHolder">
<a href="#nmaTest" id="nmaTest" class="testNotification">Send a message to NotifyMyAndroid, see if it works.</a>
</div>
<div class="ctrlHolder">
<label>Priority</label>
<select name="NMA.priority" class="textInput large">
<option value="-2"${' selected="selected"' if config.get('NMA', 'priority') == '-2' else ''}>Very Low</option>
<option value="-1"${' selected="selected"' if config.get('NMA', 'priority') == '-1' else ''}>Moderate</option>
<option value="0"${' selected="selected"' if config.get('NMA', 'priority') == '0' else ''}>Normal</option>
<option value="1"${' selected="selected"' if config.get('NMA', 'priority') == '1' else ''}>High</option>
<option value="2"${' selected="selected"' if config.get('NMA', 'priority') == '2' else ''}>Emergency</option>
</select>
</div>
</fieldset>
<fieldset class="inlineLabels" id="nmwpFieldset">
<h3>NotifyMyWindowsPhone</h3>
<div class="ctrlHolder checkbox">
<label>Enabled</label>
<input type="checkbox" name="NMWP.enabled" value="True" ${' checked="checked"' if config.get('NMWP', 'enabled') else ''} />
<p class="formHint">
Sends a notification to <a href="https://NotifyMyWindowsPhone.com">NotifyMyWindowsPhone.com</a>
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Also on snatched</label>
<input type="checkbox" name="NMWP.onSnatch" value="True" ${' checked="checked"' if config.get('NMWP', 'onSnatch') else ''} />
<p class="formHint">
Also send a notification when a movie is snatched.
</p>
</div>
<div class="ctrlHolder">
<label>API Key</label>
<input type="text" name="NMWP.apikey" value="${config.get('NMWP', 'apikey')}" class="textInput large" />
<p class="formHint">
Multiple keys must be seperated by a , (comma). Up to a maximum of 5
</p>
</div>
<div class="ctrlHolder">
<a href="#nmwpTest" id="nmwpTest" class="testNotification">Send a message to NotifyMyWindowsPhone, see if it works.</a>
</div>
<div class="ctrlHolder">
<label>Priority</label>
<select name="NMWP.priority" class="textInput large">
<option value="-2"${' selected="selected"' if config.get('NMWP', 'priority') == '-2' else ''}>Very Low</option>
<option value="-1"${' selected="selected"' if config.get('NMWP', 'priority') == '-1' else ''}>Moderate</option>
<option value="0"${' selected="selected"' if config.get('NMWP', 'priority') == '0' else ''}>Normal</option>
<option value="1"${' selected="selected"' if config.get('NMWP', 'priority') == '1' else ''}>High</option>
<option value="2"${' selected="selected"' if config.get('NMWP', 'priority') == '2' else ''}>Emergency</option>
</select>
</div>
</fieldset>
<fieldset class="inlineLabels" id="twitterFieldset">
<h3>Twitter</h3>
<div class="ctrlHolder checkbox">
<label>Enabled</label>
<input type="checkbox" name="Twitter.enabled" value="True" ${' checked="checked"' if config.get('Twitter', 'enabled') else ''} />
<p class="formHint">
Sends a notification on Twitter.
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Also on snatched</label>
<input type="checkbox" name="Twitter.onSnatch" value="True" ${' checked="checked"' if config.get('Twitter', 'onSnatch') else ''} />
<p class="formHint">
Also send a notification when a movie is snatched.
</p>
</div>
% if not config.get('Twitter', 'isAuthenticated'):
<div class"ctrlHolder">
<a href="${url(controller='config', action='twitterReqAuth')}" class="testNotification">Request Authorization</a>
</div>
% endif
<div class="ctrlHolder">
<a href="#twitterTest" id="twitterTest" class="testNotification">Send a notification on Twitter, see if it works.</a>
</div>
</fieldset>
<fieldset class="inlineLabels" id="synoIndexFieldset">
<h3>Synology Media Server</h3>
<div class="ctrlHolder checkbox">
<label>Enabled</label>
<input type="checkbox" name="Synoindex.enabled" value="True" ${' checked="checked"' if config.get('Synoindex', 'enabled') else ''} />
<p class="formHint">
Automaticly adds index to Synology Media Server.
</p>
</div>
<p class="ctrlHolder formHint">
This only works if CP is running on a Synology NAS.
</p>
</fieldset>
<fieldset class="inlineLabels" id="traktNotificationFieldset">
<h3>Trakt</h3>
<div class="ctrlHolder checkbox">
<label>Update library</label>
<input type="checkbox" name="Trakt.notification_enabled" value="True" ${' checked="checked"' if config.get('Trakt', 'notification_enabled') else ''} />
<p class="formHint">
Sends a notification and updates your Trakt library. You must fill out the username and password in the extras tab for this to work.
</p>
</div>
<div class="ctrlHolder checkbox">
<label>Remove from watchlist</label>
<input type="checkbox" name="Trakt.watchlist_remove" value="True" ${' checked="checked"' if config.get('Trakt', 'watchlist_remove') else ''} />
<p class="formHint">
Removes the downloaded movie from your Trakt watchlist.
</p>
</div>
</fieldset>
</div>
<div class="buttonHolder">
<span class="cancel"><a href="#cancel">Cancel</a> or</span>
<button type="submit" class="primaryAction">
Save »
</button>
</div>
</form>
</div>
<script type="text/javascript">
var form = $('configForm').getElement('form');
window.addEvent('domready', function(){
// Quality sorting and hiding
var sq = form.getElement('.standardQualities')
var saveQualityTemplateOrder = function(){
data = []
hide = []
sq.getElements('.item').each(function(el){
var checkbox = el.getElement('input[type=checkbox]')
var label = el.getElement('.label')
label.setStyle('opacity', 1)
data.append([el.get('data-id')])
if (!checkbox.get('checked')){
hide.append([el.get('data-name')])
label.setStyle('opacity', 0.6)
}
})
sq.getElement('input[name=Quality.order]').set('value', data)
sq.getElement('input[name=Quality.hide]').set('value', hide)
}
sq.getElements('.item input[type=checkbox]').addEvent('click', saveQualityTemplateOrder)
var qualitySortable = new Sortables(sq, {
'revert': true,
'clone': true,
'handle': '.handle',
'opacity': 0.5,
'onComplete': saveQualityTemplateOrder
});
saveQualityTemplateOrder()
var qt = form.getElement('.qualityTemplates')
<%
import json
types = json.dumps(dict([(v['order'], v) for k, v in Qualities.getTypes()]))
templates = json.dumps(Qualities.getTemplates())
%>
var q = new Quality(qt, ${types}, ${templates});
$('newTemplate').addEvent('click', function(e){
(e).stop()
q.add({
'id':0,
'name': 'New Quality',
'waitFor': 0,
'types': [{
'type':'720p',
'markComplete': true
}]
})
})
var showHideFileRenameOptionsLink = form.getElement('a[id=showHideFileRenameOptions]')
var toggleFileRenameOptions = function(){
var field = form.getElement('p[id=fileRenameOptions]')
if(field.getStyle('display') != 'none'){
field.setStyle('display', 'none')
showHideFileRenameOptionsLink.innerText = "Show naming-options"
}
else{
field.setStyle('display', 'block')
showHideFileRenameOptionsLink.innerText = "Hide naming-options"
}
}
showHideFileRenameOptionsLink.addEvent('click', toggleFileRenameOptions)
// Replace Userscript IE
if (Browser.ie){
form.getElement('.userscript fieldset a').setStyle('display', 'none')
}
// Get host and post with Userscript
var usButton = $('configForm').getElement('.userscriptInstall')
usButton.set('href', usButton.get('href')+'?host='+location.href.replace('config/', '')+'&type=CouchPotato.user.js')
// Match label to input, cause i'm lazy
form.getElements('label').each(function(el, nr){
if(!el.get('for')){
var id = 'formItem-'+nr
el.set('for', id)
el.getNext().set('id', id)
}
});
// Form highlight
new Uniform();
// Renaming disabled stuff
var isEnabled = function(checkbox, fieldset){
if (checkbox.get('checked'))
fieldset.getElements('.ctrlHolder').setStyle('opacity', 1)
else {
var first = fieldset.getElement('.ctrlHolder');
fieldset.getElements('.ctrlHolder').each(function(el){
if(el != first) el.setStyle('opacity', 0.5)
});
}
}
Array.each(['renamingFieldset','torrentsFieldset','nzbsFieldset','nzbmatrixFieldset','nzbsorgFieldset','newznabFieldset','subtitleFieldset', 'xbmcFieldset', 'nmjFieldset', 'plexFieldset', 'prowlFieldset', 'growlFieldset', 'notifoFieldset', 'boxcarFieldset', 'nmaFieldset', 'twitterFieldset', 'synoIndexFieldset', 'traktNotificationFieldset'],function(item){
var fieldset = $(item)
var checkbox = fieldset.getElement('[type=checkbox]')
isEnabled(checkbox, fieldset)
checkbox.addEvent('change', function(){
isEnabled(checkbox, fieldset)
});
})
// hide unused sendto for nzb
var sendToSelectnzb = $('nzbSendTo')
var sendTonzb = function(){
form.getElements('.sendTonzb').setStyle('display', 'none')
if (sendToSelectnzb.get('value') == 'Sabnzbd')
form.getElement('.sabnzbd').setStyle('display', 'block')
else if (sendToSelectnzb.get('value') == 'Nzbget')
form.getElement('.nzbget').setStyle('display', 'block')
else
form.getElement('.nzbblackhole').setStyle('display', 'block')
}
sendToSelectnzb.addEvent('change', sendTonzb);
sendTonzb();
// hide unused sendto for torrents
var sendToSelecttorrents = $('torrentsSendTo')
var sendTotorrents = function(){
form.getElements('.sendTotorrents').setStyle('display', 'none')
if (sendToSelecttorrents.get('value') == 'Transmission')
form.getElement('.transmission').setStyle('display', 'block')
else
form.getElement('.torrentsblackhole').setStyle('display', 'block')
}
sendToSelecttorrents.addEvent('change', sendTotorrents);
sendTotorrents();
// Cancel button
form.getElements('.cancel a').addEvent('click', function(e){
(e).stop()
history.back();
});
// Shutdown button
form.getElements('.about a.submit').addEvent('click', function(e){
(e).stop()
new Spinner(e.target).show();
new Request({
'url': e.target.get('href'),
'onComplete': function(){
if (e.target.get('text') == 'Restart')
e.target.getParent().set('text', 'CouchPotato will restart in a few seconds.')
else
e.target.getParent().set('text', 'CouchPotato has shutdown.')
new Spinner(e.target).hide();
}
}).send()
});
// Menu
$('configForm').getElements('ul a').addEvent('click', function(e){
(e).stop()
showForm(e.target, e.target.get('href').substr(1))
});
var showForm = function(el, name){
form.getElements('.group').removeClass('current')
form.getElements('.group.'+name).addClass('current')
$('configForm').getElements('ul a').removeClass('current');
el.addClass('current');
}
var firstItem = $('configForm').getElement('ul li:last-child a');
showForm(firstItem, firstItem.get('href').substr(1));
$('xbmcTest').addEvent('click', function(e){
(e).stop()
new Request({
'url': './testXBMC/',
'data': $('xbmcFieldset')
}).send()
})
$('plexTest').addEvent('click', function(e){
(e).stop()
new Request({
'url': './testPLEX/',
'data': $('plexFieldset')
}).send()
})
$('prowlTest').addEvent('click', function(e){
(e).stop()
new Request({
'url': './testPROWL/',
'data': $('prowlFieldset')
}).send()
})
$('growlTest').addEvent('click', function(e){
(e).stop()
new Request({
'url': './testGROWL/',
'data': $('growlFieldset')
}).send()
})
$('notifoTest').addEvent('click', function(e){
(e).stop()
new Request({
'url': './testNotifo/',
'data': $('notifoFieldset')
}).send()
})
$('boxcarTest').addEvent('click', function(e){
(e).stop()
new Request({
'url': './testBoxcar/',
'data': $('boxcarFieldset')
}).send()
})
$('nmjTest').addEvent('click', function(e){
(e).stop()
new Request({
'url': './testNMJ/',
'data': $('nmjFieldset')
}).send()
})
$('nmjAuto').addEvent('click', function(e){
(e).stop()
if (form.getElement('.NMJhost').value == '') {
alert('Please fill in the Popcorn Hour IP address');
form.getElement('.NMJhost').focus();
return
}
new Request.JSON({
url: './autoNMJ/',
onComplete: function(response){
if (response == null) return
form.getElement('.NMJdatabase').value = response.database;
form.getElement('.NMJmount').value = response.mount;
},
data: $('nmjFieldset')
}).send()
})
$('nmaTest').addEvent('click',function(e){
(e).stop()
new Request({
'url': './testNMA/',
'data': $('nmaFieldset')
}).send()
})
$('nmwpTest').addEvent('click',function(e){
(e).stop()
new Request({
'url': './testNMWP/',
'data': $('nmwpFieldset')
}).send()
})
$('twitterTest').addEvent('click',function(e){
(e).stop()
new Request({
'url': './testTwitter/',
'data': $('twitterFieldset')
}).send()
})
$('traktTest').addEvent('click', function(e){
(e).stop()
new Request({
'url': './testTrakt/',
'data': $('traktFieldset')
}).send()
})
});
</script>
<%inherit file="/base.html" />
| RuudBurger/CouchPotatoV1 | app/views/config/index.html | HTML | gpl-3.0 | 60,663 |
<?php
require_once($GLOBALS['g_campsiteDir'].'/classes/Input.php');
require_once($GLOBALS['g_campsiteDir'].'/classes/Attachment.php');
require_once($GLOBALS['g_campsiteDir'].'/classes/Log.php');
require_once LIBS_DIR . '/MediaList/MediaList.php';
require_once LIBS_DIR . '/MediaPlayer/MediaPlayer.php';
$f_attachment_id = Input::Get('f_attachment_id', 'int', 0);
$translator = \Zend_Registry::get('container')->getService('translator');
if (!Input::IsValid()) {
camp_html_goto_page("/$ADMIN/media-archive/index.php#files");
}
$em = \Zend_Registry::get('container')->getService('em');
$attachment = $em->getRepository('Newscoop\Entity\Attachment')->findOneById($f_attachment_id);
$attachmentService = \Zend_Registry::get('container')->getService('attachment');
$label_text = '';
$crumbs = array();
$crumbs[] = array($translator->trans('Content'), "");
$crumbs[] = array($translator->trans('Media Archive', array(), 'home'), "/$ADMIN/media-archive/index.php#files");
if ($g_user->hasPermission('ChangeImage')) {
$label_text = $translator->trans('Change attachment information', array(), 'media_archive');
}
else {
$label_text = $translator->trans('View attachment', array(), 'media_archive');
}
$crumbs[] = array($label_text, '');
$breadcrumbs = camp_html_breadcrumbs($crumbs);
$controller->view->headTitle($label_text.' - Newscoop Admin', 'SET');
echo $breadcrumbs;
?>
<?php camp_html_display_msgs(); ?>
<div class="wrapper"><div class="main-content-wrapper">
<h2><?php echo $attachment->getName(); ?></h2>
<p class="dates"><?php echo $translator->trans('Created', array(), 'media_archive'); ?>: <?php echo $attachment->getCreated()->format('Y-m-d H:i:s'); ?>, <?php echo $translator->trans('Last modified', array(), 'media_archive'); ?>: <?php echo $attachment->getUpdated()->format('Y-m-d H:i:s'); ?></p>
<?php echo new MediaPlayer($attachmentService->getAttachmentUrl($attachment) . '?g_show_in_browser=1', $attachment->getMimeType()); ?>
<dl class="attachment">
<dt><?php echo $translator->trans('Type'); ?>:</dt>
<dd><?php echo $attachment->getMimeType(); ?></dd>
<dt><?php echo $translator->trans('Size', array(), 'media_archive'); ?>:</dt>
<dd><?php echo MediaList::FormatFileSize($attachment->getSizeInBytes()); ?></dd>
<?php if ($attachment->getHttpCharset()) { ?>
<dt><?php echo $translator->trans('Charset', array(), 'media_archive'); ?>:</dt>
<dd><?php echo $attachment->getHttpCharset(); ?></dd>
<?php } ?>
</dl>
<form name="edit" method="POST" action="/<?php echo $ADMIN; ?>/media-archive/do_edit-attachment.php">
<?php echo SecurityToken::FormParameter(); ?>
<input type="hidden" name="f_attachment_id" value="<?php echo $attachment->getId(); ?>" />
<div class="ui-widget-content big-block block-shadow padded-strong">
<fieldset class="plain">
<legend><?php echo $translator->trans('Change attachment information', array(), 'media_archive'); ?></legend>
<ul>
<li>
<label for="description"><?php echo $translator->trans("Description"); ?>:</label>
<input id="description" type="text" name="f_description" value="<?php echo htmlspecialchars($attachment->getDescription()); ?>" size="50" maxlength="255" class="input_text" />
</li>
<li>
<label><?php echo $translator->trans("Do you want this file to open in the users browser, or to automatically download?", array(), 'media_archive'); ?></label>
<input id="disposition0" class="input_radio" type="radio" name="f_content_disposition" value=""<?php if ($attachment->getContentDisposition() == NULL) { echo ' checked="checked"'; } ?> />
<label for="disposition0" class="inline-style left-floated" style="padding-right:15px"><?php echo $translator->trans("Open in the browser", array(), 'media_archive'); ?></label>
<input id="disposition1" class="input_radio" type="radio" name="f_content_disposition" value="attachment"<?php if ($attachment->getContentDisposition() == 'attachment') { echo ' checked="checked"'; } ?> />
<label for="disposition1" class="inline-style left-floated"><?php echo $translator->trans("Automatically download", array(), 'media_archive'); ?></label>
</li>
<li>
<label> </label>
<input type="submit" name="Save" value="<?php echo $translator->trans('Save'); ?>" class="button" />
</li>
</ul>
</fieldset>
</div>
</form>
</div></div><!-- /.main-content-wrapper /.wrapper -->
<?php camp_html_copyright_notice(); ?>
</body>
</html>
| danielhjames/Newscoop | newscoop/admin-files/media-archive/edit-attachment.php | PHP | gpl-3.0 | 4,566 |
-----------------------------------
-- Area: Qu'Bia Arena
-- NPC: Those Who Lurk in Shadows
-- !pos -221 -24 19 206
-----------------------------------
package.loaded["scripts/zones/QuBia_Arena/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/QuBia_Arena/TextIDs");
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if (player:hasKeyItem(MARK_OF_SEED)) then
player:delKeyItem(MARK_OF_SEED);
end
if (leavecode == 2) then -- Play end CS. Need time and battle id for record keeping + storage
player:addExp(700);
if (player:getCurrentMission(ACP) == THOSE_WHO_LURK_IN_SHADOWS_III) then
player:startEvent(32001,1,1,1,instance:getTimeInside(),1,20,0);
else -- Gives skip dialog if previously completed
player:startEvent(32001,1,1,1,instance:getTimeInside(),1,20,1);
end
elseif (leavecode == 4) then
player:startEvent(32002);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if (csid == 32001) then
if (player:getCurrentMission(ACP) == THOSE_WHO_LURK_IN_SHADOWS_III) then
player:completeMission(ACP,THOSE_WHO_LURK_IN_SHADOWS_III);
player:addMission(ACP,REMEMBER_ME_IN_YOUR_DREAMS);
end
if (player:hasKeyItem(IVORY_KEY) == false and player:getCurrentMission(ACP) >= THOSE_WHO_LURK_IN_SHADOWS_III) then
player:addKeyItem(IVORY_KEY);
player:setVar("LastIvoryKey", os.date("%j"));
player:messageSpecial(KEYITEM_OBTAINED,IVORY_KEY);
end
end
end; | Whitechaser/darkstar | scripts/zones/QuBia_Arena/bcnms/those_who_lurk_in_shadows.lua | Lua | gpl-3.0 | 2,390 |
#pragma once
#include "ASyncTCP.h"
#include "P1MeterBase.h"
class P1MeterTCP : public P1MeterBase, ASyncTCP
{
public:
P1MeterTCP(int ID, const std::string &IPAddress, unsigned short usIPPort, bool disable_crc, int ratelimit, const std::string &DecryptionKey);
~P1MeterTCP() override = default;
bool WriteToHardware(const char *pdata, unsigned char length) override;
public:
// signals
boost::signals2::signal<void()> sDisconnected;
private:
bool StartHardware() override;
bool StopHardware() override;
protected:
std::string m_szIPAddress;
unsigned short m_usIPPort;
void Do_Work();
void OnConnect() override;
void OnDisconnect() override;
void OnData(const unsigned char *pData, size_t length) override;
void OnError(const boost::system::error_code &error) override;
std::shared_ptr<std::thread> m_thread;
};
| domoticz/domoticz | hardware/P1MeterTCP.h | C | gpl-3.0 | 857 |
/* Copyright (C) 2015-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C 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.
The GNU C 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 the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <nss.h>
#include <string.h>
const char __nss_invalid_field_characters[] = NSS_INVALID_FIELD_CHARACTERS;
/* Check that VALUE is either NULL or a NUL-terminated string which
does not contain characters not permitted in NSS database
fields. */
_Bool
internal_function
__nss_valid_field (const char *value)
{
return value == NULL
|| strpbrk (value, __nss_invalid_field_characters) == NULL;
}
| geminy/aidear | oss/glibc/glibc-2.24/nss/valid_field.c | C | gpl-3.0 | 1,201 |
/*
Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
See the file copying.txt for copying permission.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include "xmlrpc_config.h"
#include "xmlparse.h"
#include "codepage.h"
#include "xmlfile.h"
#include "xmltchar.h"
#if MSVCRT
#include <crtdbg.h>
#endif
/* This ensures proper sorting. */
#define NSSEP T('\001')
static void characterData(void *userData, const XML_Char *s, int len)
{
FILE *fp = userData;
for (; len > 0; --len, ++s) {
switch (*s) {
case T('&'):
fputts(T("&"), fp);
break;
case T('<'):
fputts(T("<"), fp);
break;
case T('>'):
fputts(T(">"), fp);
break;
#ifdef W3C14N
case 13:
fputts(T("
"), fp);
break;
#else
case T('"'):
fputts(T("""), fp);
break;
case 9:
case 10:
case 13:
ftprintf(fp, T("&#%d;"), *s);
break;
#endif
default:
puttc(*s, fp);
break;
}
}
}
static void attributeValue(FILE *fp, const XML_Char *s)
{
puttc(T('='), fp);
puttc(T('"'), fp);
for (;;) {
switch (*s) {
case 0:
case NSSEP:
puttc(T('"'), fp);
return;
case T('&'):
fputts(T("&"), fp);
break;
case T('<'):
fputts(T("<"), fp);
break;
case T('"'):
fputts(T("""), fp);
break;
#ifdef W3C14N
case 9:
fputts(T("	"), fp);
break;
case 10:
fputts(T("
"), fp);
break;
case 13:
fputts(T("
"), fp);
break;
#else
case T('>'):
fputts(T(">"), fp);
break;
case 9:
case 10:
case 13:
ftprintf(fp, T("&#%d;"), *s);
break;
#endif
default:
puttc(*s, fp);
break;
}
s++;
}
}
/* Lexicographically comparing UTF-8 encoded attribute values,
is equivalent to lexicographically comparing based on the character number. */
static int attcmp(const void *att1, const void *att2)
{
return tcscmp(*(const XML_Char **)att1, *(const XML_Char **)att2);
}
static void startElement(void *userData, const XML_Char *name, const XML_Char **atts)
{
int nAtts;
const XML_Char **p;
FILE *fp = userData;
puttc(T('<'), fp);
fputts(name, fp);
p = atts;
while (*p)
++p;
nAtts = (p - atts) >> 1;
if (nAtts > 1)
qsort((void *)atts, nAtts, sizeof(XML_Char *) * 2, attcmp);
while (*atts) {
puttc(T(' '), fp);
fputts(*atts++, fp);
attributeValue(fp, *atts);
atts++;
}
puttc(T('>'), fp);
}
static void endElement(void *userData, const XML_Char *name)
{
FILE *fp = userData;
puttc(T('<'), fp);
puttc(T('/'), fp);
fputts(name, fp);
puttc(T('>'), fp);
}
static int nsattcmp(const void *p1, const void *p2)
{
const XML_Char *att1 = *(const XML_Char **)p1;
const XML_Char *att2 = *(const XML_Char **)p2;
int sep1 = (tcsrchr(att1, NSSEP) != 0);
int sep2 = (tcsrchr(att1, NSSEP) != 0);
if (sep1 != sep2)
return sep1 - sep2;
return tcscmp(att1, att2);
}
static void startElementNS(void *userData, const XML_Char *name, const XML_Char **atts)
{
int nAtts;
int nsi;
const XML_Char **p;
FILE *fp = userData;
const XML_Char *sep;
puttc(T('<'), fp);
sep = tcsrchr(name, NSSEP);
if (sep) {
fputts(T("n1:"), fp);
fputts(sep + 1, fp);
fputts(T(" xmlns:n1"), fp);
attributeValue(fp, name);
nsi = 2;
}
else {
fputts(name, fp);
nsi = 1;
}
p = atts;
while (*p)
++p;
nAtts = (p - atts) >> 1;
if (nAtts > 1)
qsort((void *)atts, nAtts, sizeof(XML_Char *) * 2, nsattcmp);
while (*atts) {
name = *atts++;
sep = tcsrchr(name, NSSEP);
puttc(T(' '), fp);
if (sep) {
ftprintf(fp, T("n%d:"), nsi);
fputts(sep + 1, fp);
}
else
fputts(name, fp);
attributeValue(fp, *atts);
if (sep) {
ftprintf(fp, T(" xmlns:n%d"), nsi++);
attributeValue(fp, name);
}
atts++;
}
puttc(T('>'), fp);
}
static void endElementNS(void *userData, const XML_Char *name)
{
FILE *fp = userData;
const XML_Char *sep;
puttc(T('<'), fp);
puttc(T('/'), fp);
sep = tcsrchr(name, NSSEP);
if (sep) {
fputts(T("n1:"), fp);
fputts(sep + 1, fp);
}
else
fputts(name, fp);
puttc(T('>'), fp);
}
#ifndef W3C14N
static void processingInstruction(void *userData, const XML_Char *target, const XML_Char *data)
{
FILE *fp = userData;
puttc(T('<'), fp);
puttc(T('?'), fp);
fputts(target, fp);
puttc(T(' '), fp);
fputts(data, fp);
puttc(T('?'), fp);
puttc(T('>'), fp);
}
#endif /* not W3C14N */
static void defaultCharacterData(XML_Parser parser, const XML_Char *s, int len)
{
XML_DefaultCurrent(parser);
}
static void defaultStartElement(XML_Parser parser, const XML_Char *name, const XML_Char **atts)
{
XML_DefaultCurrent(parser);
}
static void defaultEndElement(XML_Parser parser, const XML_Char *name)
{
XML_DefaultCurrent(parser);
}
static void defaultProcessingInstruction(XML_Parser parser, const XML_Char *target, const XML_Char *data)
{
XML_DefaultCurrent(parser);
}
static void nopCharacterData(XML_Parser parser, const XML_Char *s, int len)
{
}
static void nopStartElement(XML_Parser parser, const XML_Char *name, const XML_Char **atts)
{
}
static void nopEndElement(XML_Parser parser, const XML_Char *name)
{
}
static void nopProcessingInstruction(XML_Parser parser, const XML_Char *target, const XML_Char *data)
{
}
static void markup(XML_Parser parser, const XML_Char *s, int len)
{
FILE *fp = XML_GetUserData(parser);
for (; len > 0; --len, ++s)
puttc(*s, fp);
}
static
void metaLocation(XML_Parser parser)
{
const XML_Char *uri = XML_GetBase(parser);
if (uri)
ftprintf(XML_GetUserData(parser), T(" uri=\"%s\""), uri);
ftprintf(XML_GetUserData(parser),
T(" byte=\"%ld\" nbytes=\"%d\" line=\"%d\" col=\"%d\""),
XML_GetCurrentByteIndex(parser),
XML_GetCurrentByteCount(parser),
XML_GetCurrentLineNumber(parser),
XML_GetCurrentColumnNumber(parser));
}
static
void metaStartDocument(XML_Parser parser)
{
fputts(T("<document>\n"), XML_GetUserData(parser));
}
static
void metaEndDocument(XML_Parser parser)
{
fputts(T("</document>\n"), XML_GetUserData(parser));
}
static
void metaStartElement(XML_Parser parser, const XML_Char *name, const XML_Char **atts)
{
FILE *fp = XML_GetUserData(parser);
const XML_Char **specifiedAttsEnd
= atts + XML_GetSpecifiedAttributeCount(parser);
const XML_Char **idAttPtr;
int idAttIndex = XML_GetIdAttributeIndex(parser);
if (idAttIndex < 0)
idAttPtr = 0;
else
idAttPtr = atts + idAttIndex;
ftprintf(fp, T("<starttag name=\"%s\""), name);
metaLocation(parser);
if (*atts) {
fputts(T(">\n"), fp);
do {
ftprintf(fp, T("<attribute name=\"%s\" value=\""), atts[0]);
characterData(fp, atts[1], tcslen(atts[1]));
if (atts >= specifiedAttsEnd)
fputts(T("\" defaulted=\"yes\"/>\n"), fp);
else if (atts == idAttPtr)
fputts(T("\" id=\"yes\"/>\n"), fp);
else
fputts(T("\"/>\n"), fp);
} while (*(atts += 2));
fputts(T("</starttag>\n"), fp);
}
else
fputts(T("/>\n"), fp);
}
static
void metaEndElement(XML_Parser parser, const XML_Char *name)
{
FILE *fp = XML_GetUserData(parser);
ftprintf(fp, T("<endtag name=\"%s\""), name);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void metaProcessingInstruction(XML_Parser parser, const XML_Char *target, const XML_Char *data)
{
FILE *fp = XML_GetUserData(parser);
ftprintf(fp, T("<pi target=\"%s\" data=\""), target);
characterData(fp, data, tcslen(data));
puttc(T('"'), fp);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void metaComment(XML_Parser parser, const XML_Char *data)
{
FILE *fp = XML_GetUserData(parser);
fputts(T("<comment data=\""), fp);
characterData(fp, data, tcslen(data));
puttc(T('"'), fp);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void metaStartCdataSection(XML_Parser parser)
{
FILE *fp = XML_GetUserData(parser);
fputts(T("<startcdata"), fp);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void metaEndCdataSection(XML_Parser parser)
{
FILE *fp = XML_GetUserData(parser);
fputts(T("<endcdata"), fp);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void metaCharacterData(XML_Parser parser, const XML_Char *s, int len)
{
FILE *fp = XML_GetUserData(parser);
fputts(T("<chars str=\""), fp);
characterData(fp, s, len);
puttc(T('"'), fp);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void metaStartDoctypeDecl(XML_Parser parser, const XML_Char *doctypeName)
{
FILE *fp = XML_GetUserData(parser);
ftprintf(fp, T("<startdoctype name=\"%s\""), doctypeName);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void metaEndDoctypeDecl(XML_Parser parser)
{
FILE *fp = XML_GetUserData(parser);
fputts(T("<enddoctype"), fp);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void metaUnparsedEntityDecl(XML_Parser parser,
const XML_Char *entityName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId,
const XML_Char *notationName)
{
FILE *fp = XML_GetUserData(parser);
ftprintf(fp, T("<entity name=\"%s\""), entityName);
if (publicId)
ftprintf(fp, T(" public=\"%s\""), publicId);
fputts(T(" system=\""), fp);
characterData(fp, systemId, tcslen(systemId));
puttc(T('"'), fp);
ftprintf(fp, T(" notation=\"%s\""), notationName);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void metaNotationDecl(XML_Parser parser,
const XML_Char *notationName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId)
{
FILE *fp = XML_GetUserData(parser);
ftprintf(fp, T("<notation name=\"%s\""), notationName);
if (publicId)
ftprintf(fp, T(" public=\"%s\""), publicId);
if (systemId) {
fputts(T(" system=\""), fp);
characterData(fp, systemId, tcslen(systemId));
puttc(T('"'), fp);
}
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void metaExternalParsedEntityDecl(XML_Parser parser,
const XML_Char *entityName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId)
{
FILE *fp = XML_GetUserData(parser);
ftprintf(fp, T("<entity name=\"%s\""), entityName);
if (publicId)
ftprintf(fp, T(" public=\"%s\""), publicId);
fputts(T(" system=\""), fp);
characterData(fp, systemId, tcslen(systemId));
puttc(T('"'), fp);
metaLocation(parser);
fputts(T("/>\n"), fp);
}
static
void metaInternalParsedEntityDecl(XML_Parser parser,
const XML_Char *entityName,
const XML_Char *text,
int textLen)
{
FILE *fp = XML_GetUserData(parser);
ftprintf(fp, T("<entity name=\"%s\""), entityName);
metaLocation(parser);
puttc(T('>'), fp);
characterData(fp, text, textLen);
fputts(T("</entity/>\n"), fp);
}
static
void metaStartNamespaceDecl(XML_Parser parser,
const XML_Char *prefix,
const XML_Char *uri)
{
FILE *fp = XML_GetUserData(parser);
fputts(T("<startns"), fp);
if (prefix)
ftprintf(fp, T(" prefix=\"%s\""), prefix);
if (uri) {
fputts(T(" ns=\""), fp);
characterData(fp, uri, tcslen(uri));
fputts(T("\"/>\n"), fp);
}
else
fputts(T("/>\n"), fp);
}
static
void metaEndNamespaceDecl(XML_Parser parser, const XML_Char *prefix)
{
FILE *fp = XML_GetUserData(parser);
if (!prefix)
fputts(T("<endns/>\n"), fp);
else
ftprintf(fp, T("<endns prefix=\"%s\"/>\n"), prefix);
}
static
int unknownEncodingConvert(void *data, const char *p)
{
return codepageConvert(*(int *)data, p);
}
static
int unknownEncoding(void *userData,
const XML_Char *name,
XML_Encoding *info)
{
int cp;
static const XML_Char prefixL[] = T("windows-");
static const XML_Char prefixU[] = T("WINDOWS-");
int i;
for (i = 0; prefixU[i]; i++)
if (name[i] != prefixU[i] && name[i] != prefixL[i])
return 0;
cp = 0;
for (; name[i]; i++) {
static const XML_Char digits[] = T("0123456789");
const XML_Char *s = tcschr(digits, name[i]);
if (!s)
return 0;
cp *= 10;
cp += s - digits;
if (cp >= 0x10000)
return 0;
}
if (!codepageMap(cp, info->map))
return 0;
info->convert = unknownEncodingConvert;
/* We could just cast the code page integer to a void *,
and avoid the use of release. */
info->release = free;
info->data = malloc(sizeof(int));
if (!info->data)
return 0;
*(int *)info->data = cp;
return 1;
}
static
int notStandalone(void *userData)
{
return 0;
}
static
void usage(const XML_Char *prog)
{
ftprintf(stderr, T("usage: %s [-n] [-p] [-r] [-s] [-w] [-x] [-d output-dir] [-e encoding] file ...\n"), prog);
exit(1);
}
int tmain(int argc, XML_Char **argv)
{
int i, j;
const XML_Char *outputDir = 0;
const XML_Char *encoding = 0;
unsigned processFlags = XML_MAP_FILE;
int windowsCodePages = 0;
int outputType = 0;
int useNamespaces = 0;
int requireStandalone = 0;
int paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
#if MSVCRT
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);
#endif
i = 1;
j = 0;
while (i < argc) {
if (j == 0) {
if (argv[i][0] != T('-'))
break;
if (argv[i][1] == T('-') && argv[i][2] == T('\0')) {
i++;
break;
}
j++;
}
switch (argv[i][j]) {
case T('r'):
processFlags &= ~XML_MAP_FILE;
j++;
break;
case T('s'):
requireStandalone = 1;
j++;
break;
case T('n'):
useNamespaces = 1;
j++;
break;
case T('p'):
paramEntityParsing = XML_PARAM_ENTITY_PARSING_ALWAYS;
/* fall through */
case T('x'):
processFlags |= XML_EXTERNAL_ENTITIES;
j++;
break;
case T('w'):
windowsCodePages = 1;
j++;
break;
case T('m'):
outputType = 'm';
j++;
break;
case T('c'):
outputType = 'c';
useNamespaces = 0;
j++;
break;
case T('t'):
outputType = 't';
j++;
break;
case T('d'):
if (argv[i][j + 1] == T('\0')) {
if (++i == argc)
usage(argv[0]);
outputDir = argv[i];
}
else
outputDir = argv[i] + j + 1;
i++;
j = 0;
break;
case T('e'):
if (argv[i][j + 1] == T('\0')) {
if (++i == argc)
usage(argv[0]);
encoding = argv[i];
}
else
encoding = argv[i] + j + 1;
i++;
j = 0;
break;
case T('\0'):
if (j > 1) {
i++;
j = 0;
break;
}
/* fall through */
default:
usage(argv[0]);
}
}
if (i == argc)
usage(argv[0]);
for (; i < argc; i++) {
FILE *fp = 0;
XML_Char *outName = 0;
int result;
XML_Parser parser;
if (useNamespaces)
parser = XML_ParserCreateNS(encoding, NSSEP);
else
parser = XML_ParserCreate(encoding);
if (requireStandalone)
XML_SetNotStandaloneHandler(parser, notStandalone);
XML_SetParamEntityParsing(parser, paramEntityParsing);
if (outputType == 't') {
/* This is for doing timings; this gives a more realistic estimate of
the parsing time. */
outputDir = 0;
XML_SetElementHandler(parser, nopStartElement, nopEndElement);
XML_SetCharacterDataHandler(parser, nopCharacterData);
XML_SetProcessingInstructionHandler(parser, nopProcessingInstruction);
}
else if (outputDir) {
const XML_Char *file = argv[i];
if (tcsrchr(file, T('/')))
file = tcsrchr(file, T('/')) + 1;
#if MSVCRT
if (tcsrchr(file, T('\\')))
file = tcsrchr(file, T('\\')) + 1;
#endif
outName = malloc((tcslen(outputDir) + tcslen(file) + 2) * sizeof(XML_Char));
tcscpy(outName, outputDir);
tcscat(outName, T("/"));
tcscat(outName, file);
fp = tfopen(outName, T("wb"));
if (!fp) {
tperror(outName);
exit(1);
}
setvbuf(fp, NULL, _IOFBF, 16384);
#ifdef XML_UNICODE
puttc(0xFEFF, fp);
#endif
XML_SetUserData(parser, fp);
switch (outputType) {
case 'm':
XML_UseParserAsHandlerArg(parser);
XML_SetElementHandler(parser, metaStartElement, metaEndElement);
XML_SetProcessingInstructionHandler(parser, metaProcessingInstruction);
XML_SetCommentHandler(parser, metaComment);
XML_SetCdataSectionHandler(parser, metaStartCdataSection, metaEndCdataSection);
XML_SetCharacterDataHandler(parser, metaCharacterData);
XML_SetDoctypeDeclHandler(parser, metaStartDoctypeDecl, metaEndDoctypeDecl);
XML_SetUnparsedEntityDeclHandler(parser, metaUnparsedEntityDecl);
XML_SetNotationDeclHandler(parser, metaNotationDecl);
XML_SetExternalParsedEntityDeclHandler(parser, metaExternalParsedEntityDecl);
XML_SetInternalParsedEntityDeclHandler(parser, metaInternalParsedEntityDecl);
XML_SetNamespaceDeclHandler(parser, metaStartNamespaceDecl, metaEndNamespaceDecl);
metaStartDocument(parser);
break;
case 'c':
XML_UseParserAsHandlerArg(parser);
XML_SetDefaultHandler(parser, markup);
XML_SetElementHandler(parser, defaultStartElement, defaultEndElement);
XML_SetCharacterDataHandler(parser, defaultCharacterData);
XML_SetProcessingInstructionHandler(parser, defaultProcessingInstruction);
break;
default:
if (useNamespaces)
XML_SetElementHandler(parser, startElementNS, endElementNS);
else
XML_SetElementHandler(parser, startElement, endElement);
XML_SetCharacterDataHandler(parser, characterData);
#ifndef W3C14N
XML_SetProcessingInstructionHandler(parser, processingInstruction);
#endif /* not W3C14N */
break;
}
}
if (windowsCodePages)
XML_SetUnknownEncodingHandler(parser, unknownEncoding, 0);
result = XML_ProcessFile(parser, argv[i], processFlags);
if (outputDir) {
if (outputType == 'm')
metaEndDocument(parser);
fclose(fp);
if (!result)
tremove(outName);
free(outName);
}
XML_ParserFree(parser);
}
return 0;
}
| JMSDOnline/QuickBox | xmlrpc-c_1-39-07/lib/expat/xmlwf/xmlwf.c | C | gpl-3.0 | 17,924 |
<?php
/**
* Hoa
*
*
* @license
*
* New BSD License
*
* Copyright © 2007-2017, Hoa community. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Hoa nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND 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.
*/
namespace Hoa\Stream\Wrapper;
use Hoa\Stream;
/**
* Class \Hoa\Stream\Wrapper\Exception.
*
* Extending the \Hoa\Stream\Exception class.
*
* @copyright Copyright © 2007-2017 Hoa community
* @license New BSD License
*/
class Exception extends Stream\Exception
{
}
| collectiveaccess/providence | vendor/hoa/stream/Wrapper/Exception.php | PHP | gpl-3.0 | 1,926 |
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Google_Service_CloudKMS_AsymmetricSignResponse extends Google_Model
{
public $name;
public $signature;
public $signatureCrc32c;
public $verifiedDigestCrc32c;
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setSignature($signature)
{
$this->signature = $signature;
}
public function getSignature()
{
return $this->signature;
}
public function setSignatureCrc32c($signatureCrc32c)
{
$this->signatureCrc32c = $signatureCrc32c;
}
public function getSignatureCrc32c()
{
return $this->signatureCrc32c;
}
public function setVerifiedDigestCrc32c($verifiedDigestCrc32c)
{
$this->verifiedDigestCrc32c = $verifiedDigestCrc32c;
}
public function getVerifiedDigestCrc32c()
{
return $this->verifiedDigestCrc32c;
}
}
| ftisunpar/BlueTape | vendor/google/apiclient-services/src/Google/Service/CloudKMS/AsymmetricSignResponse.php | PHP | gpl-3.0 | 1,469 |
#ifndef __LV2_STORAGE_H__
#define __LV2_STORAGE_H__
#include <stdint.h>
#include <lv2/lv2.h>
#include <lv1/lv1.h>
/* Devices */
#define ATA_HDD 0x101000000000007
#define BDVD_DRIVE 0x101000000000006
#define PATA0_HDD_DRIVE 0x101000000000008
#define PATA0_BDVD_DRIVE BDVD_DRIVE
#define PATA1_HDD_DRIVE ATA_HDD
#define BUILTIN_FLASH 0x100000000000001
#define NAND_FLASH BUILTIN_FLASH
#define NOR_FLASH 0x100000000000004
#define MEMORY_STICK 0x103000000000010
#define SD_CARD 0x103000100000010
#define COMPACT_FLASH 0x103000200000010
#define USB_MASS_STORAGE_1(n) (0x10300000000000A+n) /* For 0-5 */
#define USB_MASS_STORAGE_2(n) (0x10300000000001F+(n-6)) /* For 6-127 */
#define HDD_PARTITION(n) (ATA_HDD | (n<<32))
#define FLASH_PARTITION(n) (BUILTIN_FLASH | (n<<32))
/* Commands for storage_send_device_command */
#define STORAGE_COMMAND_NATIVE 0x01
#define STORAGE_COMMAND_GET_DEVICE_SIZE 0x10
#define STORAGE_COMMAND_GET_DEVICE_TYPE 0x11
/* Device types returned by STORAGE_COMMAND_GET_DEVICE_TYPE and some scsi commands */
#define DEVICE_TYPE_PS3_DVD 0xFF70
#define DEVICE_TYPE_PS3_BD 0xFF71
#define DEVICE_TYPE_PS2_CD 0xFF60
#define DEVICE_TYPE_PS2_DVD 0xFF61
#define DEVICE_TYPE_PSX_CD 0xFF50
#define DEVICE_TYPE_BDROM 0x40
#define DEVICE_TYPE_BDMR_SR 0x41 /* Sequential record */
#define DEVICE_TYPE_BDMR_RR 0x42 /* Random record */
#define DEVICE_TYPE_BDMRE 0x43
#define DEVICE_TYPE_DVD 0x10 /* DVD-ROM, DVD+-R, DVD+-RW etc, they are differenced by booktype field in some scsi command */
#define DEVICE_TYPE_CD 0x08 /* CD-ROM, CD-DA, CD-R, CD-RW, etc, they are differenced somehow with scsi commands */
typedef uint32_t device_handle_t; // Kernel
typedef uint32_t sys_device_handle_t; // User
typedef struct
{
char *label; // 0
uint32_t unk_08; // 8 0xB8 0x90
uint32_t unk_0C; // 0x0C 0xBC 0x94
uint64_t unk_10; // 0x10 not copied in sys_storage_get_device_info 0xC0 unused
uint64_t sector_count; // 0x18 0xC8 0x98
uint32_t sector_size; // 0x20 0xD0 0xA0
uint32_t unk_24; // 0x24 not copied in sys_storage_get_device_info 0xD4 unused
uint32_t unk_28; // 0x28 not copied in sys_storage_get_device_info 0xD8 unused
uint32_t unk_2C; // 0x2C not copied in sys_storage_get_device_info 0xDC unused
uint32_t unk_30; // 0x30 0xE0 0xA4
uint32_t unk_34; // 0x34 not copied in sys_storage_get_device_info 0xE4 unused
uint64_t unk_38; // 0x38 not copied in sys_storage_get_device_info 0xE8 unused
uint8_t unk_40[8]; // 0x40 0xF0 0xA8
} __attribute__((packed)) device_info_t;
typedef struct
{
uint32_t inlen;
uint32_t unk1;
uint32_t outlen;
uint32_t unk2;
uint32_t unk3;
} __attribute__((packed)) StorageCmdScsiData;
LV2_EXPORT int storage_get_device_info(uint64_t device_id, device_info_t *device_info);
LV2_EXPORT int storage_get_device_config(int *unk, int *unk2);
// storage_open(0x0101000000000006, 0, &device_handle, 0); // dev_bdvd
LV2_EXPORT int storage_open(uint64_t device_id, uint64_t unk, device_handle_t *device_handle, uint64_t unk2);
LV2_EXPORT int storage_close(device_handle_t device_handle);
// storage_read(3, 0, 0x220, 0x10, buf, &nread, 4); // flash?
// storage_read(0x13, 0, 0x030761E0, 0x80, buf, &nread, 0); // hdd
// storage_read(0x24, 0, 0x3C01, 0x20, buf, &nread, 4); // usb. Raw sector, not partition one.
// storage_read(0x41, 0, 0x10, 0x10, buf, &nread, 0); // dev_bdvd
LV2_EXPORT int storage_read(device_handle_t device_handle, uint64_t unk, uint64_t start_sector, uint32_t sector_count, void *buf, uint32_t *nread, uint64_t flags);
LV2_EXPORT int storage_write(device_handle_t device_handle, uint64_t unk, uint64_t start_sector, uint32_t sector_count, void *buf, uint32_t *nwrite, uint64_t flags);
/* get device type?
command = 0x11
indata = 0x01010071 (also works with indata 00000000)
outdata = 0x0000FF71 PS3 BD game
outdata = 0x00000040 BD-ROM
outdata = 0x00000041 BD-R
outdata = 0x0000FF61 PS2 DVD game
outdata = 0x00000010 DVD (any except ps2)
outdata = 0x00000008 CD (any except ps1?)
*/
LV2_EXPORT int storage_send_device_command(device_handle_t device_handle, unsigned int command, void *indata, uint64_t inlen, void *outdata, uint64_t outlen, uint64_t *unkret);
LV2_EXPORT int storage_map_io_memory(uint64_t device, void *buf, uint64_t size);
LV2_EXPORT int storage_unmap_io_memory(uint64_t device, void *buf);
static INLINE uint64_t storage_get_flash_device(void)
{
uint64_t value, v2;
lv1_get_repository_node_value(PS3_LPAR_ID_PME, FIELD_FIRST("sys", 0), FIELD("flash", 0), FIELD("ext", 0), 0, &value, &v2);
if (value&1)
return NAND_FLASH;
return NOR_FLASH;
}
#endif /* __LV2_STORAGE_H__ */
| Encapsulate/PS3Manager_API | ps3manager_api_mamba/lv2/include/lv2/storage.h | C | gpl-3.0 | 4,853 |
using System.IO;
using System.Collections.Generic;
using System.Xml;
using PDollarGestureRecognizer;
namespace PDollarDemo
{
public class GestureIO
{
/// <summary>
/// Reads a multistroke gesture from an string representation of xml
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public static Gesture ReadXMLGesture(string xml)
{
List<Point> points = new List<Point>();
XmlTextReader xmlReader = null;
int currentStrokeIndex = -1;
string gestureName = "";
try
{
xmlReader = new XmlTextReader(new StringReader(xml));
while (xmlReader.Read())
{
if (xmlReader.NodeType != XmlNodeType.Element) continue;
switch (xmlReader.Name)
{
case "Gesture":
gestureName = xmlReader["Name"];
if (gestureName.Contains("~")) // '~' character is specific to the naming convention of the MMG set
gestureName = gestureName.Substring(0, gestureName.LastIndexOf('~'));
if (gestureName.Contains("_")) // '_' character is specific to the naming convention of the MMG set
gestureName = gestureName.Replace('_', ' ');
break;
case "Stroke":
currentStrokeIndex++;
break;
case "Point":
points.Add(new Point(
float.Parse(xmlReader["X"]),
float.Parse(xmlReader["Y"]),
currentStrokeIndex
));
break;
}
}
}
finally
{
if (xmlReader != null)
xmlReader.Close();
}
return new Gesture(points.ToArray(), gestureName);
}
/// <summary>
/// Reads a multistroke gesture from an XML file
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static Gesture ReadGesture(string fileName)
{
List<Point> points = new List<Point>();
XmlTextReader xmlReader = null;
int currentStrokeIndex = -1;
string gestureName = "";
try
{
xmlReader = new XmlTextReader(File.OpenText(fileName));
while (xmlReader.Read())
{
if (xmlReader.NodeType != XmlNodeType.Element) continue;
switch (xmlReader.Name)
{
case "Gesture":
gestureName = xmlReader["Name"];
if (gestureName.Contains("~")) // '~' character is specific to the naming convention of the MMG set
gestureName = gestureName.Substring(0, gestureName.LastIndexOf('~'));
if (gestureName.Contains("_")) // '_' character is specific to the naming convention of the MMG set
gestureName = gestureName.Replace('_', ' ');
break;
case "Stroke":
currentStrokeIndex++;
break;
case "Point":
points.Add(new Point(
float.Parse(xmlReader["X"]),
float.Parse(xmlReader["Y"]),
currentStrokeIndex
));
break;
}
}
}
finally
{
if (xmlReader != null)
xmlReader.Close();
}
return new Gesture(points.ToArray(), gestureName);
}
/// <summary>
/// Writes a multistroke gesture to an XML file
/// </summary>
public static void WriteGesture(PDollarGestureRecognizer.Point[] points, string gestureName, string fileName)
{
using (StreamWriter sw = new StreamWriter(fileName))
{
sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>");
sw.WriteLine("<Gesture Name = \"{0}\">", gestureName);
int currentStroke = -1;
for (int i = 0; i < points.Length; i++)
{
if (points[i].StrokeID != currentStroke)
{
if (i > 0)
sw.WriteLine("\t</Stroke>");
sw.WriteLine("\t<Stroke>");
currentStroke = points[i].StrokeID;
}
sw.WriteLine("\t\t<Point X = \"{0}\" Y = \"{1}\" T = \"0\" Pressure = \"0\" />",
points[i].X, points[i].Y
);
}
sw.WriteLine("\t</Stroke>");
sw.WriteLine("</Gesture>");
}
}
}
} | vmohan7/NaviTouch | NaviTouch/Assets/NaviSDK/PDollarGestureRecognizer/GestureIO.cs | C# | gpl-3.0 | 4,722 |
/**
* L2FProd.com Common Components 7.3 License.
*
* Copyright 2005-2007 L2FProd.com
*
* 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.l2fprod.common.swing.plaf;
/**
* Each new component type of the library will contribute an addon to
* the LookAndFeelAddons. A <code>ComponentAddon</code> is the
* equivalent of a {@link javax.swing.LookAndFeel}but focused on one
* component. <br>
*
* @author <a href="mailto:fred@L2FProd.com">Frederic Lavigne</a>
*/
public interface ComponentAddon {
/**
* @return the name of this addon
*/
String getName();
/**
* Initializes this addon (i.e register UI classes, colors, fonts,
* borders, any UIResource used by the component class). When
* initializing, the addon can register different resources based on
* the addon or the current look and feel.
*
* @param addon the current addon
*/
void initialize(LookAndFeelAddons addon);
/**
* Uninitializes this addon.
*
* @param addon
*/
void uninitialize(LookAndFeelAddons addon);
} | pabalexa/calibre2opds | OpdsOutput/src/main/java/com/l2fprod/common/swing/plaf/ComponentAddon.java | Java | gpl-3.0 | 1,604 |
<?php
/* ----------------------------------------------------------------------
* themes/default/views/ca_objects_browse_html.php :
* ----------------------------------------------------------------------
* CollectiveAccess
* Open-source collections management software
* ----------------------------------------------------------------------
*
* Software by Whirl-i-Gig (http://www.whirl-i-gig.com)
* Copyright 2009-2010 Whirl-i-Gig
*
* For more information visit http://www.CollectiveAccess.org
*
* This program is free software; you may redistribute it and/or modify it under
* the terms of the provided license as published by Whirl-i-Gig
*
* CollectiveAccess is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This source code is free and modifiable under the terms of
* GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See
* the "license.txt" file for details, or visit the CollectiveAccess web site at
* http://www.CollectiveAccess.org
*
* ----------------------------------------------------------------------
*/
$va_facets = $this->getVar('available_facets');
$va_facets_with_content = $this->getVar('facets_with_content');
$va_facet_info = $this->getVar('facet_info');
$va_criteria = is_array($this->getVar('criteria')) ? $this->getVar('criteria') : array();
$va_results = $this->getVar('result');
$vs_browse_ui_style = $this->request->config->get('browse_ui_style');
$vs_browse_target = $this->getVar('target');
?>
<div id="browse"><div id="resultBox">
<?php
# --- we need to calculate the height of the box using the number of facets.
$vn_num_facets = sizeof($va_facets_with_content)-1;
$vn_boxHeight = "";
$vn_boxHeight = 20 + ($vn_num_facets * 15);
?>
<div class="browseTargetSelect"><?php print _t('Browsing By:').' '.$this->getVar('browse_selector'); ?></div>
<div style="clear: both;"><!-- empty --></div>
<div style="position: relative;">
<div id="browseCriteria">
<?php
if (sizeof($va_criteria)) {
$vn_x = 0;
foreach($va_criteria as $vs_facet_name => $va_row_ids) {
foreach($va_row_ids as $vn_row_id => $vs_label) {
$vs_facet_label = (isset($va_facet_info[$vs_facet_name]['label_singular'])) ? unicode_ucfirst($va_facet_info[$vs_facet_name]['label_singular']) : '???';
?>
<div class="browseBox" ">
<div class="heading"><?php print $vs_facet_label; ?>:</div>
<?php
print "<div class='browsingBy'>{$vs_label}".caNavLink($this->request, 'x', 'close', '', 'Browse', 'removeCriteria', array('facet' => $vs_facet_name, 'id' => $vn_row_id))."</div>\n";
?>
</div>
<?php
$vn_x++;
if($vn_x < sizeof($va_criteria)){
?>
<div class="browseWith" >with</div>
<?php
}
}
}
if (sizeof($va_facets)) {
?>
<div class="browseArrow" ><img src='<?php print $this->request->getThemeUrlPath(); ?>/graphics/browseArrow.gif' width='24' height='16' border='0'></div>
<div class="browseBoxRefine" style="height:<?php print $vn_boxHeight; ?>px;">
<div class='heading'>Refine results by:</div>
<?php
$va_available_facets = $this->getVar('available_facets');
foreach($va_available_facets as $vs_facet_code => $va_facet_info) {
print "<div class='browseFacetLink'><a href='#' onclick='caUIBrowsePanel.showBrowsePanel(\"{$vs_facet_code}\");'>".$va_facet_info['label_plural']."</a></div>\n";
}
?>
<div class="startOver">or <?php print caNavLink($this->request, _t('start over'), '', '', 'Browse', 'clearCriteria', array()); ?></div>
</div>
<?php
} else {
?>
<div class="browseArrow" style="margin-top:<?php print ($vn_boxHeight/2)-4; ?>px;"><img src='<?php print $this->request->getThemeUrlPath(); ?>/graphics/browseArrow.gif' width='24' height='16' border='0'></div>
<div class="browseBoxRefine" style="height:<?php print $vn_boxHeight; ?>px;">
<div class="startOver" style="margin-top:0px;"><?php print caNavLink($this->request, _t('start over'), '', '', 'Browse', 'clearCriteria', array()); ?></div>
</div>
<?php
}
} else {
if (sizeof($va_facets)) {
?>
<div class="browseBoxRefine" style="height:<?php print $vn_boxHeight; ?>px;">
<div class="heading">Start browsing by:</div>
<?php
$va_available_facets = $this->getVar('available_facets');
foreach($va_available_facets as $vs_facet_code => $va_facet_info) {
print "<div class='browseFacetLink'><a href='#' onclick='caUIBrowsePanel.showBrowsePanel(\"{$vs_facet_code}\");'>".$va_facet_info['label_plural']."</a></div>\n";
}
?>
</div>
<?php
}
}
?>
<div style='clear:both;'><!-- empty --></div></div><!-- end browseCriteria -->
</div><!-- end position:relative -->
<?php
if (sizeof($va_criteria) == 0) {
print $this->render('Browse/browse_start_html.php');
} else {
print ($vs_paging_controls = $this->render('Results/paging_controls_html.php'));
print $this->render('Search/search_controls_html.php');
print "<div class='sectionBox'>";
print $this->render('Results/'.$vs_browse_target.'_results_'.$this->getVar('current_view').'_html.php');
print "</div>";
}
?>
</div><!-- end resultbox --></div><!-- end browse -->
<div id="splashBrowsePanel" class="browseSelectPanel" style="z-index:1000;">
<a href="#" onclick="caUIBrowsePanel.hideBrowsePanel()" class="browseSelectPanelButton"> </a>
<div id="splashBrowsePanelContent">
</div>
</div>
<script type="text/javascript">
var caUIBrowsePanel = caUI.initBrowsePanel({ facetUrl: '<?php print caNavUrl($this->request, '', 'Browse', 'getFacet'); ?>'});
//
// Handle browse header scrolling
//
jQuery(document).ready(function() {
jQuery("div.scrollableBrowseController").scrollable();
});
</script> | collectiveaccess/pawtucket | themes/white/views/Browse/browse_controls_html.php | PHP | gpl-3.0 | 5,886 |
#ifndef MACTYPES_H
#define MACTYPES_H
#include <stdint.h>
#include <CoreFoundation/CFBase.h>
class _StringHandle;
#if 0 // declared in CFBase.h
typedef int8_t SInt8;
typedef uint8_t UInt8;
typedef int16_t SInt16;
typedef uint16_t UInt16;
typedef int32_t SInt32;
typedef uint32_t UInt32;
typedef int64_t SInt64;
typedef uint64_t UInt64;
typedef float Float32;
typedef double Float64;
#endif
typedef uint32_t OptionBits;
typedef int32_t Fixed; // 16/16
typedef Fixed* FixedPtr;
typedef int32_t Fract; // 2/30
typedef Fract* FractPtr;
typedef uint32_t UnsignedFixed; // 16u/16
typedef UnsignedFixed* UnsignedFixedPtr;
typedef short ShortFixed;
typedef ShortFixed * ShortFixedPtr; // 8/8
typedef int64_t wide;
typedef uint64_t UnsignedWide;
typedef uint64_t AbsoluteTime;
typedef int32_t Duration; // milliseconds
typedef uint8_t Boolean;
// Pascal strings
typedef unsigned char Str255[256];
typedef unsigned char Str63[64];
typedef unsigned char Str32[33];
typedef unsigned char Str31[32];
typedef unsigned char Str27[28];
typedef unsigned char Str15[16];
typedef unsigned char* StringPtr;
typedef unsigned char** StringHandle;
typedef char* Ptr;
typedef char** Handle;
typedef int16_t OSErr;
typedef int32_t OSStatus;
typedef uint32_t OSType;
#endif
| iBeacons/darling | src/CoreServices/MacTypes.h | C | gpl-3.0 | 1,276 |
#region netDxf library, Copyright (C) 2009-2018 Daniel Carvajal (haplokuon@gmail.com)
// netDxf library
// Copyright (C) 2009-2018 Daniel Carvajal (haplokuon@gmail.com)
//
// 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.
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion
using netDxf.Tables;
namespace netDxf.Objects
{
/// <summary>
/// Represents an underlay definition.
/// </summary>
public abstract class UnderlayDefinition :
TableObject
{
#region private fields
private readonly UnderlayType type;
private readonly string file;
#endregion
#region constructor
/// <summary>
/// Initializes a new instance of the <c>UnderlayDefinition</c> class.
/// </summary>
/// <param name="name">Underlay name.</param>
/// <param name="file">Underlay file name with full or relative path.</param>
/// <param name="type">Underlay type.</param>
protected UnderlayDefinition(string name, string file, UnderlayType type)
: base(name, DxfObjectCode.UnderlayDefinition, false)
{
this.file = file;
this.type = type;
switch (type)
{
case UnderlayType.DGN:
this.CodeName = DxfObjectCode.UnderlayDgnDefinition;
break;
case UnderlayType.DWF:
this.CodeName = DxfObjectCode.UnderlayDwfDefinition;
break;
case UnderlayType.PDF:
this.CodeName = DxfObjectCode.UnderlayPdfDefinition;
break;
}
}
#endregion
#region public properties
/// <summary>
/// Get the underlay type.
/// </summary>
public UnderlayType Type
{
get { return this.type; }
}
/// <summary>
/// Gets the underlay file.
/// </summary>
public string File
{
get { return this.file; }
}
#endregion
}
} | virtualrobotix/MissionPlanner | ExtLibs/netDxf/Objects/UnderlayDefinition.cs | C# | gpl-3.0 | 2,898 |
# Custom properties lose unicode text when copied
| hwbehrens/livecode | docs/notes/bugfix-15258.md | Markdown | gpl-3.0 | 50 |
' R- Instat
' Copyright (C) 2015-2017
'
' 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 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 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/>.
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class frmMetaData
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.grdMetaData = New unvell.ReoGrid.ReoGridControl()
Me.txtMetadata = New System.Windows.Forms.TextBox()
Me.SuspendLayout()
'
'grdMetaData
'
Me.grdMetaData.BackColor = System.Drawing.Color.White
Me.grdMetaData.ColumnHeaderContextMenuStrip = Nothing
Me.grdMetaData.Dock = System.Windows.Forms.DockStyle.Fill
Me.grdMetaData.LeadHeaderContextMenuStrip = Nothing
Me.grdMetaData.Location = New System.Drawing.Point(0, 0)
Me.grdMetaData.Name = "grdMetaData"
Me.grdMetaData.RowHeaderContextMenuStrip = Nothing
Me.grdMetaData.Script = Nothing
Me.grdMetaData.SheetTabContextMenuStrip = Nothing
Me.grdMetaData.SheetTabNewButtonVisible = False
Me.grdMetaData.SheetTabVisible = False
Me.grdMetaData.SheetTabWidth = 100
Me.grdMetaData.ShowScrollEndSpacing = True
Me.grdMetaData.Size = New System.Drawing.Size(477, 317)
Me.grdMetaData.TabIndex = 1
Me.grdMetaData.Text = "Meta Data"
'
'txtMetadata
'
Me.txtMetadata.Location = New System.Drawing.Point(213, 11)
Me.txtMetadata.Multiline = True
Me.txtMetadata.Name = "txtMetadata"
Me.txtMetadata.ReadOnly = True
Me.txtMetadata.Size = New System.Drawing.Size(205, 100)
Me.txtMetadata.TabIndex = 2
'
'frmMetaData
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(96.0!, 96.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi
Me.ClientSize = New System.Drawing.Size(477, 317)
Me.Controls.Add(Me.grdMetaData)
Me.Controls.Add(Me.txtMetadata)
Me.Name = "frmMetaData"
Me.ShowIcon = False
Me.Text = "Data frame Metadata"
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents grdMetaData As unvell.ReoGrid.ReoGridControl
Friend WithEvents txtMetadata As TextBox
End Class
| Patowhiz/R-Instat | instat/frmMetaData.designer.vb | Visual Basic | gpl-3.0 | 3,619 |
/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "core/html/forms/URLInputType.h"
#include "core/InputTypeNames.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "platform/text/PlatformLocale.h"
namespace blink {
InputType* URLInputType::create(HTMLInputElement& element) {
return new URLInputType(element);
}
void URLInputType::countUsage() {
countUsageIfVisible(UseCounter::InputTypeURL);
}
const AtomicString& URLInputType::formControlType() const {
return InputTypeNames::url;
}
bool URLInputType::typeMismatchFor(const String& value) const {
return !value.isEmpty() && !KURL(KURL(), value).isValid();
}
bool URLInputType::typeMismatch() const {
return typeMismatchFor(element().value());
}
String URLInputType::typeMismatchText() const {
return locale().queryString(WebLocalizedString::ValidationTypeMismatchForURL);
}
String URLInputType::sanitizeValue(const String& proposedValue) const {
return BaseTextInputType::sanitizeValue(
stripLeadingAndTrailingHTMLSpaces(proposedValue));
}
String URLInputType::sanitizeUserInputValue(const String& proposedValue) const {
// Do not call URLInputType::sanitizeValue.
return BaseTextInputType::sanitizeValue(proposedValue);
}
} // namespace blink
| geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/WebKit/Source/core/html/forms/URLInputType.cpp | C++ | gpl-3.0 | 2,803 |
/*
* Copyright (c) 2011 Matthew Francis
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.itadaki.bzip2;
/**
* An in-place, length restricted Canonical Huffman code length allocator
*
* Based on the algorithm proposed by R. L. Milidiú, A. A. Pessoa and E. S. Laber in "In-place
* Length-Restricted Prefix Coding" (see: http://www-di.inf.puc-rio.br/~laber/public/spire98.ps)
* and incorporating additional ideas from the implementation of "shcodec" by Simakov Alexander
* (see: http://webcenter.ru/~xander/)
*/
public class HuffmanAllocator {
/**
* FIRST() function
* @param array The code length array
* @param i The input position
* @param nodesToMove The number of internal nodes to be relocated
* @return The smallest {@code k} such that {@code nodesToMove <= k <= i} and
* {@code i <= (array[k] % array.length)}
*/
private static int first (final int[] array, int i, final int nodesToMove) {
final int length = array.length;
final int limit = i;
int k = array.length - 2;
while ((i >= nodesToMove) && ((array[i] % length) > limit)) {
k = i;
i -= (limit - i + 1);
}
i = Math.max (nodesToMove - 1, i);
while (k > (i + 1)) {
int temp = (i + k) >> 1;
if ((array[temp] % length) > limit) {
k = temp;
} else {
i = temp;
}
}
return k;
}
/**
* Fills the code array with extended parent pointers
* @param array The code length array
*/
private static void setExtendedParentPointers (final int[] array) {
final int length = array.length;
array[0] += array[1];
for (int headNode = 0, tailNode = 1, topNode = 2; tailNode < (length - 1); tailNode++) {
int temp;
if ((topNode >= length) || (array[headNode] < array[topNode])) {
temp = array[headNode];
array[headNode++] = tailNode;
} else {
temp = array[topNode++];
}
if ((topNode >= length) || ((headNode < tailNode) && (array[headNode] < array[topNode]))) {
temp += array[headNode];
array[headNode++] = tailNode + length;
} else {
temp += array[topNode++];
}
array[tailNode] = temp;
}
}
/**
* Finds the number of nodes to relocate in order to achieve a given code length limit
* @param array The code length array
* @param maximumLength The maximum bit length for the generated codes
* @return The number of nodes to relocate
*/
private static int findNodesToRelocate (final int[] array, final int maximumLength) {
int currentNode = array.length - 2;
for (int currentDepth = 1; (currentDepth < (maximumLength - 1)) && (currentNode > 1); currentDepth++) {
currentNode = first (array, currentNode - 1, 0);
}
return currentNode;
}
/**
* A final allocation pass with no code length limit
* @param array The code length array
*/
private static void allocateNodeLengths (final int[] array) {
int firstNode = array.length - 2;
int nextNode = array.length - 1;
for (int currentDepth = 1, availableNodes = 2; availableNodes > 0; currentDepth++) {
final int lastNode = firstNode;
firstNode = first (array, lastNode - 1, 0);
for (int i = availableNodes - (lastNode - firstNode); i > 0; i--) {
array[nextNode--] = currentDepth;
}
availableNodes = (lastNode - firstNode) << 1;
}
}
/**
* A final allocation pass that relocates nodes in order to achieve a maximum code length limit
* @param array The code length array
* @param nodesToMove The number of internal nodes to be relocated
* @param insertDepth The depth at which to insert relocated nodes
*/
private static void allocateNodeLengthsWithRelocation (final int[] array, final int nodesToMove, final int insertDepth) {
int firstNode = array.length - 2;
int nextNode = array.length - 1;
int currentDepth = (insertDepth == 1) ? 2 : 1;
int nodesLeftToMove = (insertDepth == 1) ? nodesToMove - 2 : nodesToMove;
for (int availableNodes = currentDepth << 1; availableNodes > 0; currentDepth++) {
final int lastNode = firstNode;
firstNode = (firstNode <= nodesToMove) ? firstNode : first (array, lastNode - 1, nodesToMove);
int offset = 0;
if (currentDepth >= insertDepth) {
offset = Math.min (nodesLeftToMove, 1 << (currentDepth - insertDepth));
} else if (currentDepth == (insertDepth - 1)) {
offset = 1;
if ((array[firstNode]) == lastNode) {
firstNode++;
}
}
for (int i = availableNodes - (lastNode - firstNode + offset); i > 0; i--) {
array[nextNode--] = currentDepth;
}
nodesLeftToMove -= offset;
availableNodes = (lastNode - firstNode + offset) << 1;
}
}
/**
* Allocates Canonical Huffman code lengths in place based on a sorted frequency array
* @param array On input, a sorted array of symbol frequencies; On output, an array of Canonical
* Huffman code lengths
* @param maximumLength The maximum code length. Must be at least {@code ceil(log2(array.length))}
*/
public static void allocateHuffmanCodeLengths (final int[] array, final int maximumLength) {
switch (array.length) {
case 2:
array[1] = 1;
case 1:
array[0] = 1;
return;
}
/* Pass 1 : Set extended parent pointers */
setExtendedParentPointers (array);
/* Pass 2 : Find number of nodes to relocate in order to achieve maximum code length */
int nodesToRelocate = findNodesToRelocate (array, maximumLength);
/* Pass 3 : Generate code lengths */
if ((array[0] % array.length) >= nodesToRelocate) {
allocateNodeLengths (array);
} else {
int insertDepth = maximumLength - (32 - Integer.numberOfLeadingZeros (nodesToRelocate - 1));
allocateNodeLengthsWithRelocation (array, nodesToRelocate, insertDepth);
}
}
/**
* Non-instantiable
*/
private HuffmanAllocator() { }
}
| routeKIT/routeKIT | src/org/itadaki/bzip2/HuffmanAllocator.java | Java | gpl-3.0 | 6,762 |
/*
---------------------------------------------------------------------------------------
This source file is part of SWG:ANH (Star Wars Galaxies - A New Hope - Server Emulator)
For more information, visit http://www.swganh.com
Copyright (c) 2006 - 2010 The SWG:ANH Team
---------------------------------------------------------------------------------------
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
---------------------------------------------------------------------------------------
*/
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
use swganh;
--
-- Definition of procedure `sp_ReturnAccountCharacters`
--
DROP PROCEDURE IF EXISTS `sp_ReturnAccountCharacters`;
DELIMITER $$
/*!50003 SET @TEMP_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */ $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_ReturnAccountCharacters`(IN account_id INT)
BEGIN
SELECT A.id, A.firstname, A.lastname, A.galaxy_id, B.base_model_string
FROM swganh.characters A
INNER JOIN swganh.character_appearance B ON (A.id = B.character_id)
WHERE A.account_id= account_id AND A.archived=0;
END $$
/*!50003 SET SESSION SQL_MODE=@TEMP_SQL_MODE */ $$
DELIMITER ;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; | swganh/mmoserver | mmoserverdb/swganh/procedures/sp_ReturnAccountCharacters.sql | SQL | gpl-3.0 | 2,645 |
/*
* Doubly linked list construction and deletion.
*/
#include <stdlib.h>
#include <verifier-builtins.h>
int main() {
struct T {
struct T* next;
struct T* prev;
int data;
};
struct T* x = NULL;
struct T* y = NULL;
x = malloc(sizeof(struct T));
x->next = NULL;
x->prev = NULL;
while (__VERIFIER_nondet_int()) {
y = malloc(sizeof(struct T));
y->next = x;
x->prev = y;
y->prev = NULL;
x = y;
}
__VERIFIER_plot("test-f0028-fixpoint");
while (x) {
y = x->next;
free(x);
x = y;
}
return 0;
}
| kdudka/predator | tests/forester/dll.c | C | gpl-3.0 | 532 |
# Authors:
# Petr Vobornik <pvoborni@redhat.com>
#
# Copyright (C) 2013 Red Hat
# see file 'COPYING' for use and warranty information
#
# 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 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 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/>.
"""
Range tests
"""
import ipatests.test_webui.test_trust as trust_mod
from ipatests.test_webui.ui_driver import screenshot
from ipatests.test_webui.task_range import range_tasks
ENTITY = 'idrange'
PKEY = 'itest-range'
class test_range(range_tasks):
@screenshot
def test_crud(self):
"""
Basic CRUD: range
"""
self.init_app()
self.get_shifts()
self.basic_crud(ENTITY, self.get_data(PKEY))
@screenshot
def test_types(self):
"""
Test range types
Only 'local' and 'ipa-ad-trust' types are tested since range validation
made quite hard to test the other types:
- 'ipa-ad-trust-posix' can be tested only with subdomains.
- 'ipa-ad-winsync' and 'ipa-ipa-trust' and are not supported yet
https://fedorahosted.org/freeipa/ticket/4323
"""
self.init_app()
self.get_shifts()
pkey_local = 'itest-local'
pkey_ad = 'itest-ad'
pkey_posix = 'itest-ad-posix'
pkey_winsync = 'itest-ad-winsync'
pkey_trust = 'itest-ipa-trust'
column = 'iparangetype'
add = self.get_add_data(pkey_local)
data = self.get_data(pkey_local, add_data=add)
self.add_record(ENTITY, data)
self.assert_record_value('local domain range', pkey_local, column)
if self.has_trusts():
trust_tasks = trust_mod.trust_tasks()
trust_data = trust_tasks.get_data()
self.add_record(trust_mod.ENTITY, trust_data)
domain = self.get_domain()
self.navigate_to_entity(ENTITY)
add = self.get_add_data(pkey_ad, range_type='ipa-ad-trust', domain=domain)
data = self.get_data(pkey_ad, add_data=add)
self.add_record(ENTITY, data, navigate=False)
self.assert_record_value('Active Directory domain range', pkey_ad, column)
self.delete(trust_mod.ENTITY, [trust_data])
self.navigate_to_entity(ENTITY)
self.delete_record(pkey_ad)
self.delete_record(pkey_local)
| pspacek/freeipa | ipatests/test_webui/test_range.py | Python | gpl-3.0 | 2,865 |
/*
* #%~
* org.overture.ide.core
* %%
* Copyright (C) 2008 - 2014 Overture
* %%
* 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 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 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/gpl-3.0.html>.
* #~%
*/
package org.overture.ide.core.resources;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.overture.ide.core.VdmCore;
import org.overture.ide.internal.core.ResourceManager;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ModelBuildPath
{
final IVdmProject vdmProject;
final IProject project;
final File modelPathFile;
List<IContainer> srcPaths = new Vector<IContainer>();
IContainer output;
IContainer library;
public ModelBuildPath(IVdmProject project)
{
this.vdmProject = project;
this.project = (IProject) this.vdmProject.getAdapter(IProject.class);
IPath base = this.project.getLocation();
base = base.append(".modelpath");
this.modelPathFile = base.toFile();
this.output = this.project.getFolder("generated");
this.library = this.project.getFolder("lib");
parse();
}
private boolean hasModelPath()
{
return this.modelPathFile.exists();
}
private IContainer getDefaultModelSrcPath()
{
return this.project;
}
public List<IContainer> getModelSrcPaths()
{
List<IContainer> tmp = new Vector<IContainer>(srcPaths.size());
tmp.addAll(srcPaths);
return tmp;
}
public synchronized IContainer getOutput()
{
return this.output;
}
public synchronized IContainer getLibrary()
{
return this.library;
}
private synchronized void parse()
{
if (!hasModelPath())
{
srcPaths.add(getDefaultModelSrcPath());
return;
}
try
{
File file = this.modelPathFile;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName("modelpathentry");
for (int s = 0; s < nodeLst.getLength(); s++)
{
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE)
{
Node kindAttribute = fstNode.getAttributes().getNamedItem("kind");
String kindValue = kindAttribute.getNodeValue();
if (kindValue != null)
{
if (kindValue.equals("src"))
{
Node pathAttribute = fstNode.getAttributes().getNamedItem("path");
String pathValue = pathAttribute.getNodeValue();
if(pathValue.equals("."))
{
add(getDefaultModelSrcPath());
}else
{
add(this.project.getFolder(pathValue));
}
} else if (kindValue.equals("output"))
{
Node pathAttribute = fstNode.getAttributes().getNamedItem("path");
String pathValue = pathAttribute.getNodeValue();
output = this.project.getFolder(pathValue);
} else if (kindValue.equals("library"))
{
Node pathAttribute = fstNode.getAttributes().getNamedItem("path");
String pathValue = pathAttribute.getNodeValue();
library = this.project.getFolder(pathValue);
}
}
}
}
if(srcPaths.isEmpty())
{
srcPaths.add(getDefaultModelSrcPath());
}
} catch (Exception e)
{
VdmCore.log("Faild to parse .modelpath file", e);
}
}
public synchronized void setOutput(IContainer container)
{
this.output = container;
}
public synchronized void setLibrary(IContainer container)
{
this.library = container;
}
public synchronized void add(IContainer container)
{
if(container instanceof IProject)
{
srcPaths.clear();
}
else if(container instanceof IFolder)
{
String fullPath = container.getProjectRelativePath().toString();
boolean flag = true;
for (IContainer s : srcPaths)
{
flag = flag && s.getProjectRelativePath().toString().startsWith(fullPath);
}
if(flag)
srcPaths.clear();
}
if (!srcPaths.contains(container))
{
srcPaths.add(container);
}
}
public synchronized void remove(IContainer container)
{
if (srcPaths.contains(container))
{
srcPaths.remove(container);
}
}
public synchronized boolean contains(IContainer container)
{
return srcPaths.contains(container);
}
public synchronized void save() throws CoreException
{
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
sb.append("<modelpath>\n");
for (IContainer src : srcPaths)
{
if (src.getProjectRelativePath().toString().length() > 0)
{
sb.append("\t<modelpathentry kind=\"src\" path=\""
+ src.getProjectRelativePath() + "\"/>\n");
}else if (src instanceof IProject)
{
sb.append("\t<modelpathentry kind=\"src\" path=\".\"/>\n");
}
}
if (output != null
&& output.getProjectRelativePath().toString().length() > 0)
{
sb.append("\t<modelpathentry kind=\"output\" path=\""
+ output.getProjectRelativePath() + "\"/>\n");
}
if (library != null
&& library.getProjectRelativePath().toString().length() > 0)
{
sb.append("\t<modelpathentry kind=\"library\" path=\""
+ library.getProjectRelativePath() + "\"/>\n");
}
sb.append("</modelpath>");
PrintWriter out = null;
try
{
FileWriter outFile = new FileWriter(this.modelPathFile);
out = new PrintWriter(outFile);
out.println(sb.toString());
} catch (IOException e)
{
VdmCore.log("Faild to save .modelpath file", e);
} finally
{
if (out != null)
{
out.close();
}
}
ResourceManager.getInstance().syncBuildPath(vdmProject);
}
/**
* Reload the build path and discard any un-saved changes
*/
public void reload()
{
parse();
}
}
| jmcPereira/overture | ide/core/src/main/java/org/overture/ide/core/resources/ModelBuildPath.java | Java | gpl-3.0 | 6,618 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<TITLE>
Uses of Class org.apache.poi.hssf.record.CellRecord (POI API Documentation)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.poi.hssf.record.CellRecord (POI API Documentation)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/poi/hssf/record/CellRecord.html" title="class in org.apache.poi.hssf.record"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/poi/hssf/record//class-useCellRecord.html" target="_top"><B>FRAMES</B></A>
<A HREF="CellRecord.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.poi.hssf.record.CellRecord</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../org/apache/poi/hssf/record/CellRecord.html" title="class in org.apache.poi.hssf.record">CellRecord</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.poi.hssf.record"><B>org.apache.poi.hssf.record</B></A></TD>
<TD>Record package contains class representations for XLS binary strutures. </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.poi.hssf.record"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../org/apache/poi/hssf/record/CellRecord.html" title="class in org.apache.poi.hssf.record">CellRecord</A> in <A HREF="../../../../../../org/apache/poi/hssf/record/package-summary.html">org.apache.poi.hssf.record</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../../org/apache/poi/hssf/record/CellRecord.html" title="class in org.apache.poi.hssf.record">CellRecord</A> in <A HREF="../../../../../../org/apache/poi/hssf/record/package-summary.html">org.apache.poi.hssf.record</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/poi/hssf/record/BoolErrRecord.html" title="class in org.apache.poi.hssf.record">BoolErrRecord</A></B></CODE>
<BR>
Creates new BoolErrRecord.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/poi/hssf/record/FormulaRecord.html" title="class in org.apache.poi.hssf.record">FormulaRecord</A></B></CODE>
<BR>
Formula Record (0x0006).</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/poi/hssf/record/LabelSSTRecord.html" title="class in org.apache.poi.hssf.record">LabelSSTRecord</A></B></CODE>
<BR>
Title: Label SST Record</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/poi/hssf/record/NumberRecord.html" title="class in org.apache.poi.hssf.record">NumberRecord</A></B></CODE>
<BR>
NUMBER (0x0203) Contains a numeric cell value.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/poi/hssf/record/RKRecord.html" title="class in org.apache.poi.hssf.record">RKRecord</A></B></CODE>
<BR>
Title: RK Record (0x027E)</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/poi/hssf/record/package-summary.html">org.apache.poi.hssf.record</A> with parameters of type <A HREF="../../../../../../org/apache/poi/hssf/record/CellRecord.html" title="class in org.apache.poi.hssf.record">CellRecord</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected void</CODE></FONT></TD>
<TD><CODE><B>CellRecord.</B><B><A HREF="../../../../../../org/apache/poi/hssf/record/CellRecord.html#copyBaseFields(org.apache.poi.hssf.record.CellRecord)">copyBaseFields</A></B>(<A HREF="../../../../../../org/apache/poi/hssf/record/CellRecord.html" title="class in org.apache.poi.hssf.record">CellRecord</A> rec)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/poi/hssf/record/CellRecord.html" title="class in org.apache.poi.hssf.record"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/poi/hssf/record//class-useCellRecord.html" target="_top"><B>FRAMES</B></A>
<A HREF="CellRecord.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright 2017 The Apache Software Foundation or
its licensors, as applicable.</i>
</BODY>
</HTML>
| TonyClark/ESL | lib/poi-3.17/docs/apidocs/org/apache/poi/hssf/record/class-use/CellRecord.html | HTML | gpl-3.0 | 10,534 |
/* -*- c++ -*- */
/*
* Copyright 2013-2014 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* GNU Radio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "encoder_impl.h"
#include <gnuradio/io_signature.h>
#include <stdio.h>
namespace gr {
namespace fec {
encoder::sptr
encoder::make(generic_encoder::sptr my_encoder,
size_t input_item_size,
size_t output_item_size)
{
return gnuradio::get_initial_sptr
(new encoder_impl(my_encoder, input_item_size,
output_item_size));
}
encoder_impl::encoder_impl(generic_encoder::sptr my_encoder,
size_t input_item_size,
size_t output_item_size)
: block("fec_encoder",
io_signature::make(1, 1, input_item_size),
io_signature::make(1, 1, output_item_size)),
d_input_item_size(input_item_size),
d_output_item_size(output_item_size)
{
set_fixed_rate(true);
set_relative_rate((double)my_encoder->get_output_size()/(double)my_encoder->get_input_size());
set_output_multiple(my_encoder->get_output_size());
d_encoder = my_encoder;
d_input_size = d_encoder->get_input_size()*d_input_item_size;
d_output_size = d_encoder->get_output_size()*d_output_item_size;
}
encoder_impl::~encoder_impl()
{
}
int
encoder_impl::fixed_rate_ninput_to_noutput(int ninput)
{
return (int)(0.5 + ninput*relative_rate());
}
int
encoder_impl::fixed_rate_noutput_to_ninput(int noutput)
{
return (int)(0.5 + noutput/relative_rate());
}
void
encoder_impl::forecast(int noutput_items,
gr_vector_int& ninput_items_required)
{
ninput_items_required[0] = fixed_rate_noutput_to_ninput(noutput_items);
}
int
encoder_impl::general_work(int noutput_items,
gr_vector_int& ninput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items)
{
char *inbuffer = (char*)input_items[0];
char *outbuffer = (char*)output_items[0];
//GR_LOG_DEBUG(d_debug_logger, boost::format("%1%, %2%, %3%") \
// % noutput_items % ninput_items[0] % (noutput_items/output_multiple()));
for(int i = 0; i < noutput_items/output_multiple(); i++) {
d_encoder->generic_work((void*)(inbuffer+(i*d_input_size)),
(void*)(outbuffer+(i*d_output_size)));
}
//GR_LOG_DEBUG(d_debug_logger, boost::format("consuming: %1%") \
// % (fixed_rate_noutput_to_ninput(noutput_items)));
//GR_LOG_DEBUG(d_debug_logger, boost::format("returning: %1%") \
// % (noutput_items));
consume_each(fixed_rate_noutput_to_ninput(noutput_items));
return noutput_items;
}
} /* namespace fec */
} /* namespace gr */
| surligas/cs436-gnuradio | gr-fec/lib/encoder_impl.cc | C++ | gpl-3.0 | 3,746 |
/*
Unix SMB/CIFS implementation.
Filename utility functions.
Copyright (C) Tim Prouty 2009
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 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 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 "includes.h"
/**
* XXX: This is temporary and there should be no callers of this outside of
* this file once smb_filename is plumbed through all path based operations.
* The one legitimate caller currently is smb_fname_str_dbg(), which this
* could be made static for.
*/
NTSTATUS get_full_smb_filename(TALLOC_CTX *ctx,
const struct smb_filename *smb_fname,
char **full_name)
{
if (smb_fname->stream_name) {
/* stream_name must always be NULL if there is no stream. */
SMB_ASSERT(smb_fname->stream_name[0] != '\0');
*full_name = talloc_asprintf(ctx, "%s%s", smb_fname->base_name,
smb_fname->stream_name);
} else {
*full_name = talloc_strdup(ctx, smb_fname->base_name);
}
if (!*full_name) {
return NT_STATUS_NO_MEMORY;
}
return NT_STATUS_OK;
}
/**
* There are actually legitimate callers of this such as functions that
* enumerate streams using the vfs_streaminfo interface and then want to
* operate on each stream.
*/
struct smb_filename *synthetic_smb_fname(TALLOC_CTX *mem_ctx,
const char *base_name,
const char *stream_name,
const SMB_STRUCT_STAT *psbuf,
uint32_t flags)
{
struct smb_filename smb_fname_loc = { 0, };
/* Setup the base_name/stream_name. */
smb_fname_loc.base_name = discard_const_p(char, base_name);
smb_fname_loc.stream_name = discard_const_p(char, stream_name);
smb_fname_loc.flags = flags;
/* Copy the psbuf if one was given. */
if (psbuf)
smb_fname_loc.st = *psbuf;
/* Let cp_smb_filename() do the heavy lifting. */
return cp_smb_filename(mem_ctx, &smb_fname_loc);
}
/**
* Utility function used by VFS calls that must *NOT* operate
* on a stream filename, only the base_name.
*/
struct smb_filename *cp_smb_filename_nostream(TALLOC_CTX *mem_ctx,
const struct smb_filename *smb_fname_in)
{
struct smb_filename *smb_fname = cp_smb_filename(mem_ctx,
smb_fname_in);
if (smb_fname == NULL) {
return NULL;
}
TALLOC_FREE(smb_fname->stream_name);
return smb_fname;
}
/**
* There are a few legitimate users of this.
*/
struct smb_filename *synthetic_smb_fname_split(TALLOC_CTX *ctx,
const char *fname,
bool posix_path)
{
char *stream_name = NULL;
char *base_name = NULL;
struct smb_filename *ret;
bool ok;
if (posix_path) {
/* No stream name looked for. */
return synthetic_smb_fname(ctx,
fname,
NULL,
NULL,
SMB_FILENAME_POSIX_PATH);
}
ok = split_stream_filename(ctx,
fname,
&base_name,
&stream_name);
if (!ok) {
return NULL;
}
ret = synthetic_smb_fname(ctx, base_name, stream_name, NULL, 0);
TALLOC_FREE(base_name);
TALLOC_FREE(stream_name);
return ret;
}
/**
* Return a string using the talloc_tos()
*/
const char *smb_fname_str_dbg(const struct smb_filename *smb_fname)
{
char *fname = NULL;
NTSTATUS status;
if (smb_fname == NULL) {
return "";
}
status = get_full_smb_filename(talloc_tos(), smb_fname, &fname);
if (!NT_STATUS_IS_OK(status)) {
return "";
}
return fname;
}
/**
* Return a debug string of the path name of an fsp using the talloc_tos().
*/
const char *fsp_str_dbg(const struct files_struct *fsp)
{
return smb_fname_str_dbg(fsp->fsp_name);
}
/**
* Create a debug string for the fnum of an fsp.
*
* This is allocated to talloc_tos() or a string constant
* in certain corner cases. The returned string should
* hence not be free'd directly but only via the talloc stack.
*/
const char *fsp_fnum_dbg(const struct files_struct *fsp)
{
char *str;
if (fsp == NULL) {
return "fnum [fsp is NULL]";
}
if (fsp->fnum == FNUM_FIELD_INVALID) {
return "fnum [invalid value]";
}
str = talloc_asprintf(talloc_tos(), "fnum %llu",
(unsigned long long)fsp->fnum);
if (str == NULL) {
DEBUG(1, ("%s: talloc_asprintf failed\n", __FUNCTION__));
return "fnum [talloc failed!]";
}
return str;
}
struct smb_filename *cp_smb_filename(TALLOC_CTX *mem_ctx,
const struct smb_filename *in)
{
struct smb_filename *out;
size_t base_len = 0;
size_t stream_len = 0;
size_t lcomp_len = 0;
int num = 0;
/* stream_name must always be NULL if there is no stream. */
if (in->stream_name) {
SMB_ASSERT(in->stream_name[0] != '\0');
}
if (in->base_name != NULL) {
base_len = strlen(in->base_name) + 1;
num += 1;
}
if (in->stream_name != NULL) {
stream_len = strlen(in->stream_name) + 1;
num += 1;
}
if (in->original_lcomp != NULL) {
lcomp_len = strlen(in->original_lcomp) + 1;
num += 1;
}
out = talloc_pooled_object(mem_ctx, struct smb_filename,
num, stream_len + base_len + lcomp_len);
if (out == NULL) {
return NULL;
}
ZERO_STRUCTP(out);
/*
* The following allocations cannot fail as we
* pre-allocated space for them in the out pooled
* object.
*/
if (in->base_name != NULL) {
out->base_name = talloc_memdup(
out, in->base_name, base_len);
talloc_set_name_const(out->base_name,
out->base_name);
}
if (in->stream_name != NULL) {
out->stream_name = talloc_memdup(
out, in->stream_name, stream_len);
talloc_set_name_const(out->stream_name,
out->stream_name);
}
if (in->original_lcomp != NULL) {
out->original_lcomp = talloc_memdup(
out, in->original_lcomp, lcomp_len);
talloc_set_name_const(out->original_lcomp,
out->original_lcomp);
}
out->flags = in->flags;
out->st = in->st;
return out;
}
/****************************************************************************
Simple check to determine if the filename is a stream.
***************************************************************************/
bool is_ntfs_stream_smb_fname(const struct smb_filename *smb_fname)
{
/* stream_name must always be NULL if there is no stream. */
if (smb_fname->stream_name) {
SMB_ASSERT(smb_fname->stream_name[0] != '\0');
}
if (smb_fname->flags & SMB_FILENAME_POSIX_PATH) {
return false;
}
return smb_fname->stream_name != NULL;
}
/****************************************************************************
Returns true if the filename's stream == "::$DATA"
***************************************************************************/
bool is_ntfs_default_stream_smb_fname(const struct smb_filename *smb_fname)
{
if (!is_ntfs_stream_smb_fname(smb_fname)) {
return false;
}
return strcasecmp_m(smb_fname->stream_name, "::$DATA") == 0;
}
/****************************************************************************
Filter out Windows invalid EA names (list probed from Windows 2012).
****************************************************************************/
static char bad_ea_name_chars[] = "\"*+,/:;<=>?[\\]|";
bool is_invalid_windows_ea_name(const char *name)
{
int i;
/* EA name is pulled as ascii so we can examine
individual bytes here. */
for (i = 0; name[i] != 0; i++) {
int val = (name[i] & 0xff);
if (val < ' ' || strchr(bad_ea_name_chars, val)) {
return true;
}
}
return false;
}
bool ea_list_has_invalid_name(struct ea_list *ea_list)
{
for (;ea_list; ea_list = ea_list->next) {
if (is_invalid_windows_ea_name(ea_list->ea.name)) {
return true;
}
}
return false;
}
/****************************************************************************
Split an incoming name into tallocd filename and stream components.
Returns true on success, false on out of memory.
****************************************************************************/
bool split_stream_filename(TALLOC_CTX *ctx,
const char *filename_in,
char **filename_out,
char **streamname_out)
{
const char *stream_name = NULL;
char *stream_out = NULL;
char *file_out = NULL;
stream_name = strchr_m(filename_in, ':');
if (stream_name) {
stream_out = talloc_strdup(ctx, stream_name);
if (stream_out == NULL) {
return false;
}
file_out = talloc_strndup(ctx,
filename_in,
PTR_DIFF(stream_name, filename_in));
} else {
file_out = talloc_strdup(ctx, filename_in);
}
if (file_out == NULL) {
TALLOC_FREE(stream_out);
return false;
}
if (filename_out) {
*filename_out = file_out;
}
if (streamname_out) {
*streamname_out = stream_out;
}
return true;
}
| sathieu/samba | source3/lib/filename_util.c | C | gpl-3.0 | 8,836 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using u8 = System.Byte;
using u16 = System.UInt16;
using s32 = System.Int32;
using u32 = System.UInt32;
using gps_time_t = System.UInt64;
namespace MissionPlanner.Utilities
{
public class rtcm3 : ICorrections
{
const byte RTCM3PREAMB = 0xD3;
int step = 0;
byte[] buffer = new u8[1024 * 4];
u32 payloadlen = 0;
int msglencount = 0;
rtcmpreamble pre;
public int Read(byte data)
{
switch (step)
{
default:
case 0:
if (data == RTCM3PREAMB)
{
step = 1;
buffer[0] = data;
}
break;
case 1:
buffer[1] = data;
step++;
break;
case 2:
buffer[2] = data;
step++;
pre = new rtcmpreamble();
pre.Read(buffer);
payloadlen = pre.length;
msglencount = 0;
// reset on oversize packet
if (payloadlen > buffer.Length)
step = 0;
break;
case 3:
if (msglencount < (payloadlen))
{
buffer[msglencount + 3] = data;
msglencount++;
}
else
{
step++;
goto case 4;
}
break;
case 4:
buffer[payloadlen + 3] = data;
step++;
break;
case 5:
buffer[payloadlen + 3 + 1] = data;
step++;
break;
case 6:
buffer[payloadlen + 3 + 2] = data;
payloadlen = payloadlen + 3;
u32 crc = crc24.crc24q(buffer, payloadlen, 0);
u32 crcpacket = getbitu(buffer, payloadlen * 8, 24);
if (crc == crcpacket)
{
rtcmheader head = new rtcmheader();
head.Read(buffer);
step = 0;
return head.messageno;
}
step = 0;
break;
}
return -1;
}
static uint getbitu(u8[] buff, u32 pos, u32 len)
{
uint bits = 0;
u32 i;
for (i = pos; i < pos + len; i++)
bits = (uint)((bits << 1) + ((buff[i / 8] >> (int)(7 - i % 8)) & 1u));
return bits;
}
static void setbitu(u8[] buff, u32 pos, u32 len, u32 data)
{
u32 mask = 1u << (int)(len - 1);
if (len <= 0 || 32 < len) return;
for (u32 i = pos; i < pos + len; i++, mask >>= 1)
{
if ((data & mask) > 0)
buff[i / 8] |= (byte)(1u << (int)(7 - i % 8));
else
buff[i / 8] &= (byte)(~(1u << (int)(7 - i % 8)));
}
}
public class rtcmpreamble
{
public u8 preamble = RTCM3PREAMB;
public u8 resv1;
public u16 length;
public void Read(byte[] buffer)
{
uint i = 0;
preamble = (byte)getbitu(buffer, i, 8); i += 8;
resv1 = (byte)getbitu(buffer, i, 6); i += 6;
length = (u16)getbitu(buffer, i, 10); i += 10;
}
public byte[] Write(byte[] buffer)
{
uint i = 0;
setbitu(buffer, i, 8, RTCM3PREAMB); i += 8;
setbitu(buffer, i, 6, resv1); i += 6;
setbitu(buffer, i, 10, length); i += 10;
return buffer;
}
}
public class rtcmheader
{
public u16 messageno;
public u16 refstationid;
public u32 epoch;
public u8 sync;
public u8 nsat;
public u8 smoothind;
public u8 smoothint;
public void Read(byte[] buffer)
{
u32 i = 24;
messageno = (u16)getbitu(buffer, i, 12); i += 12; /* message no */
refstationid = (u16)getbitu(buffer, i, 12); i += 12; /* ref station id */
epoch = (u32)getbitu(buffer, i, 30); i += 30; /* gps epoch time */
sync = (u8)getbitu(buffer, i, 1); i += 1; /* synchronous gnss flag */
nsat = (u8)getbitu(buffer, i, 5); i += 5; /* no of satellites */
smoothind = (u8)getbitu(buffer, i, 1); i += 1; /* smoothing indicator */
smoothint = (u8)getbitu(buffer, i, 3); i += 3; /* smoothing interval */
}
public byte[] Write(byte[] buffer)
{
u32 i = 24;
setbitu(buffer, i, 12, messageno); i += 12; /* message no */
setbitu(buffer, i, 12, refstationid); i += 12; /* ref station id */
setbitu(buffer, i, 30, epoch); i += 30; /* gps epoch time */
setbitu(buffer, i, 1, sync); i += 1; /* synchronous gnss flag */
setbitu(buffer, i, 5, nsat); i += 5; /* no of satellites */
setbitu(buffer, i, 1, smoothind); i += 1; /* smoothing indicator */
setbitu(buffer, i, 3, smoothint); i += 3; /* smoothing interval */
return buffer;
}
}
public class crc24
{
static u32[] crc24qtab = new u32[] {
0x000000, 0x864CFB, 0x8AD50D, 0x0C99F6, 0x93E6E1, 0x15AA1A, 0x1933EC, 0x9F7F17,
0xA18139, 0x27CDC2, 0x2B5434, 0xAD18CF, 0x3267D8, 0xB42B23, 0xB8B2D5, 0x3EFE2E,
0xC54E89, 0x430272, 0x4F9B84, 0xC9D77F, 0x56A868, 0xD0E493, 0xDC7D65, 0x5A319E,
0x64CFB0, 0xE2834B, 0xEE1ABD, 0x685646, 0xF72951, 0x7165AA, 0x7DFC5C, 0xFBB0A7,
0x0CD1E9, 0x8A9D12, 0x8604E4, 0x00481F, 0x9F3708, 0x197BF3, 0x15E205, 0x93AEFE,
0xAD50D0, 0x2B1C2B, 0x2785DD, 0xA1C926, 0x3EB631, 0xB8FACA, 0xB4633C, 0x322FC7,
0xC99F60, 0x4FD39B, 0x434A6D, 0xC50696, 0x5A7981, 0xDC357A, 0xD0AC8C, 0x56E077,
0x681E59, 0xEE52A2, 0xE2CB54, 0x6487AF, 0xFBF8B8, 0x7DB443, 0x712DB5, 0xF7614E,
0x19A3D2, 0x9FEF29, 0x9376DF, 0x153A24, 0x8A4533, 0x0C09C8, 0x00903E, 0x86DCC5,
0xB822EB, 0x3E6E10, 0x32F7E6, 0xB4BB1D, 0x2BC40A, 0xAD88F1, 0xA11107, 0x275DFC,
0xDCED5B, 0x5AA1A0, 0x563856, 0xD074AD, 0x4F0BBA, 0xC94741, 0xC5DEB7, 0x43924C,
0x7D6C62, 0xFB2099, 0xF7B96F, 0x71F594, 0xEE8A83, 0x68C678, 0x645F8E, 0xE21375,
0x15723B, 0x933EC0, 0x9FA736, 0x19EBCD, 0x8694DA, 0x00D821, 0x0C41D7, 0x8A0D2C,
0xB4F302, 0x32BFF9, 0x3E260F, 0xB86AF4, 0x2715E3, 0xA15918, 0xADC0EE, 0x2B8C15,
0xD03CB2, 0x567049, 0x5AE9BF, 0xDCA544, 0x43DA53, 0xC596A8, 0xC90F5E, 0x4F43A5,
0x71BD8B, 0xF7F170, 0xFB6886, 0x7D247D, 0xE25B6A, 0x641791, 0x688E67, 0xEEC29C,
0x3347A4, 0xB50B5F, 0xB992A9, 0x3FDE52, 0xA0A145, 0x26EDBE, 0x2A7448, 0xAC38B3,
0x92C69D, 0x148A66, 0x181390, 0x9E5F6B, 0x01207C, 0x876C87, 0x8BF571, 0x0DB98A,
0xF6092D, 0x7045D6, 0x7CDC20, 0xFA90DB, 0x65EFCC, 0xE3A337, 0xEF3AC1, 0x69763A,
0x578814, 0xD1C4EF, 0xDD5D19, 0x5B11E2, 0xC46EF5, 0x42220E, 0x4EBBF8, 0xC8F703,
0x3F964D, 0xB9DAB6, 0xB54340, 0x330FBB, 0xAC70AC, 0x2A3C57, 0x26A5A1, 0xA0E95A,
0x9E1774, 0x185B8F, 0x14C279, 0x928E82, 0x0DF195, 0x8BBD6E, 0x872498, 0x016863,
0xFAD8C4, 0x7C943F, 0x700DC9, 0xF64132, 0x693E25, 0xEF72DE, 0xE3EB28, 0x65A7D3,
0x5B59FD, 0xDD1506, 0xD18CF0, 0x57C00B, 0xC8BF1C, 0x4EF3E7, 0x426A11, 0xC426EA,
0x2AE476, 0xACA88D, 0xA0317B, 0x267D80, 0xB90297, 0x3F4E6C, 0x33D79A, 0xB59B61,
0x8B654F, 0x0D29B4, 0x01B042, 0x87FCB9, 0x1883AE, 0x9ECF55, 0x9256A3, 0x141A58,
0xEFAAFF, 0x69E604, 0x657FF2, 0xE33309, 0x7C4C1E, 0xFA00E5, 0xF69913, 0x70D5E8,
0x4E2BC6, 0xC8673D, 0xC4FECB, 0x42B230, 0xDDCD27, 0x5B81DC, 0x57182A, 0xD154D1,
0x26359F, 0xA07964, 0xACE092, 0x2AAC69, 0xB5D37E, 0x339F85, 0x3F0673, 0xB94A88,
0x87B4A6, 0x01F85D, 0x0D61AB, 0x8B2D50, 0x145247, 0x921EBC, 0x9E874A, 0x18CBB1,
0xE37B16, 0x6537ED, 0x69AE1B, 0xEFE2E0, 0x709DF7, 0xF6D10C, 0xFA48FA, 0x7C0401,
0x42FA2F, 0xC4B6D4, 0xC82F22, 0x4E63D9, 0xD11CCE, 0x575035, 0x5BC9C3, 0xDD8538
};
/** Calculate Qualcomm 24-bit Cyclical Redundancy Check (CRC-24Q).
*
* The CRC polynomial used is:
* \f[
* x^{24} + x^{23} + x^{18} + x^{17} + x^{14} + x^{11} + x^{10} +
* x^7 + x^6 + x^5 + x^4 + x^3 + x+1
* \f]
* Mask 0x1864CFB, not reversed, not XOR'd
*
* \param buf Array of data to calculate CRC for
* \param len Length of data array
* \param crc Initial CRC value
*
* \return CRC-24Q value
*/
public static u32 crc24q(u8[] buf, u32 len, u32 crc)
{
for (u32 i = 0; i < len; i++)
crc = ((crc << 8) & 0xFFFFFF) ^ crc24qtab[(crc >> 16) ^ buf[i]];
return crc;
}
}
public s32 length
{
get { return (s32)(payloadlen + 2 + 1); }
}
public u8[] packet
{
get { return buffer; }
}
}
} | uwafsl/MissionPlanner | Utilities/rtcm3.cs | C# | gpl-3.0 | 10,196 |
#ifndef __al_included_allegro5_fullscreen_mode_h
#define __al_included_allegro5_fullscreen_mode_h
#include "allegro5/base.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Type: ALLEGRO_DISPLAY_MODE
*/
typedef struct ALLEGRO_DISPLAY_MODE
{
int width;
int height;
int format;
int refresh_rate;
} ALLEGRO_DISPLAY_MODE;
AL_FUNC(int, al_get_num_display_modes, (void));
AL_FUNC(ALLEGRO_DISPLAY_MODE*, al_get_display_mode, (int index,
ALLEGRO_DISPLAY_MODE *mode));
#ifdef __cplusplus
}
#endif
#endif
/* vim: set ts=8 sts=3 sw=3 et: */
| ivankrato/The-Battle-of-the-Two-Armies | packages/Allegro.5.2.2.0/build/native/include/allegro5/fullscreen_mode.h | C | gpl-3.0 | 561 |
// Set iterators produces entries in the order they were inserted.
var set = Set();
var i;
for (i = 7; i !== 1; i = i * 7 % 1117)
set.add(i);
assertEq(set.size, 557);
i = 7;
for (var v of set) {
assertEq(v, i);
i = i * 7 % 1117;
}
assertEq(i, 1);
| SlateScience/MozillaJS | js/src/jit-test/tests/collections/Set-iterator-order.js | JavaScript | mpl-2.0 | 261 |
% include base.dockerfile
RUN \
apt-get install -qy --no-install-recommends \
#
# Testing decisionlib (see etc/taskcluster/mock.py)
python3-coverage \
#
# Multiple C/C++ dependencies built from source
g++ \
make \
cmake \
#
# ANGLE
xorg-dev \
#
# mozjs (SpiderMonkey)
autoconf2.13 \
#
# Bindgen (for SpiderMonkey bindings)
clang \
#
# GStreamer
libgstreamer-plugins-bad1.0-dev \
#
# OpenSSL
libssl1.0-dev \
#
# blurz
libdbus-1-dev \
#
# Skia
libglu1-mesa-dev \
libbz2-dev \
#
#
&& \
#
#
curl https://sh.rustup.rs -sSf | sh -s -- --default-toolchain none -y && \
#
#
curl -sSfL \
https://github.com/mozilla/sccache/releases/download/0.2.7/sccache-0.2.7-x86_64-unknown-linux-musl.tar.gz \
| tar -xz --strip-components=1 -C /usr/local/bin/ \
sccache-0.2.7-x86_64-unknown-linux-musl/sccache
| danlrobertson/servo | etc/taskcluster/docker/build.dockerfile | Dockerfile | mpl-2.0 | 1,104 |
/**
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Place it on classes which you want to be beans created conditionally based on
* OpenMRS version and/or started modules.
*
* @since 1.10, 1.9.8, 1.8.5, 1.7.5
*/
@Target( { ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OpenmrsProfile {
public String openmrsVersion() default "";
public String[] modules() default {};
}
| jembi/openmrs-core | api/src/main/java/org/openmrs/annotation/OpenmrsProfile.java | Java | mpl-2.0 | 1,065 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Unicode tests - reference rending</title>
<style>
/* work around unreliable form-control rendering on Gtk+3 (see bug 1223198): */
input { -moz-appearance: none; }
</style>
</head>
<body>
<div><p lang="hi">स्टार</p></div>
<input disabled>
</body>
</html>
| Yukarumya/Yukarum-Redfoxes | layout/reftests/unicode/unicode-ref.html | HTML | mpl-2.0 | 374 |
<a name="docs"></a>
## Что дальше?
Информацию о БЭМ-методологии, инструментарии и новостях в мире БЭМ смотрите на сайте [bem.info](https://ru.bem.info/).
Полную информацию обо всех методах API `i-bem.js` можно найти в разделе [JSDoc](https://ru.bem.info/libs/bem-core/current/desktop/i-bem/jsdoc/) блока `i-bem`.
Обменяться опытом и задать вопрос опытным пользователям и разработчикам `i-bem.js` можно на [форуме](https://ru.bem.info/forum/).
Примеры использования `i-bem.js` и дополнительную информацию смотрите в статьях:
* [JavaScript по БЭМ: основные понятия](https://ru.bem.info/articles/bem-js-main-terms/).
* [Справочное руководство по i-bem.js](https://ru.bem.info/tutorials/bem-js-tutorial/).
* [Создаем свой проект на БЭМ](https://ru.bem.info/tutorials/start-with-project-stub/).
* [БЭМ-приложение на Leaflet и API 2GIS](https://ru.bem.info/articles/firm-card-story/).
| megatolya/bem-core | common.docs/i-bem-js/i-bem-js-extras.ru.md | Markdown | mpl-2.0 | 1,235 |
<!--
Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
-->
<!DOCTYPE html>
<html>
<head>
<title>CSS Masking: Test clip-path and polygon with margin-box</title>
<link rel="author" title="Dirk Schulze" href="mailto:dschulze@adobe.com">
<link rel="help" href="http://www.w3.org/TR/css-masking-1/#clipping-paths">
<link rel="help" href="http://www.w3.org/TR/css-masking-1/#propdef-clip-path">
<link rel="match" href="clip-path-stripes-002-ref.html">
<meta name="assert" content="The clip-path property allows specifying
basic shapes and reference boxes. This test checks the usage of the correct
reference box 'margin-box' for the polygon() function by mixing percentage
and absolute values as coordinates. On sucess you should see a green
vertical stripe next to a lime green vertical stripe. Both should be of equal
size.">
</head>
<style>
div {
width: 50px;
height: 50px;
background-color: green;
padding: 25px;
margin: 25px;
border: red solid 25px;
border-left: lime solid 25px;
}
</style>
<body>
<p>The test passes if you see a green vertical stripe next to a lime green vertical stripe, both stripes should be of equal size and there should be no red.</p>
<div style="clip-path: polygon(12.5% 25%, 37.5% 50px, 75px 50%, 25px 100px) margin-box"></div>
</body>
</html> | Yukarumya/Yukarum-Redfoxes | layout/reftests/svg/svg-integration/clip-path/clip-path-polygon-008.html | HTML | mpl-2.0 | 1,377 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::any::Any;
use std::boxed::FnBox;
use std::cell::RefCell;
use std::panic::{PanicInfo, take_hook, set_hook};
use std::sync::{Once, ONCE_INIT};
use std::thread;
// only set the panic hook once
static HOOK_SET: Once = ONCE_INIT;
/// TLS data pertaining to how failures should be reported
pub struct PanicHandlerLocal {
/// failure handler passed through spawn_named_with_send_on_failure
pub fail: Box<FnBox(&Any)>
}
thread_local!(pub static LOCAL_INFO: RefCell<Option<PanicHandlerLocal>> = RefCell::new(None));
/// Set the thread-local panic hook
pub fn set_thread_local_hook(local: Box<FnBox(&Any)>) {
LOCAL_INFO.with(|i| *i.borrow_mut() = Some(PanicHandlerLocal { fail: local }));
}
/// Initiates the custom panic hook
/// Should be called in main() after arguments have been parsed
pub fn initiate_panic_hook() {
// Set the panic handler only once. It is global.
HOOK_SET.call_once(|| {
// The original backtrace-printing hook. We still want to call this
let hook = take_hook();
let new_hook = move |info: &PanicInfo| {
let payload = info.payload();
let name = thread::current().name().unwrap_or("<unknown thread>").to_string();
// Notify error handlers stored in LOCAL_INFO if any
LOCAL_INFO.with(|i| {
if let Some(local_info) = i.borrow_mut().take() {
debug!("Thread `{}` failed, notifying error handlers", name);
(local_info.fail).call_box((payload, ));
} else {
hook(&info);
}
});
};
set_hook(Box::new(new_hook));
});
}
| achals/servo | components/util/panicking.rs | Rust | mpl-2.0 | 1,877 |
package tc.oc.commons.core.plugin;
import java.util.Set;
import tc.oc.commons.core.commands.CommandRegistry;
import tc.oc.commons.core.commands.Commands;
import tc.oc.commons.core.commands.NestedCommands;
import tc.oc.minecraft.api.event.Activatable;
import tc.oc.commons.core.inject.Facet;
/**
* Something that needs to be enabled and disabled (along with a plugin).
*
* Each plugin has a private set of facets, configured through a {@link PluginFacetBinder}.
* To get the instances, @Inject a {@link Set< PluginFacet >}.
*
* Facets are automatically enabled and disabled at the same time as the
* plugin they are bound to.
*
* If a facet implements the {@link tc.oc.minecraft.api.event.Listener} interfaces,
* it will also be registered to receive events.
*
* If it implements {@link Commands} or {@link NestedCommands}, it will be registered
* through a {@link CommandRegistry}.
*
* Specific plugins may do other automatic things with their own facets, be we
* don't yet have a framework for extending facets across all plugins.
*/
public interface PluginFacet extends Facet, Activatable {
}
| cswhite2000/ProjectAres | Util/core/src/main/java/tc/oc/commons/core/plugin/PluginFacet.java | Java | agpl-3.0 | 1,116 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" >
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>OHLC Charts</title>
<!--[if IE]><script language="javascript" type="text/javascript" src="../excanvas.js"></script><![endif]-->
<link rel="stylesheet" type="text/css" href="../jquery.jqplot.css" />
<link rel="stylesheet" type="text/css" href="examples.css" />
<!-- BEGIN: load jquery -->
<script language="javascript" type="text/javascript" src="../jquery-1.4.2.min.js"></script>
<!-- END: load jquery -->
<!-- BEGIN: load jqplot -->
<script language="javascript" type="text/javascript" src="../jquery.jqplot.js"></script>
<script language="javascript" type="text/javascript" src="../plugins/jqplot.dateAxisRenderer.js"></script>
<script language="javascript" type="text/javascript" src="../plugins/jqplot.categoryAxisRenderer.js"></script>
<script language="javascript" type="text/javascript" src="../plugins/jqplot.ohlcRenderer.js"></script>
<script language="javascript" type="text/javascript" src="../plugins/jqplot.highlighter.js"></script>
<script language="javascript" type="text/javascript" src="../plugins/jqplot.cursor.js"></script>
<style type="text/css">
.jqplot-target {
margin-bottom: 2em;
}
pre {
background: #D8F4DC;
border: 1px solid rgb(200, 200, 200);
padding-top: 1em;
padding-left: 3em;
padding-bottom: 1em;
margin-top: 1em;
margin-bottom: 4em;
}
p {
margin: 2em 0;
}
.note {
font-size: 0.8em;
}
</style>
<!-- END: load jqplot -->
<script class="common" type="text/javascript">
$.jqplot.config.enablePlugins = true;
ohlc = [['07/06/09', 138.7, 139.68, 135.18, 135.4],
['06/29/09', 143.46, 144.66, 139.79, 140.02],
['06/22/09', 140.67, 143.56, 132.88, 142.44],
['06/15/09', 136.01, 139.5, 134.53, 139.48],
['06/08/09', 143.82, 144.56, 136.04, 136.97],
['06/01/09', 136.47, 146.4, 136, 144.67],
['05/26/09', 124.76, 135.9, 124.55, 135.81],
['05/18/09', 123.73, 129.31, 121.57, 122.5],
['05/11/09', 127.37, 130.96, 119.38, 122.42],
['05/04/09', 128.24, 133.5, 126.26, 129.19],
['04/27/09', 122.9, 127.95, 122.66, 127.24],
['04/20/09', 121.73, 127.2, 118.6, 123.9],
['04/13/09', 120.01, 124.25, 115.76, 123.42],
['04/06/09', 114.94, 120, 113.28, 119.57],
['03/30/09', 104.51, 116.13, 102.61, 115.99],
['03/23/09', 102.71, 109.98, 101.75, 106.85],
['03/16/09', 96.53, 103.48, 94.18, 101.59],
['03/09/09', 84.18, 97.2, 82.57, 95.93],
['03/02/09', 88.12, 92.77, 82.33, 85.3],
['02/23/09', 91.65, 92.92, 86.51, 89.31],
['02/17/09', 96.87, 97.04, 89, 91.2],
['02/09/09', 100, 103, 95.77, 99.16],
['02/02/09', 89.1, 100, 88.9, 99.72],
['01/26/09', 88.86, 95, 88.3, 90.13],
['01/20/09', 81.93, 90, 78.2, 88.36],
['01/12/09', 90.46, 90.99, 80.05, 82.33],
['01/05/09', 93.17, 97.17, 90.04, 90.58],
['12/29/08', 86.52, 91.04, 84.72, 90.75],
['12/22/08', 90.02, 90.03, 84.55, 85.81],
['12/15/08', 95.99, 96.48, 88.02, 90],
['12/08/08', 97.28, 103.6, 92.53, 98.27],
['12/01/08', 91.3, 96.23, 86.5, 94],
['11/24/08', 85.21, 95.25, 84.84, 92.67],
['11/17/08', 88.48, 91.58, 79.14, 82.58],
['11/10/08', 100.17, 100.4, 86.02, 90.24],
['11/03/08', 105.93, 111.79, 95.72, 98.24],
['10/27/08', 95.07, 112.19, 91.86, 107.59],
['10/20/08', 99.78, 101.25, 90.11, 96.38],
['10/13/08', 104.55, 116.4, 85.89, 97.4],
['10/06/08', 91.96, 101.5, 85, 96.8],
['09/29/08', 119.62, 119.68, 94.65, 97.07],
['09/22/08', 139.94, 140.25, 123, 128.24],
['09/15/08', 142.03, 147.69, 120.68, 140.91],
['09/08/08', 164.57, 164.89, 146, 148.94]
];
ohlc_b = [['07/06/09', 138.7, 139.68, 135.18, 135.4, 'j'],
['06/29/09', 143.46, 144.66, 139.79, 140.02, 'q'],
['06/22/09', 140.67, 143.56, 132.88, 142.44, 'p'],
['06/15/09', 136.01, 139.5, 134.53, 139.48, 'l'],
['06/08/09', 143.82, 144.56, 136.04, 136.97, 'o'],
['06/01/09', 136.47, 146.4, 136, 144.67, 't'],
['05/26/09', 124.76, 135.9, 124.55, 135.81, '_'],
['05/18/09', 123.73, 129.31, 121.57, 122.5, 'c'],
['05/11/09', 127.37, 130.96, 119.38, 122.42, 'h'],
['05/04/09', 128.24, 133.5, 126.26, 129.19, 'a'],
['04/27/09', 122.9, 127.95, 122.66, 127.24, 'r'],
['04/20/09', 121.73, 127.2, 118.6, 123.9, 't'],
['04/13/09', 120.01, 124.25, 115.76, 123.42, 's']
];
hlc = [['07/06/09', 139.68, 135.18, 135.4],
['06/29/09', 144.66, 139.79, 140.02],
['06/22/09', 143.56, 132.88, 142.44],
['06/15/09', 139.5, 134.53, 139.48],
['06/08/09', 144.56, 136.04, 136.97],
['06/01/09', 146.4, 136, 144.67],
['05/26/09', 135.9, 124.55, 135.81],
['05/18/09', 129.31, 121.57, 122.5],
['05/11/09', 130.96, 119.38, 122.42],
['05/04/09', 133.5, 126.26, 129.19],
['04/27/09', 127.95, 122.66, 127.24],
['04/20/09', 127.2, 118.6, 123.9],
['04/13/09', 124.25, 115.76, 123.42],
['04/06/09', 120, 113.28, 119.57],
['03/30/09', 116.13, 102.61, 115.99],
['03/23/09', 109.98, 101.75, 106.85],
['03/16/09', 103.48, 94.18, 101.59],
['03/09/09', 97.2, 82.57, 95.93],
['03/02/09', 92.77, 82.33, 85.3],
['02/23/09', 92.92, 86.51, 89.31],
['02/17/09', 97.04, 89, 91.2],
['02/09/09', 103, 95.77, 99.16],
['02/02/09', 100, 88.9, 99.72],
['01/26/09', 95, 88.3, 90.13],
['01/20/09', 90, 78.2, 88.36],
['01/12/09', 90.99, 80.05, 82.33],
['01/05/09', 97.17, 90.04, 90.58],
['12/29/08', 91.04, 84.72, 90.75],
['12/22/08', 90.03, 84.55, 85.81],
['12/15/08', 96.48, 88.02, 90],
['12/08/08', 103.6, 92.53, 98.27],
['12/01/08', 96.23, 86.5, 94],
['11/24/08', 95.25, 84.84, 92.67],
['11/17/08', 91.58, 79.14, 82.58],
['11/10/08', 100.4, 86.02, 90.24],
['11/03/08', 111.79, 95.72, 98.24],
['10/27/08', 112.19, 91.86, 107.59],
['10/20/08', 101.25, 90.11, 96.38],
['10/13/08', 116.4, 85.89, 97.4],
['10/06/08', 101.5, 85, 96.8],
['09/29/08', 119.68, 94.65, 97.07],
['09/22/08', 140.25, 123, 128.24],
['09/15/08', 147.69, 120.68, 140.91],
['09/08/08', 164.89, 146, 148.94]
];
</script>
<script class="code" type="text/javascript">$(document).ready(function(){
plot1 = $.jqplot('chart1',[ohlc],{
title: 'Chart',
axesDefaults:{},
axes: {
xaxis: {
renderer:$.jqplot.DateAxisRenderer,
tickOptions:{formatString:'%y.%m'}
},
yaxis: {
tickOptions:{formatString:'%.2f'}
}
},
series: [{renderer:$.jqplot.OHLCRenderer, rendererOptions:{}}],
cursor:{
zoom:true,
tooltipOffset: 10,
tooltipLocation: 'nw'
}
});
});</script>
<script class="code" type="text/javascript">$(document).ready(function(){
plot2 = $.jqplot('chart2',[ohlc],{
title: 'Chart',
axesDefaults:{},
axes: {
xaxis: {
renderer:$.jqplot.DateAxisRenderer,
tickOptions:{formatString:'%y.%m'}
},
yaxis: {
tickOptions:{formatString:'%.2f'}
}
},
series: [{renderer:$.jqplot.OHLCRenderer, rendererOptions:{candleStick:true}}],
cursor:{
zoom:true,
tooltipOffset: 10,
tooltipLocation: 'nw'
},
highlighter: {
showMarker:false,
tooltipAxes: 'xy',
yvalues: 4,
formatString:'<table class="jqplot-highlighter"> \
<tr><td>date:</td><td>%s</td></tr> \
<tr><td>open:</td><td>%s</td></tr> \
<tr><td>hi:</td><td>%s</td></tr> \
<tr><td>low:</td><td>%s</td></tr> \
<tr><td>close:</td><td>%s</td></tr></table>'
}
});
});</script>
<script class="code" type="text/javascript">$(document).ready(function(){
plot2b = $.jqplot('chart2b',[ohlc_b],{
title: 'Chart',
axesDefaults:{},
axes: {
xaxis: {
renderer:$.jqplot.DateAxisRenderer,
tickOptions:{formatString:'%y.%m'}
},
yaxis: {
tickOptions:{formatString:'%.2f'}
}
},
series: [{renderer:$.jqplot.OHLCRenderer, rendererOptions:{candleStick:true}}],
cursor:{
zoom:true,
tooltipOffset: 10,
tooltipLocation: 'nw'
},
highlighter: {
showMarker:false,
tooltipAxes: 'xy',
yvalues: 5,
formatString:'<table class="jqplot-highlighter"> \
<tr><td>date:</td><td>%s</td></tr> \
<tr><td>open:</td><td>%s</td></tr> \
<tr><td>hi:</td><td>%s</td></tr> \
<tr><td>low:</td><td>%s</td></tr> \
<tr><td>close:</td><td>%s</td></tr> \
<tr><td>letter:</td><td>%s</td></tr></table>'
}
});
});</script>
<script class="code" type="text/javascript">$(document).ready(function(){
plot3 = $.jqplot('chart3',[hlc],{
title: 'Chart',
axesDefaults:{},
axes: {
xaxis: {
renderer:$.jqplot.DateAxisRenderer,
tickOptions:{formatString:'%Y.%m'}
},
yaxis: {
tickOptions:{formatString:'%.2f'}
}
},
series: [{renderer:$.jqplot.OHLCRenderer, rendererOptions:{}}],
cursor:{
zoom:true,
tooltipOffset: 10,
tooltipLocation: 'nw'
}
});
});</script>
<script class="code" type="text/javascript">$(document).ready(function(){
var catOHLC = [[1, 138.7, 139.68, 135.18, 135.4],
[2, 143.46, 144.66, 139.79, 140.02],
[3, 140.67, 143.56, 132.88, 142.44],
[4, 136.01, 139.5, 134.53, 139.48],
[5, 143.82, 144.56, 136.04, 136.97],
[6, 136.47, 146.4, 136, 144.67],
[7, 124.76, 135.9, 124.55, 135.81],
[8, 123.73, 129.31, 121.57, 122.5]];
var ticks = ['Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun', 'Mon', 'Tue'];
plot4 = $.jqplot('chart4',[catOHLC],{
axes: {
xaxis: {
renderer:$.jqplot.CategoryAxisRenderer,
ticks:ticks
},
yaxis: {
tickOptions:{formatString:'$%.2f'}
}
},
series: [{renderer:$.jqplot.OHLCRenderer, rendererOptions:{candleStick:true}}]
});
});</script>
<script type="text/javascript">
$(document).ready(function(){
$('script.code').each(function(index) {
$('pre.code').eq(index).text($(this).html());
});
$('script.common').each(function(index) {
$('pre.common').eq(index).html($(this).html());
});
$(document).unload(function() {$('*').unbind(); });
});
</script>
</head>
<body>
<?php include "nav.inc"; ?>
<div id="chart1" class="code" style="margin:20px;height:240px; width:640px;"></div>
<pre class="code"></pre>
<div id="chart2" class="code" style="margin:20px;height:240px; width:640px;"></div>
<pre class="code"></pre>
<div id="chart2b" class="code" style="margin:20px;height:240px; width:640px;"></div>
<pre class="code"></pre>
<div id="chart3" class="code" style="margin:20px;height:240px; width:640px;"></div>
<pre class="code"></pre>
<div id="chart4" class="code" style="margin:20px;height:320px; width:500px;"></div>
<pre class="code"></pre>
<p>The examples below use the folowing code:</p>
<pre class="common"></pre>
</body>
</html> | tendenci/recessart | vendor/gems/fluxx_engine/public/javascripts/lib/jqplot/examples/OHLC.html | HTML | agpl-3.0 | 11,678 |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
exports.FLACDemuxer = require('./src/demuxer');
exports.FLACDecoder = require('./src/decoder');
require('./src/ogg');
},{"./src/decoder":2,"./src/demuxer":3,"./src/ogg":4}],2:[function(require,module,exports){
/*
* FLAC.js - Free Lossless Audio Codec decoder in JavaScript
* Original C version from FFmpeg (c) 2003 Alex Beregszaszi
* JavaScript port by Devon Govett and Jens Nockert of Official.fm Labs
*
* Licensed under the same terms as the original. The original
* license follows.
*
* FLAC.js 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.
*
* FLAC.js 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.
*
*/
var AV = (window.AV);
var FLACDecoder = AV.Decoder.extend(function() {
AV.Decoder.register('flac', this);
this.prototype.setCookie = function(cookie) {
this.cookie = cookie;
// initialize arrays
this.decoded = [];
for (var i = 0; i < this.format.channelsPerFrame; i++) {
this.decoded[i] = new Int32Array(cookie.maxBlockSize);
}
};
const BLOCK_SIZES = new Int16Array([
0, 192, 576 << 0, 576 << 1, 576 << 2, 576 << 3, 0, 0,
256 << 0, 256 << 1, 256 << 2, 256 << 3, 256 << 4, 256 << 5, 256 << 6, 256 << 7
]);
const SAMPLE_RATES = new Int32Array([
0, 88200, 176400, 192000,
8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000,
0, 0, 0, 0
]);
const SAMPLE_SIZES = new Int8Array([
0, 8, 12, 0, 16, 20, 24, 0
]);
const MAX_CHANNELS = 8,
CHMODE_INDEPENDENT = 0,
CHMODE_LEFT_SIDE = 8,
CHMODE_RIGHT_SIDE = 9,
CHMODE_MID_SIDE = 10;
this.prototype.readChunk = function() {
var stream = this.bitstream;
if (!stream.available(32))
return;
// frame sync code
if ((stream.read(15) & 0x7FFF) !== 0x7FFC)
throw new Error('Invalid sync code');
var isVarSize = stream.read(1), // variable block size stream code
bsCode = stream.read(4), // block size
srCode = stream.read(4), // sample rate code
chMode = stream.read(4), // channel mode
bpsCode = stream.read(3); // bits per sample
stream.advance(1); // reserved bit
// channels
this.chMode = chMode;
var channels;
if (chMode < MAX_CHANNELS) {
channels = chMode + 1;
this.chMode = CHMODE_INDEPENDENT;
} else if (chMode <= CHMODE_MID_SIDE) {
channels = 2;
} else {
throw new Error('Invalid channel mode');
}
if (channels !== this.format.channelsPerFrame)
throw new Error('Switching channel layout mid-stream not supported.');
// bits per sample
if (bpsCode === 3 || bpsCode === 7)
throw new Error('Invalid sample size code');
this.bps = SAMPLE_SIZES[bpsCode];
if (this.bps !== this.format.bitsPerChannel)
throw new Error('Switching bits per sample mid-stream not supported.');
var sampleShift, is32;
if (this.bps > 16) {
sampleShift = 32 - this.bps;
is32 = true;
} else {
sampleShift = 16 - this.bps;
is32 = false;
}
// sample number or frame number
// see http://www.hydrogenaudio.org/forums/index.php?s=ea7085ffe6d57132c36e6105c0d434c9&showtopic=88390&pid=754269&st=0&#entry754269
var ones = 0;
while (stream.read(1) === 1)
ones++;
var frame_or_sample_num = stream.read(7 - ones);
for (; ones > 1; ones--) {
stream.advance(2); // == 2
frame_or_sample_num = (frame_or_sample_num << 6) | stream.read(6);
}
// block size
if (bsCode === 0)
throw new Error('Reserved blocksize code');
else if (bsCode === 6)
this.blockSize = stream.read(8) + 1;
else if (bsCode === 7)
this.blockSize = stream.read(16) + 1;
else
this.blockSize = BLOCK_SIZES[bsCode];
// sample rate
var sampleRate;
if (srCode < 12)
sampleRate = SAMPLE_RATES[srCode];
else if (srCode === 12)
sampleRate = stream.read(8) * 1000;
else if (srCode === 13)
sampleRate = stream.read(16);
else if (srCode === 14)
sampleRate = stream.read(16) * 10;
else
throw new Error('Invalid sample rate code');
stream.advance(8); // skip CRC check
// subframes
for (var i = 0; i < channels; i++)
this.decodeSubframe(i);
stream.align();
stream.advance(16); // skip CRC frame footer
var output = new ArrayBuffer(this.blockSize * channels * this.bps / 8),
buf = is32 ? new Int32Array(output) : new Int16Array(output),
blockSize = this.blockSize,
decoded = this.decoded,
j = 0;
switch (this.chMode) {
case CHMODE_INDEPENDENT:
for (var k = 0; k < blockSize; k++) {
for (var i = 0; i < channels; i++) {
buf[j++] = decoded[i][k] << sampleShift;
}
}
break;
case CHMODE_LEFT_SIDE:
for (var i = 0; i < blockSize; i++) {
var left = decoded[0][i],
right = decoded[1][i];
buf[j++] = left << sampleShift;
buf[j++] = (left - right) << sampleShift;
}
break;
case CHMODE_RIGHT_SIDE:
for (var i = 0; i < blockSize; i++) {
var left = decoded[0][i],
right = decoded[1][i];
buf[j++] = (left + right) << sampleShift;
buf[j++] = right << sampleShift;
}
break;
case CHMODE_MID_SIDE:
for (var i = 0; i < blockSize; i++) {
var left = decoded[0][i],
right = decoded[1][i];
left -= right >> 1;
buf[j++] = (left + right) << sampleShift;
buf[j++] = left << sampleShift;
}
break;
}
return buf;
};
this.prototype.decodeSubframe = function(channel) {
var wasted = 0,
stream = this.bitstream,
blockSize = this.blockSize,
decoded = this.decoded;
this.curr_bps = this.bps;
if (channel === 0) {
if (this.chMode === CHMODE_RIGHT_SIDE)
this.curr_bps++;
} else {
if (this.chMode === CHMODE_LEFT_SIDE || this.chMode === CHMODE_MID_SIDE)
this.curr_bps++;
}
if (stream.read(1))
throw new Error("Invalid subframe padding");
var type = stream.read(6);
if (stream.read(1)) {
wasted = 1;
while (!stream.read(1))
wasted++;
this.curr_bps -= wasted;
}
if (this.curr_bps > 32)
throw new Error("decorrelated bit depth > 32 (" + this.curr_bps + ")");
if (type === 0) {
var tmp = stream.read(this.curr_bps, true);
for (var i = 0; i < blockSize; i++)
decoded[channel][i] = tmp;
} else if (type === 1) {
var bps = this.curr_bps;
for (var i = 0; i < blockSize; i++)
decoded[channel][i] = stream.read(bps, true);
} else if ((type >= 8) && (type <= 12)) {
this.decode_subframe_fixed(channel, type & ~0x8);
} else if (type >= 32) {
this.decode_subframe_lpc(channel, (type & ~0x20) + 1);
} else {
throw new Error("Invalid coding type");
}
if (wasted) {
for (var i = 0; i < blockSize; i++)
decoded[channel][i] <<= wasted;
}
};
this.prototype.decode_subframe_fixed = function(channel, predictor_order) {
var decoded = this.decoded[channel],
stream = this.bitstream,
bps = this.curr_bps;
// warm up samples
for (var i = 0; i < predictor_order; i++)
decoded[i] = stream.read(bps, true);
this.decode_residuals(channel, predictor_order);
var a = 0, b = 0, c = 0, d = 0;
if (predictor_order > 0)
a = decoded[predictor_order - 1];
if (predictor_order > 1)
b = a - decoded[predictor_order - 2];
if (predictor_order > 2)
c = b - decoded[predictor_order - 2] + decoded[predictor_order - 3];
if (predictor_order > 3)
d = c - decoded[predictor_order - 2] + 2 * decoded[predictor_order - 3] - decoded[predictor_order - 4];
switch (predictor_order) {
case 0:
break;
case 1:
case 2:
case 3:
case 4:
var abcd = new Int32Array([a, b, c, d]),
blockSize = this.blockSize;
for (var i = predictor_order; i < blockSize; i++) {
abcd[predictor_order - 1] += decoded[i];
for (var j = predictor_order - 2; j >= 0; j--) {
abcd[j] += abcd[j + 1];
}
decoded[i] = abcd[0];
}
break;
default:
throw new Error("Invalid Predictor Order " + predictor_order);
}
};
this.prototype.decode_subframe_lpc = function(channel, predictor_order) {
var stream = this.bitstream,
decoded = this.decoded[channel],
bps = this.curr_bps,
blockSize = this.blockSize;
// warm up samples
for (var i = 0; i < predictor_order; i++) {
decoded[i] = stream.read(bps, true);
}
var coeff_prec = stream.read(4) + 1;
if (coeff_prec === 16)
throw new Error("Invalid coefficient precision");
var qlevel = stream.read(5, true);
if (qlevel < 0)
throw new Error("Negative qlevel, maybe buggy stream");
var coeffs = new Int32Array(32);
for (var i = 0; i < predictor_order; i++) {
coeffs[i] = stream.read(coeff_prec, true);
}
this.decode_residuals(channel, predictor_order);
if (this.bps > 16)
throw new Error("no 64-bit integers in JS, could probably use doubles though");
for (var i = predictor_order; i < blockSize - 1; i += 2) {
var d = decoded[i - predictor_order],
s0 = 0, s1 = 0, c;
for (var j = predictor_order - 1; j > 0; j--) {
c = coeffs[j];
s0 += c * d;
d = decoded[i - j];
s1 += c * d;
}
c = coeffs[0];
s0 += c * d;
d = decoded[i] += (s0 >> qlevel);
s1 += c * d;
decoded[i + 1] += (s1 >> qlevel);
}
if (i < blockSize) {
var sum = 0;
for (var j = 0; j < predictor_order; j++)
sum += coeffs[j] * decoded[i - j - 1];
decoded[i] += (sum >> qlevel);
}
};
const INT_MAX = 32767;
this.prototype.decode_residuals = function(channel, predictor_order) {
var stream = this.bitstream,
method_type = stream.read(2);
if (method_type > 1)
throw new Error('Illegal residual coding method ' + method_type);
var rice_order = stream.read(4),
samples = (this.blockSize >>> rice_order);
if (predictor_order > samples)
throw new Error('Invalid predictor order ' + predictor_order + ' > ' + samples);
var decoded = this.decoded[channel],
sample = predictor_order,
i = predictor_order;
for (var partition = 0; partition < (1 << rice_order); partition++) {
var tmp = stream.read(method_type === 0 ? 4 : 5);
if (tmp === (method_type === 0 ? 15 : 31)) {
tmp = stream.read(5);
for (; i < samples; i++)
decoded[sample++] = stream.read(tmp, true);
} else {
for (; i < samples; i++)
decoded[sample++] = this.golomb(tmp, INT_MAX, 0);
}
i = 0;
}
};
const MIN_CACHE_BITS = 25;
this.prototype.golomb = function(k, limit, esc_len) {
var data = this.bitstream,
offset = data.bitPosition,
buf = data.peek(32 - offset) << offset,
v = 0;
var log = 31 - clz(buf | 1); // log2(buf)
if (log - k >= 32 - MIN_CACHE_BITS && 32 - log < limit) {
buf >>>= log - k;
buf += (30 - log) << k;
data.advance(32 + k - log);
v = buf;
} else {
for (var i = 0; data.read(1) === 0; i++)
buf = data.peek(32 - offset) << offset;
if (i < limit - 1) {
if (k)
buf = data.read(k);
else
buf = 0;
v = buf + (i << k);
} else if (i === limit - 1) {
buf = data.read(esc_len);
v = buf + 1;
} else {
v = -1;
}
}
return (v >> 1) ^ -(v & 1);
};
// Should be in the damned standard library...
function clz(input) {
var output = 0,
curbyte = 0;
while(true) { // emulate goto in JS using the break statement :D
curbyte = input >>> 24;
if (curbyte) break;
output += 8;
curbyte = input >>> 16;
if (curbyte & 0xff) break;
output += 8;
curbyte = input >>> 8;
if (curbyte & 0xff) break;
output += 8;
curbyte = input;
if (curbyte & 0xff) break;
output += 8;
return output;
}
if (!(curbyte & 0xf0))
output += 4;
else
curbyte >>>= 4;
if (curbyte & 0x8)
return output;
if (curbyte & 0x4)
return output + 1;
if (curbyte & 0x2)
return output + 2;
if (curbyte & 0x1)
return output + 3;
// shouldn't get here
return output + 4;
}
});
module.exports = FLACDecoder;
},{}],3:[function(require,module,exports){
/*
* FLAC.js - Free Lossless Audio Codec decoder in JavaScript
* By Devon Govett and Jens Nockert of Official.fm Labs
*
* FLAC.js 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.
*
* FLAC.js 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.
*
*/
var AV = (window.AV);
var FLACDemuxer = AV.Demuxer.extend(function() {
AV.Demuxer.register(this);
this.probe = function(buffer) {
return buffer.peekString(0, 4) === 'fLaC';
}
const STREAMINFO = 0,
PADDING = 1,
APPLICATION = 2,
SEEKTABLE = 3,
VORBIS_COMMENT = 4,
CUESHEET = 5,
PICTURE = 6,
INVALID = 127,
STREAMINFO_SIZE = 34;
this.prototype.readChunk = function() {
var stream = this.stream;
if (!this.readHeader && stream.available(4)) {
if (stream.readString(4) !== 'fLaC')
return this.emit('error', 'Invalid FLAC file.');
this.readHeader = true;
}
while (stream.available(1) && !this.last) {
if (!this.readBlockHeaders) {
var tmp = stream.readUInt8();
this.last = (tmp & 0x80) === 0x80,
this.type = tmp & 0x7F,
this.size = stream.readUInt24();
}
if (!this.foundStreamInfo && this.type !== STREAMINFO)
return this.emit('error', 'STREAMINFO must be the first block');
if (!stream.available(this.size))
return;
switch (this.type) {
case STREAMINFO:
if (this.foundStreamInfo)
return this.emit('error', 'STREAMINFO can only occur once.');
if (this.size !== STREAMINFO_SIZE)
return this.emit('error', 'STREAMINFO size is wrong.');
this.foundStreamInfo = true;
var bitstream = new AV.Bitstream(stream);
var cookie = {
minBlockSize: bitstream.read(16),
maxBlockSize: bitstream.read(16),
minFrameSize: bitstream.read(24),
maxFrameSize: bitstream.read(24)
};
this.format = {
formatID: 'flac',
sampleRate: bitstream.read(20),
channelsPerFrame: bitstream.read(3) + 1,
bitsPerChannel: bitstream.read(5) + 1
};
this.emit('format', this.format);
this.emit('cookie', cookie);
var sampleCount = bitstream.read(36);
this.emit('duration', sampleCount / this.format.sampleRate * 1000 | 0);
stream.advance(16); // skip MD5 hashes
this.readBlockHeaders = false;
break;
/*
I am only looking at the least significant 32 bits of sample number and offset data
This is more than sufficient for the longest flac file I have (~50 mins 2-channel 16-bit 44.1k which uses about 7.5% of the UInt32 space for the largest offset)
Can certainly be improved by storing sample numbers and offests as doubles, but would require additional overriding of the searchTimestamp and seek functions (possibly more?)
Also the flac faq suggests it would be possible to find frame lengths and thus create seek points on the fly via decoding but I assume this would be slow
I may look into these thigns though as my project progresses
*/
case SEEKTABLE:
for(var s=0; s<this.size/18; s++)
{
if(stream.peekUInt32(0) == 0xFFFFFFFF && stream.peekUInt32(1) == 0xFFFFFFFF)
{
//placeholder, ignore
stream.advance(18);
} else {
if(stream.readUInt32() > 0)
{
this.emit('error', 'Seek points with sample number >UInt32 not supported');
}
var samplenum = stream.readUInt32();
if(stream.readUInt32() > 0)
{
this.emit('error', 'Seek points with stream offset >UInt32 not supported');
}
var offset = stream.readUInt32();
stream.advance(2);
this.addSeekPoint(offset, samplenum);
}
}
break;
case VORBIS_COMMENT:
// see http://www.xiph.org/vorbis/doc/v-comment.html
this.metadata || (this.metadata = {});
var len = stream.readUInt32(true);
this.metadata.vendor = stream.readString(len);
var length = stream.readUInt32(true);
for (var i = 0; i < length; i++) {
len = stream.readUInt32(true);
var str = stream.readString(len, 'utf8'),
idx = str.indexOf('=');
this.metadata[str.slice(0, idx).toLowerCase()] = str.slice(idx + 1);
}
// TODO: standardize field names across formats
break;
case PICTURE:
var type = stream.readUInt32();
if (type !== 3) { // make sure this is album art (type 3)
stream.advance(this.size - 4);
} else {
var mimeLen = stream.readUInt32(),
mime = stream.readString(mimeLen),
descLen = stream.readUInt32(),
description = stream.readString(descLen),
width = stream.readUInt32(),
height = stream.readUInt32(),
depth = stream.readUInt32(),
colors = stream.readUInt32(),
length = stream.readUInt32(),
picture = stream.readBuffer(length);
this.metadata || (this.metadata = {});
this.metadata.coverArt = picture;
}
// does anyone want the rest of the info?
break;
default:
stream.advance(this.size);
this.readBlockHeaders = false;
}
if (this.last && this.metadata)
this.emit('metadata', this.metadata);
}
while (stream.available(1) && this.last) {
var buffer = stream.readSingleBuffer(stream.remainingBytes());
this.emit('data', buffer);
}
}
});
module.exports = FLACDemuxer;
},{}],4:[function(require,module,exports){
// if ogg.js exists, register a plugin
try {
var OggDemuxer = (window.AV.OggDemuxer);
} catch (e) {};
if (!OggDemuxer) return;
OggDemuxer.plugins.push({
magic: "\177FLAC",
init: function() {
this.list = new AV.BufferList();
this.stream = new AV.Stream(this.list);
},
readHeaders: function(packet) {
var stream = this.stream;
this.list.append(new AV.Buffer(packet));
stream.advance(5); // magic
if (stream.readUInt8() != 1)
throw new Error('Unsupported FLAC version');
stream.advance(3);
if (stream.peekString(0, 4) != 'fLaC')
throw new Error('Not flac');
this.flac = AV.Demuxer.find(stream.peekSingleBuffer(0, stream.remainingBytes()));
if (!this.flac)
throw new Error('Flac demuxer not found');
this.flac.prototype.readChunk.call(this);
return true;
},
readPacket: function(packet) {
this.list.append(new AV.Buffer(packet));
this.flac.prototype.readChunk.call(this);
}
});
},{}]},{},[1])
//# sourceMappingURL=flac.js.map | systems-rebooter/music | js/vendor/aurora/flac.js | JavaScript | agpl-3.0 | 25,523 |
import os.path
import time
from django.core.management.base import BaseCommand
from django.conf import settings
import mitxmako.middleware as middleware
from django.core.mail import send_mass_mail
import sys
import datetime
middleware.MakoMiddleware()
def chunks(l, n):
""" Yield successive n-sized chunks from l.
"""
for i in xrange(0, len(l), n):
yield l[i:i + n]
class Command(BaseCommand):
help = \
'''Sends an e-mail to all users in a text file.
E.g.
manage.py userlist.txt message logfile.txt rate
userlist.txt -- list of all users
message -- prefix for template with message
logfile.txt -- where to log progress
rate -- messages per second
'''
log_file = None
def hard_log(self, text):
self.log_file.write(datetime.datetime.utcnow().isoformat() + ' -- ' + text + '\n')
def handle(self, *args, **options):
(user_file, message_base, logfilename, ratestr) = args
users = [u.strip() for u in open(user_file).readlines()]
message = middleware.lookup['main'].get_template('emails/' + message_base + "_body.txt").render()
subject = middleware.lookup['main'].get_template('emails/' + message_base + "_subject.txt").render().strip()
rate = int(ratestr)
self.log_file = open(logfilename, "a+", buffering=0)
i = 0
for users in chunks(users, rate):
emails = [(subject, message, settings.DEFAULT_FROM_EMAIL, [u]) for u in users]
self.hard_log(" ".join(users))
send_mass_mail(emails, fail_silently=False)
time.sleep(1)
print datetime.datetime.utcnow().isoformat(), i
i = i + len(users)
# Emergency interruptor
if os.path.exists("/tmp/stopemails.txt"):
self.log_file.close()
sys.exit(-1)
self.log_file.close()
| kalebhartje/schoolboost | common/djangoapps/student/management/commands/massemailtxt.py | Python | agpl-3.0 | 1,862 |
/*
* /MathJax/localization/br/br.js
*
* Copyright (c) 2009-2015 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Localization.addTranslation( "br", null, {
menuTitle: "brezhoneg",
version: "2.5.0",
isLoaded: true,
domains: {
_: {
version: "2.5.0",
isLoaded: true,
strings: {
MathProcessingError: "Fazi o treta\u00F1 ar formulenn",
MathError: "Fazi er formulenn",
LoadFile: "O karga\u00F1 %1",
Loading: "O karga\u00F1",
LoadFailed: "N'eus ket bet gallet karga\u00F1 %1",
ProcessMath: "Treta\u00F1 ar formulenno\u00F9 : %1%%",
Processing: "O treta\u00F1",
TypesetMath: "Aoza\u00F1 formulenno\u00F9 : %1%%",
Typesetting: "Aoza\u00F1",
MathJaxNotSupported: "Ne c'hall ket ho merdeer ober gant MathJax"
}
}, FontWarnings: {}, "HTML-CSS": {}, HelpDialog: {}, MathML: {}, MathMenu: {}, TeX: {}
},
plural: function( a )
{
if (a % 10 === 1 && !(a % 100 === 11 || a % 100 === 71 || a % 100 === 91)) {
return 1
}
if (a % 10 === 2 && !(a % 100 === 12 || a % 100 === 72 || a % 100 === 92)) {
return 2
}
if ((a % 10 === 3 || a % 10 === 4 || a % 10 === 9) && !(10 <= a % 100 && a % 100 <= 19 || 70 <= a % 100 && a % 100 <= 79 || 90 <= a % 100 && a % 100 <= 99)) {
return 3
}
if (a !== 0 && a % 1000000 === 0) {
return 4
}
return 5
},
number: function( a )
{
return a
}
} );
MathJax.Ajax.loadComplete( "[MathJax]/localization/br/br.js" );
| hannesk001/SPHERE-Framework | Library/MathJax/2.5.0/localization/br/br.js | JavaScript | agpl-3.0 | 2,278 |
/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the Places Command Controller.
*
* The Initial Developer of the Original Code is Google Inc.
*
* Portions created by the Initial Developer are Copyright (C) 2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Sungjoon Steve Won <stevewon@gmail.com> (Original Author)
* Asaf Romano <mano@mozilla.com>
* Marco Bonarco <mak77@bonardo.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
let Ci = Components.interfaces;
let Cc = Components.classes;
let Cr = Components.results;
const LOAD_IN_SIDEBAR_ANNO = "bookmarkProperties/loadInSidebar";
const DESCRIPTION_ANNO = "bookmarkProperties/description";
const GUID_ANNO = "placesInternal/GUID";
const CLASS_ID = Components.ID("c0844a84-5a12-4808-80a8-809cb002bb4f");
const CONTRACT_ID = "@mozilla.org/browser/placesTransactionsService;1";
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
__defineGetter__("PlacesUtils", function() {
delete this.PlacesUtils
var tmpScope = {};
Components.utils.import("resource://gre/modules/utils.js", tmpScope);
return this.PlacesUtils = tmpScope.PlacesUtils;
});
// The minimum amount of transactions we should tell our observers to begin
// batching (rather than letting them do incremental drawing).
const MIN_TRANSACTIONS_FOR_BATCH = 5;
function placesTransactionsService() {
this.mTransactionManager = Cc["@mozilla.org/transactionmanager;1"].
createInstance(Ci.nsITransactionManager);
}
placesTransactionsService.prototype = {
classDescription: "Places Transaction Manager",
classID: CLASS_ID,
contractID: CONTRACT_ID,
QueryInterface: XPCOMUtils.generateQI([Ci.nsIPlacesTransactionsService,
Ci.nsITransactionManager]),
aggregateTransactions:
function placesTxn_aggregateTransactions(aName, aTransactions) {
return new placesAggregateTransactions(aName, aTransactions);
},
createFolder:
function placesTxn_createFolder(aName, aContainer, aIndex,
aAnnotations, aChildItemsTransactions) {
return new placesCreateFolderTransactions(aName, aContainer, aIndex,
aAnnotations, aChildItemsTransactions);
},
createItem:
function placesTxn_createItem(aURI, aContainer, aIndex, aTitle,
aKeyword, aAnnotations, aChildTransactions) {
return new placesCreateItemTransactions(aURI, aContainer, aIndex, aTitle,
aKeyword, aAnnotations, aChildTransactions);
},
createSeparator:
function placesTxn_createSeparator(aContainer, aIndex) {
return new placesCreateSeparatorTransactions(aContainer, aIndex);
},
createLivemark:
function placesTxn_createLivemark(aFeedURI, aSiteURI, aName,
aContainer, aIndex, aAnnotations) {
return new placesCreateLivemarkTransactions(aFeedURI, aSiteURI, aName,
aContainer, aIndex, aAnnotations);
},
moveItem:
function placesTxn_moveItem(aItemId, aNewContainer, aNewIndex) {
return new placesMoveItemTransactions(aItemId, aNewContainer, aNewIndex);
},
removeItem:
function placesTxn_removeItem(aItemId) {
if (aItemId == PlacesUtils.tagsFolderId ||
aItemId == PlacesUtils.placesRootId ||
aItemId == PlacesUtils.bookmarksMenuFolderId ||
aItemId == PlacesUtils.toolbarFolderId)
throw Cr.NS_ERROR_INVALID_ARG;
// if the item lives within a tag container, use the tagging transactions
var parent = PlacesUtils.bookmarks.getFolderIdForItem(aItemId);
var grandparent = PlacesUtils.bookmarks.getFolderIdForItem(parent);
if (grandparent == PlacesUtils.tagsFolderId) {
var uri = PlacesUtils.bookmarks.getBookmarkURI(aItemId);
return this.untagURI(uri, [parent]);
}
// if the item is a livemark container we will not save its children and
// will use createLivemark to undo.
if (PlacesUtils.itemIsLivemark(aItemId))
return new placesRemoveLivemarkTransaction(aItemId);
return new placesRemoveItemTransaction(aItemId);
},
editItemTitle:
function placesTxn_editItemTitle(aItemId, aNewTitle) {
return new placesEditItemTitleTransactions(aItemId, aNewTitle);
},
editBookmarkURI:
function placesTxn_editBookmarkURI(aItemId, aNewURI) {
return new placesEditBookmarkURITransactions(aItemId, aNewURI);
},
setItemAnnotation:
function placesTxn_setItemAnnotation(aItemId, aAnnotationObject) {
return new placesSetItemAnnotationTransactions(aItemId, aAnnotationObject);
},
setPageAnnotation:
function placesTxn_setPageAnnotation(aURI, aAnnotationObject) {
return new placesSetPageAnnotationTransactions(aURI, aAnnotationObject);
},
setLoadInSidebar:
function placesTxn_setLoadInSidebar(aItemId, aLoadInSidebar) {
var annoObj = { name: LOAD_IN_SIDEBAR_ANNO,
type: Ci.nsIAnnotationService.TYPE_INT32,
flags: 0,
value: aLoadInSidebar,
expires: Ci.nsIAnnotationService.EXPIRE_NEVER };
return this.setItemAnnotation(aItemId, annoObj);
},
editItemDescription:
function placesTxn_editItemDescription(aItemId, aDescription) {
var annoObj = { name: DESCRIPTION_ANNO,
type: Ci.nsIAnnotationService.TYPE_STRING,
flags: 0,
value: aDescription,
expires: Ci.nsIAnnotationService.EXPIRE_NEVER };
return this.setItemAnnotation(aItemId, annoObj);
},
editBookmarkKeyword:
function placesTxn_editBookmarkKeyword(aItemId, aNewKeyword) {
return new placesEditBookmarkKeywordTransactions(aItemId, aNewKeyword);
},
editBookmarkPostData:
function placesTxn_editBookmarkPostdata(aItemId, aPostData) {
return new placesEditBookmarkPostDataTransactions(aItemId, aPostData);
},
editLivemarkSiteURI:
function placesTxn_editLivemarkSiteURI(aLivemarkId, aSiteURI) {
return new placesEditLivemarkSiteURITransactions(aLivemarkId, aSiteURI);
},
editLivemarkFeedURI:
function placesTxn_editLivemarkFeedURI(aLivemarkId, aFeedURI) {
return new placesEditLivemarkFeedURITransactions(aLivemarkId, aFeedURI);
},
editBookmarkMicrosummary:
function placesTxn_editBookmarkMicrosummary(aItemId, aNewMicrosummary) {
return new placesEditBookmarkMicrosummaryTransactions(aItemId, aNewMicrosummary);
},
editItemDateAdded:
function placesTxn_editItemDateAdded(aItemId, aNewDateAdded) {
return new placesEditItemDateAddedTransaction(aItemId, aNewDateAdded);
},
editItemLastModified:
function placesTxn_editItemLastModified(aItemId, aNewLastModified) {
return new placesEditItemLastModifiedTransaction(aItemId, aNewLastModified);
},
sortFolderByName:
function placesTxn_sortFolderByName(aFolderId) {
return new placesSortFolderByNameTransactions(aFolderId);
},
tagURI:
function placesTxn_tagURI(aURI, aTags) {
return new placesTagURITransaction(aURI, aTags);
},
untagURI:
function placesTxn_untagURI(aURI, aTags) {
return new placesUntagURITransaction(aURI, aTags);
},
// Update commands in the undo group of the active window
// commands in inactive windows will are updated on-focus
_updateCommands: function placesTxn__updateCommands() {
var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
getService(Ci.nsIWindowMediator);
var win = wm.getMostRecentWindow(null);
if (win)
win.updateCommands("undo");
},
// nsITransactionManager
beginBatch: function() {
this.mTransactionManager.beginBatch();
// A no-op transaction is pushed to the stack, in order to make safe and
// easy to implement "Undo" an unknown number of transactions (including 0),
// "above" beginBatch and endBatch. Otherwise,implementing Undo that way
// head to dataloss: for example, if no changes were done in the
// edit-item panel, the last transaction on the undo stack would be the
// initial createItem transaction, or even worse, the batched editing of
// some other item.
// DO NOT MOVE this to the window scope, that would leak (bug 490068)!
this.doTransaction({ doTransaction: function() { },
undoTransaction: function() { },
redoTransaction: function() { },
isTransient: false,
merge: function() { return false; } });
},
endBatch: function() this.mTransactionManager.endBatch(),
doTransaction: function placesTxn_doTransaction(txn) {
this.mTransactionManager.doTransaction(txn);
this._updateCommands();
},
undoTransaction: function placesTxn_undoTransaction() {
this.mTransactionManager.undoTransaction();
this._updateCommands();
},
redoTransaction: function placesTxn_redoTransaction() {
this.mTransactionManager.redoTransaction();
this._updateCommands();
},
clear: function() this.mTransactionManager.clear(),
get numberOfUndoItems() {
return this.mTransactionManager.numberOfUndoItems;
},
get numberOfRedoItems() {
return this.mTransactionManager.numberOfRedoItems;
},
get maxTransactionCount() {
return this.mTransactionManager.maxTransactionCount;
},
set maxTransactionCount(val) {
return this.mTransactionManager.maxTransactionCount = val;
},
peekUndoStack: function() this.mTransactionManager.peekUndoStack(),
peekRedoStack: function() this.mTransactionManager.peekRedoStack(),
getUndoStack: function() this.mTransactionManager.getUndoStack(),
getRedoStack: function() this.mTransactionManager.getRedoStack(),
AddListener: function(l) this.mTransactionManager.AddListener(l),
RemoveListener: function(l) this.mTransactionManager.RemoveListener(l)
};
/**
* Method and utility stubs for Places Edit Transactions
*/
function placesBaseTransaction() {
}
placesBaseTransaction.prototype = {
// for child-transactions
get wrappedJSObject() {
return this;
},
// nsITransaction
redoTransaction: function PBT_redoTransaction() {
throw Cr.NS_ERROR_NOT_IMPLEMENTED;
},
get isTransient() {
return false;
},
merge: function mergeFunc(transaction) {
return false;
},
// nsISupports
QueryInterface: XPCOMUtils.generateQI([Ci.nsITransaction]),
};
function placesAggregateTransactions(name, transactions) {
this._transactions = transactions;
this._name = name;
this.container = -1;
this.redoTransaction = this.doTransaction;
// Check child transactions number. We will batch if we have more than
// MIN_TRANSACTIONS_FOR_BATCH total number of transactions.
var countTransactions = function(aTransactions, aTxnCount) {
for (let i = 0;
i < aTransactions.length && aTxnCount < MIN_TRANSACTIONS_FOR_BATCH;
i++, aTxnCount++) {
let txn = aTransactions[i].wrappedJSObject;
if (txn && txn.childTransactions && txn.childTransactions.length)
aTxnCount = countTransactions(txn.childTransactions, aTxnCount);
}
return aTxnCount;
}
var txnCount = countTransactions(transactions, 0);
this._useBatch = txnCount >= MIN_TRANSACTIONS_FOR_BATCH;
}
placesAggregateTransactions.prototype = {
__proto__: placesBaseTransaction.prototype,
doTransaction: function PAT_doTransaction() {
if (this._useBatch) {
var callback = {
_self: this,
runBatched: function() {
this._self.commit(false);
}
};
PlacesUtils.bookmarks.runInBatchMode(callback, null);
}
else
this.commit(false);
},
undoTransaction: function PAT_undoTransaction() {
if (this._useBatch) {
var callback = {
_self: this,
runBatched: function() {
this._self.commit(true);
}
};
PlacesUtils.bookmarks.runInBatchMode(callback, null);
}
else
this.commit(true);
},
commit: function PAT_commit(aUndo) {
// Use a copy of the transactions array, so we won't reverse the original
// one on undoing.
var transactions = this._transactions.slice(0);
if (aUndo)
transactions.reverse();
for (var i = 0; i < transactions.length; i++) {
var txn = transactions[i];
if (this.container > -1)
txn.wrappedJSObject.container = this.container;
if (aUndo)
txn.undoTransaction();
else
txn.doTransaction();
}
}
};
function placesCreateFolderTransactions(aName, aContainer, aIndex,
aAnnotations,
aChildItemsTransactions) {
this._name = aName;
this._container = aContainer;
this._index = typeof(aIndex) == "number" ? aIndex : -1;
this._annotations = aAnnotations;
this._id = null;
this.childTransactions = aChildItemsTransactions || [];
this.redoTransaction = this.doTransaction;
}
placesCreateFolderTransactions.prototype = {
__proto__: placesBaseTransaction.prototype,
// childItemsTransaction support
get container() { return this._container; },
set container(val) { return this._container = val; },
doTransaction: function PCFT_doTransaction() {
this._id = PlacesUtils.bookmarks.createFolder(this._container,
this._name, this._index);
if (this._annotations && this._annotations.length > 0)
PlacesUtils.setAnnotationsForItem(this._id, this._annotations);
if (this.childTransactions.length) {
// Set the new container id into child transactions.
for (var i = 0; i < this.childTransactions.length; ++i) {
this.childTransactions[i].wrappedJSObject.container = this._id;
}
let aggregateTxn = new placesAggregateTransactions("Create folder childTxn",
this.childTransactions);
aggregateTxn.doTransaction();
}
if (this._GUID)
PlacesUtils.bookmarks.setItemGUID(this._id, this._GUID);
},
undoTransaction: function PCFT_undoTransaction() {
if (this.childTransactions.length) {
let aggregateTxn = new placesAggregateTransactions("Create folder childTxn",
this.childTransactions);
aggregateTxn.undoTransaction();
}
// If a GUID exists for this item, preserve it before removing the item.
if (PlacesUtils.annotations.itemHasAnnotation(this._id, GUID_ANNO))
this._GUID = PlacesUtils.bookmarks.getItemGUID(this._id);
// Remove item only after all child transactions have been reverted.
PlacesUtils.bookmarks.removeItem(this._id);
}
};
function placesCreateItemTransactions(aURI, aContainer, aIndex, aTitle,
aKeyword, aAnnotations,
aChildTransactions) {
this._uri = aURI;
this._container = aContainer;
this._index = typeof(aIndex) == "number" ? aIndex : -1;
this._title = aTitle;
this._keyword = aKeyword;
this._annotations = aAnnotations;
this.childTransactions = aChildTransactions || [];
this.redoTransaction = this.doTransaction;
}
placesCreateItemTransactions.prototype = {
__proto__: placesBaseTransaction.prototype,
// childItemsTransactions support for the create-folder transaction
get container() { return this._container; },
set container(val) { return this._container = val; },
doTransaction: function PCIT_doTransaction() {
this._id = PlacesUtils.bookmarks.insertBookmark(this.container, this._uri,
this._index, this._title);
if (this._keyword)
PlacesUtils.bookmarks.setKeywordForBookmark(this._id, this._keyword);
if (this._annotations && this._annotations.length > 0)
PlacesUtils.setAnnotationsForItem(this._id, this._annotations);
if (this.childTransactions.length) {
// Set the new item id into child transactions.
for (var i = 0; i < this.childTransactions.length; ++i) {
this.childTransactions[i].wrappedJSObject.id = this._id;
}
let aggregateTxn = new placesAggregateTransactions("Create item childTxn",
this.childTransactions);
aggregateTxn.doTransaction();
}
if (this._GUID)
PlacesUtils.bookmarks.setItemGUID(this._id, this._GUID);
},
undoTransaction: function PCIT_undoTransaction() {
if (this.childTransactions.length) {
// Undo transactions should always be done in reverse order.
let aggregateTxn = new placesAggregateTransactions("Create item childTxn",
this.childTransactions);
aggregateTxn.undoTransaction();
}
// If a GUID exists for this item, preserve it before removing the item.
if (PlacesUtils.annotations.itemHasAnnotation(this._id, GUID_ANNO))
this._GUID = PlacesUtils.bookmarks.getItemGUID(this._id);
// Remove item only after all child transactions have been reverted.
PlacesUtils.bookmarks.removeItem(this._id);
}
};
function placesCreateSeparatorTransactions(aContainer, aIndex) {
this._container = aContainer;
this._index = typeof(aIndex) == "number" ? aIndex : -1;
this._id = null;
this.redoTransaction = this.doTransaction;
}
placesCreateSeparatorTransactions.prototype = {
__proto__: placesBaseTransaction.prototype,
// childItemsTransaction support
get container() { return this._container; },
set container(val) { return this._container = val; },
doTransaction: function PCST_doTransaction() {
this._id = PlacesUtils.bookmarks
.insertSeparator(this.container, this._index);
if (this._GUID)
PlacesUtils.bookmarks.setItemGUID(this._id, this._GUID);
},
undoTransaction: function PCST_undoTransaction() {
// If a GUID exists for this item, preserve it before removing the item.
if (PlacesUtils.annotations.itemHasAnnotation(this._id, GUID_ANNO))
this._GUID = PlacesUtils.bookmarks.getItemGUID(this._id);
PlacesUtils.bookmarks.removeItem(this._id);
}
};
function placesCreateLivemarkTransactions(aFeedURI, aSiteURI, aName,
aContainer, aIndex,
aAnnotations) {
this.redoTransaction = this.doTransaction;
this._feedURI = aFeedURI;
this._siteURI = aSiteURI;
this._name = aName;
this._container = aContainer;
this._index = typeof(aIndex) == "number" ? aIndex : -1;
this._annotations = aAnnotations;
}
placesCreateLivemarkTransactions.prototype = {
__proto__: placesBaseTransaction.prototype,
// childItemsTransaction support
get container() { return this._container; },
set container(val) { return this._container = val; },
doTransaction: function PCLT_doTransaction() {
this._id = PlacesUtils.livemarks.createLivemark(this._container, this._name,
this._siteURI, this._feedURI,
this._index);
if (this._annotations && this._annotations.length > 0)
PlacesUtils.setAnnotationsForItem(this._id, this._annotations);
if (this._GUID)
PlacesUtils.bookmarks.setItemGUID(this._id, this._GUID);
},
undoTransaction: function PCLT_undoTransaction() {
// If a GUID exists for this item, preserve it before removing the item.
if (PlacesUtils.annotations.itemHasAnnotation(this._id, GUID_ANNO))
this._GUID = PlacesUtils.bookmarks.getItemGUID(this._id);
PlacesUtils.bookmarks.removeItem(this._id);
}
};
function placesRemoveLivemarkTransaction(aFolderId) {
this.redoTransaction = this.doTransaction;
this._id = aFolderId;
this._title = PlacesUtils.bookmarks.getItemTitle(this._id);
this._container = PlacesUtils.bookmarks.getFolderIdForItem(this._id);
var annos = PlacesUtils.getAnnotationsForItem(this._id);
// Exclude livemark service annotations, those will be recreated automatically
var annosToExclude = ["livemark/feedURI",
"livemark/siteURI",
"livemark/expiration",
"livemark/loadfailed",
"livemark/loading"];
this._annotations = annos.filter(function(aValue, aIndex, aArray) {
return annosToExclude.indexOf(aValue.name) == -1;
});
this._feedURI = PlacesUtils.livemarks.getFeedURI(this._id);
this._siteURI = PlacesUtils.livemarks.getSiteURI(this._id);
this._dateAdded = PlacesUtils.bookmarks.getItemDateAdded(this._id);
this._lastModified = PlacesUtils.bookmarks.getItemLastModified(this._id);
}
placesRemoveLivemarkTransaction.prototype = {
__proto__: placesBaseTransaction.prototype,
doTransaction: function PRLT_doTransaction() {
this._index = PlacesUtils.bookmarks.getItemIndex(this._id);
PlacesUtils.bookmarks.removeItem(this._id);
},
undoTransaction: function PRLT_undoTransaction() {
this._id = PlacesUtils.livemarks.createLivemark(this._container,
this._title,
this._siteURI,
this._feedURI,
this._index);
PlacesUtils.bookmarks.setItemDateAdded(this._id, this._dateAdded);
PlacesUtils.bookmarks.setItemLastModified(this._id, this._lastModified);
// Restore annotations
PlacesUtils.setAnnotationsForItem(this._id, this._annotations);
}
};
function placesMoveItemTransactions(aItemId, aNewContainer, aNewIndex) {
this._id = aItemId;
this._oldContainer = PlacesUtils.bookmarks.getFolderIdForItem(this._id);
this._newContainer = aNewContainer;
this._newIndex = aNewIndex;
this.redoTransaction = this.doTransaction;
}
placesMoveItemTransactions.prototype = {
__proto__: placesBaseTransaction.prototype,
doTransaction: function PMIT_doTransaction() {
this._oldIndex = PlacesUtils.bookmarks.getItemIndex(this._id);
PlacesUtils.bookmarks.moveItem(this._id, this._newContainer, this._newIndex);
this._undoIndex = PlacesUtils.bookmarks.getItemIndex(this._id);
},
undoTransaction: function PMIT_undoTransaction() {
// moving down in the same container takes in count removal of the item
// so to revert positions we must move to oldIndex + 1
if (this._newContainer == this._oldContainer &&
this._oldIndex > this._undoIndex)
PlacesUtils.bookmarks.moveItem(this._id, this._oldContainer, this._oldIndex + 1);
else
PlacesUtils.bookmarks.moveItem(this._id, this._oldContainer, this._oldIndex);
}
};
function placesRemoveItemTransaction(aItemId) {
this.redoTransaction = this.doTransaction;
this._id = aItemId;
this._itemType = PlacesUtils.bookmarks.getItemType(this._id);
if (this._itemType == Ci.nsINavBookmarksService.TYPE_FOLDER) {
this.childTransactions = this._getFolderContentsTransactions();
// Remove this folder itself.
let txn = PlacesUtils.bookmarks.getRemoveFolderTransaction(this._id);
this.childTransactions.push(txn);
}
else if (this._itemType == Ci.nsINavBookmarksService.TYPE_BOOKMARK) {
this._uri = PlacesUtils.bookmarks.getBookmarkURI(this._id);
this._keyword = PlacesUtils.bookmarks.getKeywordForBookmark(this._id);
}
if (this._itemType != Ci.nsINavBookmarksService.TYPE_SEPARATOR)
this._title = PlacesUtils.bookmarks.getItemTitle(this._id);
this._oldContainer = PlacesUtils.bookmarks.getFolderIdForItem(this._id);
this._annotations = PlacesUtils.getAnnotationsForItem(this._id);
this._dateAdded = PlacesUtils.bookmarks.getItemDateAdded(this._id);
this._lastModified = PlacesUtils.bookmarks.getItemLastModified(this._id);
}
placesRemoveItemTransaction.prototype = {
__proto__: placesBaseTransaction.prototype,
doTransaction: function PRIT_doTransaction() {
this._oldIndex = PlacesUtils.bookmarks.getItemIndex(this._id);
if (this._itemType == Ci.nsINavBookmarksService.TYPE_FOLDER) {
let aggregateTxn = new placesAggregateTransactions("Remove item childTxn",
this.childTransactions);
aggregateTxn.doTransaction();
}
else {
PlacesUtils.bookmarks.removeItem(this._id);
if (this._uri) {
// if this was the last bookmark (excluding tag-items and livemark
// children, see getMostRecentBookmarkForURI) for the bookmark's url,
// remove the url from tag containers as well.
if (PlacesUtils.getMostRecentBookmarkForURI(this._uri) == -1) {
this._tags = PlacesUtils.tagging.getTagsForURI(this._uri, {});
PlacesUtils.tagging.untagURI(this._uri, this._tags);
}
}
}
},
undoTransaction: function PRIT_undoTransaction() {
if (this._itemType == Ci.nsINavBookmarksService.TYPE_BOOKMARK) {
this._id = PlacesUtils.bookmarks.insertBookmark(this._oldContainer,
this._uri,
this._oldIndex,
this._title);
if (this._tags && this._tags.length > 0)
PlacesUtils.tagging.tagURI(this._uri, this._tags);
if (this._keyword)
PlacesUtils.bookmarks.setKeywordForBookmark(this._id, this._keyword);
}
else if (this._itemType == Ci.nsINavBookmarksService.TYPE_FOLDER) {
let aggregateTxn = new placesAggregateTransactions("Remove item childTxn",
this.childTransactions);
aggregateTxn.undoTransaction();
}
else // TYPE_SEPARATOR
this._id = PlacesUtils.bookmarks.insertSeparator(this._oldContainer, this._oldIndex);
if (this._annotations.length > 0)
PlacesUtils.setAnnotationsForItem(this._id, this._annotations);
PlacesUtils.bookmarks.setItemDateAdded(this._id, this._dateAdded);
PlacesUtils.bookmarks.setItemLastModified(this._id, this._lastModified);
},
/**
* Returns a flat, ordered list of transactions for a depth-first recreation
* of items within this folder.
*/
_getFolderContentsTransactions:
function PRIT__getFolderContentsTransactions() {
var transactions = [];
var contents =
PlacesUtils.getFolderContents(this._id, false, false).root;
for (var i = 0; i < contents.childCount; ++i) {
let txn = new placesRemoveItemTransaction(contents.getChild(i).itemId);
transactions.push(txn);
}
contents.containerOpen = false;
// Reverse transactions to preserve parent-child relationship.
return transactions.reverse();
}
};
function placesEditItemTitleTransactions(id, newTitle) {
this._id = id;
this._newTitle = newTitle;
this._oldTitle = "";
this.redoTransaction = this.doTransaction;
}
placesEditItemTitleTransactions.prototype = {
__proto__: placesBaseTransaction.prototype,
doTransaction: function PEITT_doTransaction() {
this._oldTitle = PlacesUtils.bookmarks.getItemTitle(this._id);
PlacesUtils.bookmarks.setItemTitle(this._id, this._newTitle);
},
undoTransaction: function PEITT_undoTransaction() {
PlacesUtils.bookmarks.setItemTitle(this._id, this._oldTitle);
}
};
function placesEditBookmarkURITransactions(aBookmarkId, aNewURI) {
this._id = aBookmarkId;
this._newURI = aNewURI;
this.redoTransaction = this.doTransaction;
}
placesEditBookmarkURITransactions.prototype = {
__proto__: placesBaseTransaction.prototype,
doTransaction: function PEBUT_doTransaction() {
this._oldURI = PlacesUtils.bookmarks.getBookmarkURI(this._id);
PlacesUtils.bookmarks.changeBookmarkURI(this._id, this._newURI);
// move tags from old URI to new URI
this._tags = PlacesUtils.tagging.getTagsForURI(this._oldURI, {});
if (this._tags.length != 0) {
// only untag the old URI if this is the only bookmark
if (PlacesUtils.getBookmarksForURI(this._oldURI, {}).length == 0)
PlacesUtils.tagging.untagURI(this._oldURI, this._tags);
PlacesUtils.tagging.tagURI(this._newURI, this._tags);
}
},
undoTransaction: function PEBUT_undoTransaction() {
PlacesUtils.bookmarks.changeBookmarkURI(this._id, this._oldURI);
// move tags from new URI to old URI
if (this._tags.length != 0) {
// only untag the new URI if this is the only bookmark
if (PlacesUtils.getBookmarksForURI(this._newURI, {}).length == 0)
PlacesUtils.tagging.untagURI(this._newURI, this._tags);
PlacesUtils.tagging.tagURI(this._oldURI, this._tags);
}
}
};
function placesSetItemAnnotationTransactions(aItemId, aAnnotationObject) {
this.id = aItemId;
this._anno = aAnnotationObject;
// create an empty old anno
this._oldAnno = { name: this._anno.name,
type: Ci.nsIAnnotationService.TYPE_STRING,
flags: 0,
value: null,
expires: Ci.nsIAnnotationService.EXPIRE_NEVER };
this.redoTransaction = this.doTransaction;
}
placesSetItemAnnotationTransactions.prototype = {
__proto__: placesBaseTransaction.prototype,
doTransaction: function PSIAT_doTransaction() {
// Since this can be used as a child transaction this.id will be known
// only at this point, after the external caller has set it.
if (PlacesUtils.annotations.itemHasAnnotation(this.id, this._anno.name)) {
// Save the old annotation if it is set.
var flags = {}, expires = {}, mimeType = {}, type = {};
PlacesUtils.annotations.getItemAnnotationInfo(this.id, this._anno.name,
flags, expires, mimeType,
type);
this._oldAnno.flags = flags.value;
this._oldAnno.expires = expires.value;
this._oldAnno.mimeType = mimeType.value;
this._oldAnno.type = type.value;
this._oldAnno.value = PlacesUtils.annotations
.getItemAnnotation(this.id,
this._anno.name);
}
PlacesUtils.setAnnotationsForItem(this.id, [this._anno]);
},
undoTransaction: function PSIAT_undoTransaction() {
PlacesUtils.setAnnotationsForItem(this.id, [this._oldAnno]);
}
};
function placesSetPageAnnotationTransactions(aURI, aAnnotationObject) {
this._uri = aURI;
this._anno = aAnnotationObject;
// create an empty old anno
this._oldAnno = { name: this._anno.name,
type: Ci.nsIAnnotationService.TYPE_STRING,
flags: 0,
value: null,
expires: Ci.nsIAnnotationService.EXPIRE_NEVER };
if (PlacesUtils.annotations.pageHasAnnotation(this._uri, this._anno.name)) {
// fill the old anno if it is set
var flags = {}, expires = {}, mimeType = {}, type = {};
PlacesUtils.annotations.getPageAnnotationInfo(this._uri, this._anno.name,
flags, expires, mimeType, type);
this._oldAnno.flags = flags.value;
this._oldAnno.expires = expires.value;
this._oldAnno.mimeType = mimeType.value;
this._oldAnno.type = type.value;
this._oldAnno.value = PlacesUtils.annotations
.getPageAnnotation(this._uri, this._anno.name);
}
this.redoTransaction = this.doTransaction;
}
placesSetPageAnnotationTransactions.prototype = {
__proto__: placesBaseTransaction.prototype,
doTransaction: function PSPAT_doTransaction() {
PlacesUtils.setAnnotationsForURI(this._uri, [this._anno]);
},
undoTransaction: function PSPAT_undoTransaction() {
PlacesUtils.setAnnotationsForURI(this._uri, [this._oldAnno]);
}
};
function placesEditBookmarkKeywordTransactions(id, newKeyword) {
this.id = id;
this._newKeyword = newKeyword;
this._oldKeyword = "";
this.redoTransaction = this.doTransaction;
}
placesEditBookmarkKeywordTransactions.prototype = {
__proto__: placesBaseTransaction.prototype,
doTransaction: function PEBKT_doTransaction() {
this._oldKeyword = PlacesUtils.bookmarks.getKeywordForBookmark(this.id);
PlacesUtils.bookmarks.setKeywordForBookmark(this.id, this._newKeyword);
},
undoTransaction: function PEBKT_undoTransaction() {
PlacesUtils.bookmarks.setKeywordForBookmark(this.id, this._oldKeyword);
}
};
function placesEditBookmarkPostDataTransactions(aItemId, aPostData) {
this.id = aItemId;
this._newPostData = aPostData;
this._oldPostData = null;
this.redoTransaction = this.doTransaction;
}
placesEditBookmarkPostDataTransactions.prototype = {
__proto__: placesBaseTransaction.prototype,
doTransaction: function PEUPDT_doTransaction() {
this._oldPostData = PlacesUtils.getPostDataForBookmark(this.id);
PlacesUtils.setPostDataForBookmark(this.id, this._newPostData);
},
undoTransaction: function PEUPDT_undoTransaction() {
PlacesUtils.setPostDataForBookmark(this.id, this._oldPostData);
}
};
function placesEditLivemarkSiteURITransactions(folderId, uri) {
this._folderId = folderId;
this._newURI = uri;
this._oldURI = null;
this.redoTransaction = this.doTransaction;
}
placesEditLivemarkSiteURITransactions.prototype = {
__proto__: placesBaseTransaction.prototype,
doTransaction: function PELSUT_doTransaction() {
this._oldURI = PlacesUtils.livemarks.getSiteURI(this._folderId);
PlacesUtils.livemarks.setSiteURI(this._folderId, this._newURI);
},
undoTransaction: function PELSUT_undoTransaction() {
PlacesUtils.livemarks.setSiteURI(this._folderId, this._oldURI);
}
};
function placesEditLivemarkFeedURITransactions(folderId, uri) {
this._folderId = folderId;
this._newURI = uri;
this._oldURI = null;
this.redoTransaction = this.doTransaction;
}
placesEditLivemarkFeedURITransactions.prototype = {
__proto__: placesBaseTransaction.prototype,
doTransaction: function PELFUT_doTransaction() {
this._oldURI = PlacesUtils.livemarks.getFeedURI(this._folderId);
PlacesUtils.livemarks.setFeedURI(this._folderId, this._newURI);
PlacesUtils.livemarks.reloadLivemarkFolder(this._folderId);
},
undoTransaction: function PELFUT_undoTransaction() {
PlacesUtils.livemarks.setFeedURI(this._folderId, this._oldURI);
PlacesUtils.livemarks.reloadLivemarkFolder(this._folderId);
}
};
function placesEditBookmarkMicrosummaryTransactions(aItemId, newMicrosummary) {
this.id = aItemId;
this._mss = Cc["@mozilla.org/microsummary/service;1"].
getService(Ci.nsIMicrosummaryService);
this._newMicrosummary = newMicrosummary;
this._oldMicrosummary = null;
this.redoTransaction = this.doTransaction;
}
placesEditBookmarkMicrosummaryTransactions.prototype = {
__proto__: placesBaseTransaction.prototype,
doTransaction: function PEBMT_doTransaction() {
this._oldMicrosummary = this._mss.getMicrosummary(this.id);
if (this._newMicrosummary)
this._mss.setMicrosummary(this.id, this._newMicrosummary);
else
this._mss.removeMicrosummary(this.id);
},
undoTransaction: function PEBMT_undoTransaction() {
if (this._oldMicrosummary)
this._mss.setMicrosummary(this.id, this._oldMicrosummary);
else
this._mss.removeMicrosummary(this.id);
}
};
function placesEditItemDateAddedTransaction(id, newDateAdded) {
this.id = id;
this._newDateAdded = newDateAdded;
this._oldDateAdded = null;
this.redoTransaction = this.doTransaction;
}
placesEditItemDateAddedTransaction.prototype = {
__proto__: placesBaseTransaction.prototype,
// to support folders as well
get container() { return this.id; },
set container(val) { return this.id = val; },
doTransaction: function PEIDA_doTransaction() {
this._oldDateAdded = PlacesUtils.bookmarks.getItemDateAdded(this.id);
PlacesUtils.bookmarks.setItemDateAdded(this.id, this._newDateAdded);
},
undoTransaction: function PEIDA_undoTransaction() {
PlacesUtils.bookmarks.setItemDateAdded(this.id, this._oldDateAdded);
}
};
function placesEditItemLastModifiedTransaction(id, newLastModified) {
this.id = id;
this._newLastModified = newLastModified;
this._oldLastModified = null;
this.redoTransaction = this.doTransaction;
}
placesEditItemLastModifiedTransaction.prototype = {
__proto__: placesBaseTransaction.prototype,
// to support folders as well
get container() { return this.id; },
set container(val) { return this.id = val; },
doTransaction: function PEILM_doTransaction() {
this._oldLastModified = PlacesUtils.bookmarks.getItemLastModified(this.id);
PlacesUtils.bookmarks.setItemLastModified(this.id, this._newLastModified);
},
undoTransaction: function PEILM_undoTransaction() {
PlacesUtils.bookmarks.setItemLastModified(this.id, this._oldLastModified);
}
};
function placesSortFolderByNameTransactions(aFolderId) {
this._folderId = aFolderId;
this._oldOrder = null,
this.redoTransaction = this.doTransaction;
}
placesSortFolderByNameTransactions.prototype = {
__proto__: placesBaseTransaction.prototype,
doTransaction: function PSSFBN_doTransaction() {
this._oldOrder = [];
var contents =
PlacesUtils.getFolderContents(this._folderId, false, false).root;
var count = contents.childCount;
// sort between separators
var newOrder = [];
var preSep = []; // temporary array for sorting each group of items
var sortingMethod =
function (a, b) {
if (PlacesUtils.nodeIsContainer(a) && !PlacesUtils.nodeIsContainer(b))
return -1;
if (!PlacesUtils.nodeIsContainer(a) && PlacesUtils.nodeIsContainer(b))
return 1;
return a.title.localeCompare(b.title);
};
for (var i = 0; i < count; ++i) {
var item = contents.getChild(i);
this._oldOrder[item.itemId] = i;
if (PlacesUtils.nodeIsSeparator(item)) {
if (preSep.length > 0) {
preSep.sort(sortingMethod);
newOrder = newOrder.concat(preSep);
preSep.splice(0);
}
newOrder.push(item);
}
else
preSep.push(item);
}
contents.containerOpen = false;
if (preSep.length > 0) {
preSep.sort(sortingMethod);
newOrder = newOrder.concat(preSep);
}
// set the nex indexes
var callback = {
runBatched: function() {
for (var i = 0; i < newOrder.length; ++i) {
PlacesUtils.bookmarks.setItemIndex(newOrder[i].itemId, i);
}
}
};
PlacesUtils.bookmarks.runInBatchMode(callback, null);
},
undoTransaction: function PSSFBN_undoTransaction() {
var callback = {
_self: this,
runBatched: function() {
for (item in this._self._oldOrder)
PlacesUtils.bookmarks.setItemIndex(item, this._self._oldOrder[item]);
}
};
PlacesUtils.bookmarks.runInBatchMode(callback, null);
}
};
function placesTagURITransaction(aURI, aTags) {
this._uri = aURI;
this._tags = aTags;
this._unfiledItemId = -1;
this.redoTransaction = this.doTransaction;
}
placesTagURITransaction.prototype = {
__proto__: placesBaseTransaction.prototype,
doTransaction: function PTU_doTransaction() {
if (PlacesUtils.getMostRecentBookmarkForURI(this._uri) == -1) {
// Force an unfiled bookmark first
this._unfiledItemId =
PlacesUtils.bookmarks
.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
this._uri,
PlacesUtils.bookmarks.DEFAULT_INDEX,
PlacesUtils.history.getPageTitle(this._uri));
if (this._GUID)
PlacesUtils.bookmarks.setItemGUID(this._unfiledItemId, this._GUID);
}
PlacesUtils.tagging.tagURI(this._uri, this._tags);
},
undoTransaction: function PTU_undoTransaction() {
if (this._unfiledItemId != -1) {
// If a GUID exists for this item, preserve it before removing the item.
if (PlacesUtils.annotations.itemHasAnnotation(this._unfiledItemId, GUID_ANNO)) {
this._GUID = PlacesUtils.bookmarks.getItemGUID(this._unfiledItemId);
}
PlacesUtils.bookmarks.removeItem(this._unfiledItemId);
this._unfiledItemId = -1;
}
PlacesUtils.tagging.untagURI(this._uri, this._tags);
}
};
function placesUntagURITransaction(aURI, aTags) {
this._uri = aURI;
if (aTags) {
// Within this transaction, we cannot rely on tags given by itemId
// since the tag containers may be gone after we call untagURI.
// Thus, we convert each tag given by its itemId to name.
this._tags = aTags;
for (var i=0; i < aTags.length; i++) {
if (typeof(this._tags[i]) == "number")
this._tags[i] = PlacesUtils.bookmarks.getItemTitle(this._tags[i]);
}
}
else
this._tags = PlacesUtils.tagging.getTagsForURI(this._uri, {});
this.redoTransaction = this.doTransaction;
}
placesUntagURITransaction.prototype = {
__proto__: placesBaseTransaction.prototype,
doTransaction: function PUTU_doTransaction() {
PlacesUtils.tagging.untagURI(this._uri, this._tags);
},
undoTransaction: function PUTU_undoTransaction() {
PlacesUtils.tagging.tagURI(this._uri, this._tags);
}
};
function NSGetModule(aCompMgr, aFileSpec) {
return XPCOMUtils.generateModule([placesTransactionsService]);
}
| csinitiative/trisano | webapp/features/support/firefox-36/components/nsPlacesTransactionsService.js | JavaScript | agpl-3.0 | 42,772 |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_STABLENORM_H
#define EIGEN_STABLENORM_H
namespace Eigen {
namespace internal {
template<typename ExpressionType, typename Scalar>
inline void stable_norm_kernel(const ExpressionType& bl, Scalar& ssq, Scalar& scale, Scalar& invScale)
{
using std::max;
Scalar maxCoeff = bl.cwiseAbs().maxCoeff();
if (maxCoeff>scale)
{
ssq = ssq * numext::abs2(scale/maxCoeff);
Scalar tmp = Scalar(1)/maxCoeff;
if(tmp > NumTraits<Scalar>::highest())
{
invScale = NumTraits<Scalar>::highest();
scale = Scalar(1)/invScale;
}
else
{
scale = maxCoeff;
invScale = tmp;
}
}
// TODO if the maxCoeff is much much smaller than the current scale,
// then we can neglect this sub vector
if(scale>Scalar(0)) // if scale==0, then bl is 0
ssq += (bl*invScale).squaredNorm();
}
template<typename Derived>
inline typename NumTraits<typename traits<Derived>::Scalar>::Real
blueNorm_impl(const EigenBase<Derived>& _vec)
{
typedef typename Derived::RealScalar RealScalar;
typedef typename Derived::Index Index;
using std::pow;
EIGEN_USING_STD_MATH(min);
EIGEN_USING_STD_MATH(max);
using std::sqrt;
using std::abs;
const Derived& vec(_vec.derived());
static bool initialized = false;
static RealScalar b1, b2, s1m, s2m, overfl, rbig, relerr;
if(!initialized)
{
int ibeta, it, iemin, iemax, iexp;
RealScalar eps;
// This program calculates the machine-dependent constants
// bl, b2, slm, s2m, relerr overfl
// from the "basic" machine-dependent numbers
// nbig, ibeta, it, iemin, iemax, rbig.
// The following define the basic machine-dependent constants.
// For portability, the PORT subprograms "ilmaeh" and "rlmach"
// are used. For any specific computer, each of the assignment
// statements can be replaced
ibeta = std::numeric_limits<RealScalar>::radix; // base for floating-point numbers
it = std::numeric_limits<RealScalar>::digits; // number of base-beta digits in mantissa
iemin = std::numeric_limits<RealScalar>::min_exponent; // minimum exponent
iemax = std::numeric_limits<RealScalar>::max_exponent; // maximum exponent
rbig = (std::numeric_limits<RealScalar>::max)(); // largest floating-point number
iexp = -((1-iemin)/2);
b1 = RealScalar(pow(RealScalar(ibeta),RealScalar(iexp))); // lower boundary of midrange
iexp = (iemax + 1 - it)/2;
b2 = RealScalar(pow(RealScalar(ibeta),RealScalar(iexp))); // upper boundary of midrange
iexp = (2-iemin)/2;
s1m = RealScalar(pow(RealScalar(ibeta),RealScalar(iexp))); // scaling factor for lower range
iexp = - ((iemax+it)/2);
s2m = RealScalar(pow(RealScalar(ibeta),RealScalar(iexp))); // scaling factor for upper range
overfl = rbig*s2m; // overflow boundary for abig
eps = RealScalar(pow(double(ibeta), 1-it));
relerr = sqrt(eps); // tolerance for neglecting asml
initialized = true;
}
Index n = vec.size();
RealScalar ab2 = b2 / RealScalar(n);
RealScalar asml = RealScalar(0);
RealScalar amed = RealScalar(0);
RealScalar abig = RealScalar(0);
for(typename Derived::InnerIterator it(vec, 0); it; ++it)
{
RealScalar ax = abs(it.value());
if(ax > ab2) abig += numext::abs2(ax*s2m);
else if(ax < b1) asml += numext::abs2(ax*s1m);
else amed += numext::abs2(ax);
}
if(abig > RealScalar(0))
{
abig = sqrt(abig);
if(abig > overfl)
{
return rbig;
}
if(amed > RealScalar(0))
{
abig = abig/s2m;
amed = sqrt(amed);
}
else
return abig/s2m;
}
else if(asml > RealScalar(0))
{
if (amed > RealScalar(0))
{
abig = sqrt(amed);
amed = sqrt(asml) / s1m;
}
else
return sqrt(asml)/s1m;
}
else
return sqrt(amed);
asml = (min)(abig, amed);
abig = (max)(abig, amed);
if(asml <= abig*relerr)
return abig;
else
return abig * sqrt(RealScalar(1) + numext::abs2(asml/abig));
}
} // end namespace internal
/** \returns the \em l2 norm of \c *this avoiding underflow and overflow.
* This version use a blockwise two passes algorithm:
* 1 - find the absolute largest coefficient \c s
* 2 - compute \f$ s \Vert \frac{*this}{s} \Vert \f$ in a standard way
*
* For architecture/scalar types supporting vectorization, this version
* is faster than blueNorm(). Otherwise the blueNorm() is much faster.
*
* \sa norm(), blueNorm(), hypotNorm()
*/
template<typename Derived>
inline typename NumTraits<typename internal::traits<Derived>::Scalar>::Real
MatrixBase<Derived>::stableNorm() const
{
EIGEN_USING_STD_MATH(min);
using std::sqrt;
const Index blockSize = 4096;
RealScalar scale(0);
RealScalar invScale(1);
RealScalar ssq(0); // sum of square
enum {
Alignment = (int(Flags)&DirectAccessBit) || (int(Flags)&AlignedBit) ? 1 : 0
};
Index n = size();
Index bi = internal::first_aligned(derived());
if (bi>0)
internal::stable_norm_kernel(this->head(bi), ssq, scale, invScale);
for (; bi<n; bi+=blockSize)
internal::stable_norm_kernel(this->segment(bi,(min)(blockSize, n - bi)).template forceAlignedAccessIf<Alignment>(), ssq, scale, invScale);
return scale * sqrt(ssq);
}
/** \returns the \em l2 norm of \c *this using the Blue's algorithm.
* A Portable Fortran Program to Find the Euclidean Norm of a Vector,
* ACM TOMS, Vol 4, Issue 1, 1978.
*
* For architecture/scalar types without vectorization, this version
* is much faster than stableNorm(). Otherwise the stableNorm() is faster.
*
* \sa norm(), stableNorm(), hypotNorm()
*/
template<typename Derived>
inline typename NumTraits<typename internal::traits<Derived>::Scalar>::Real
MatrixBase<Derived>::blueNorm() const
{
return internal::blueNorm_impl(*this);
}
/** \returns the \em l2 norm of \c *this avoiding undeflow and overflow.
* This version use a concatenation of hypot() calls, and it is very slow.
*
* \sa norm(), stableNorm()
*/
template<typename Derived>
inline typename NumTraits<typename internal::traits<Derived>::Scalar>::Real
MatrixBase<Derived>::hypotNorm() const
{
return this->cwiseAbs().redux(internal::scalar_hypot_op<RealScalar>());
}
} // end namespace Eigen
#endif // EIGEN_STABLENORM_H
| josephlewis42/UDenverQGC | src/libs/eigen/Eigen/src/Core/StableNorm.h | C | agpl-3.0 | 6,794 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
# Copyright (C) 2010-2014 OpenERP s.a. (<http://openerp.com>).
#
# 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/>.
#
##############################################################################
import itertools
import logging
from functools import partial
from itertools import repeat
from lxml import etree
from lxml.builder import E
import openerp
from openerp import SUPERUSER_ID, models
from openerp import tools
import openerp.exceptions
from openerp.osv import fields, osv, expression
from openerp.tools.translate import _
from openerp.http import request
_logger = logging.getLogger(__name__)
#----------------------------------------------------------
# Basic res.groups and res.users
#----------------------------------------------------------
class res_groups(osv.osv):
_name = "res.groups"
_description = "Access Groups"
_rec_name = 'full_name'
_order = 'name'
def _get_full_name(self, cr, uid, ids, field, arg, context=None):
res = {}
for g in self.browse(cr, uid, ids, context):
if g.category_id:
res[g.id] = '%s / %s' % (g.category_id.name, g.name)
else:
res[g.id] = g.name
return res
def _search_group(self, cr, uid, obj, name, args, context=None):
operand = args[0][2]
operator = args[0][1]
lst = True
if isinstance(operand, bool):
domains = [[('name', operator, operand)], [('category_id.name', operator, operand)]]
if operator in expression.NEGATIVE_TERM_OPERATORS == (not operand):
return expression.AND(domains)
else:
return expression.OR(domains)
if isinstance(operand, basestring):
lst = False
operand = [operand]
where = []
for group in operand:
values = filter(bool, group.split('/'))
group_name = values.pop().strip()
category_name = values and '/'.join(values).strip() or group_name
group_domain = [('name', operator, lst and [group_name] or group_name)]
category_domain = [('category_id.name', operator, lst and [category_name] or category_name)]
if operator in expression.NEGATIVE_TERM_OPERATORS and not values:
category_domain = expression.OR([category_domain, [('category_id', '=', False)]])
if (operator in expression.NEGATIVE_TERM_OPERATORS) == (not values):
sub_where = expression.AND([group_domain, category_domain])
else:
sub_where = expression.OR([group_domain, category_domain])
if operator in expression.NEGATIVE_TERM_OPERATORS:
where = expression.AND([where, sub_where])
else:
where = expression.OR([where, sub_where])
return where
_columns = {
'name': fields.char('Name', required=True, translate=True),
'users': fields.many2many('res.users', 'res_groups_users_rel', 'gid', 'uid', 'Users'),
'model_access': fields.one2many('ir.model.access', 'group_id', 'Access Controls'),
'rule_groups': fields.many2many('ir.rule', 'rule_group_rel',
'group_id', 'rule_group_id', 'Rules', domain=[('global', '=', False)]),
'menu_access': fields.many2many('ir.ui.menu', 'ir_ui_menu_group_rel', 'gid', 'menu_id', 'Access Menu'),
'view_access': fields.many2many('ir.ui.view', 'ir_ui_view_group_rel', 'group_id', 'view_id', 'Views'),
'comment' : fields.text('Comment', size=250, translate=True),
'category_id': fields.many2one('ir.module.category', 'Application', select=True),
'full_name': fields.function(_get_full_name, type='char', string='Group Name', fnct_search=_search_group),
}
_sql_constraints = [
('name_uniq', 'unique (category_id, name)', 'The name of the group must be unique within an application!')
]
def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
# add explicit ordering if search is sorted on full_name
if order and order.startswith('full_name'):
ids = super(res_groups, self).search(cr, uid, args, context=context)
gs = self.browse(cr, uid, ids, context)
gs.sort(key=lambda g: g.full_name, reverse=order.endswith('DESC'))
gs = gs[offset:offset+limit] if limit else gs[offset:]
return map(int, gs)
return super(res_groups, self).search(cr, uid, args, offset, limit, order, context, count)
def copy(self, cr, uid, id, default=None, context=None):
group_name = self.read(cr, uid, [id], ['name'])[0]['name']
default.update({'name': _('%s (copy)')%group_name})
return super(res_groups, self).copy(cr, uid, id, default, context)
def write(self, cr, uid, ids, vals, context=None):
if 'name' in vals:
if vals['name'].startswith('-'):
raise osv.except_osv(_('Error'),
_('The name of the group can not start with "-"'))
res = super(res_groups, self).write(cr, uid, ids, vals, context=context)
self.pool['ir.model.access'].call_cache_clearing_methods(cr)
self.pool['res.users'].has_group.clear_cache(self.pool['res.users'])
return res
class res_users(osv.osv):
""" User class. A res.users record models an OpenERP user and is different
from an employee.
res.users class now inherits from res.partner. The partner model is
used to store the data related to the partner: lang, name, address,
avatar, ... The user model is now dedicated to technical data.
"""
__admin_ids = {}
_uid_cache = {}
_inherits = {
'res.partner': 'partner_id',
}
_name = "res.users"
_description = 'Users'
def _set_new_password(self, cr, uid, id, name, value, args, context=None):
if value is False:
# Do not update the password if no value is provided, ignore silently.
# For example web client submits False values for all empty fields.
return
if uid == id:
# To change their own password users must use the client-specific change password wizard,
# so that the new password is immediately used for further RPC requests, otherwise the user
# will face unexpected 'Access Denied' exceptions.
raise osv.except_osv(_('Operation Canceled'), _('Please use the change password wizard (in User Preferences or User menu) to change your own password.'))
self.write(cr, uid, id, {'password': value})
def _get_password(self, cr, uid, ids, arg, karg, context=None):
return dict.fromkeys(ids, '')
_columns = {
'id': fields.integer('ID'),
'login_date': fields.date('Latest connection', select=1, copy=False),
'partner_id': fields.many2one('res.partner', required=True,
string='Related Partner', ondelete='restrict',
help='Partner-related data of the user', auto_join=True),
'login': fields.char('Login', size=64, required=True,
help="Used to log into the system"),
'password': fields.char('Password', size=64, invisible=True, copy=False,
help="Keep empty if you don't want the user to be able to connect on the system."),
'new_password': fields.function(_get_password, type='char', size=64,
fnct_inv=_set_new_password, string='Set Password',
help="Specify a value only when creating a user or if you're "\
"changing the user's password, otherwise leave empty. After "\
"a change of password, the user has to login again."),
'signature': fields.html('Signature'),
'active': fields.boolean('Active'),
'action_id': fields.many2one('ir.actions.actions', 'Home Action', help="If specified, this action will be opened at log on for this user, in addition to the standard menu."),
'groups_id': fields.many2many('res.groups', 'res_groups_users_rel', 'uid', 'gid', 'Groups'),
# Special behavior for this field: res.company.search() will only return the companies
# available to the current user (should be the user's companies?), when the user_preference
# context is set.
'company_id': fields.many2one('res.company', 'Company', required=True,
help='The company this user is currently working for.', context={'user_preference': True}),
'company_ids':fields.many2many('res.company','res_company_users_rel','user_id','cid','Companies'),
}
# overridden inherited fields to bypass access rights, in case you have
# access to the user but not its corresponding partner
name = openerp.fields.Char(related='partner_id.name', inherited=True)
email = openerp.fields.Char(related='partner_id.email', inherited=True)
def on_change_login(self, cr, uid, ids, login, context=None):
if login and tools.single_email_re.match(login):
return {'value': {'email': login}}
return {}
def onchange_state(self, cr, uid, ids, state_id, context=None):
partner_ids = [user.partner_id.id for user in self.browse(cr, uid, ids, context=context)]
return self.pool.get('res.partner').onchange_state(cr, uid, partner_ids, state_id, context=context)
def onchange_type(self, cr, uid, ids, is_company, context=None):
""" Wrapper on the user.partner onchange_type, because some calls to the
partner form view applied to the user may trigger the
partner.onchange_type method, but applied to the user object.
"""
partner_ids = [user.partner_id.id for user in self.browse(cr, uid, ids, context=context)]
return self.pool['res.partner'].onchange_type(cr, uid, partner_ids, is_company, context=context)
def onchange_address(self, cr, uid, ids, use_parent_address, parent_id, context=None):
""" Wrapper on the user.partner onchange_address, because some calls to the
partner form view applied to the user may trigger the
partner.onchange_type method, but applied to the user object.
"""
partner_ids = [user.partner_id.id for user in self.browse(cr, uid, ids, context=context)]
return self.pool['res.partner'].onchange_address(cr, uid, partner_ids, use_parent_address, parent_id, context=context)
def _check_company(self, cr, uid, ids, context=None):
return all(((this.company_id in this.company_ids) or not this.company_ids) for this in self.browse(cr, uid, ids, context))
_constraints = [
(_check_company, 'The chosen company is not in the allowed companies for this user', ['company_id', 'company_ids']),
]
_sql_constraints = [
('login_key', 'UNIQUE (login)', 'You can not have two users with the same login !')
]
def _get_company(self,cr, uid, context=None, uid2=False):
if not uid2:
uid2 = uid
# Use read() to compute default company, and pass load=_classic_write to
# avoid useless name_get() calls. This will avoid prefetching fields
# while computing default values for new db columns, as the
# db backend may not be fully initialized yet.
user_data = self.pool['res.users'].read(cr, uid, uid2, ['company_id'],
context=context, load='_classic_write')
comp_id = user_data['company_id']
return comp_id or False
def _get_companies(self, cr, uid, context=None):
c = self._get_company(cr, uid, context)
if c:
return [c]
return False
def _get_group(self,cr, uid, context=None):
dataobj = self.pool.get('ir.model.data')
result = []
try:
dummy,group_id = dataobj.get_object_reference(cr, SUPERUSER_ID, 'base', 'group_user')
result.append(group_id)
dummy,group_id = dataobj.get_object_reference(cr, SUPERUSER_ID, 'base', 'group_partner_manager')
result.append(group_id)
except ValueError:
# If these groups does not exists anymore
pass
return result
def _get_default_image(self, cr, uid, context=None):
return self.pool['res.partner']._get_default_image(cr, uid, False, colorize=True, context=context)
_defaults = {
'password': '',
'active': True,
'customer': False,
'company_id': _get_company,
'company_ids': _get_companies,
'groups_id': _get_group,
'image': _get_default_image,
}
# User can write on a few of his own fields (but not his groups for example)
SELF_WRITEABLE_FIELDS = ['password', 'signature', 'action_id', 'company_id', 'email', 'name', 'image', 'image_medium', 'image_small', 'lang', 'tz']
# User can read a few of his own fields
SELF_READABLE_FIELDS = ['signature', 'company_id', 'login', 'email', 'name', 'image', 'image_medium', 'image_small', 'lang', 'tz', 'tz_offset', 'groups_id', 'partner_id', '__last_update']
def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):
def override_password(o):
if 'password' in o and ('id' not in o or o['id'] != uid):
o['password'] = '********'
return o
if fields and (ids == [uid] or ids == uid):
for key in fields:
if not (key in self.SELF_READABLE_FIELDS or key.startswith('context_')):
break
else:
# safe fields only, so we read as super-user to bypass access rights
uid = SUPERUSER_ID
result = super(res_users, self).read(cr, uid, ids, fields=fields, context=context, load=load)
canwrite = self.pool['ir.model.access'].check(cr, uid, 'res.users', 'write', False)
if not canwrite:
if isinstance(ids, (int, long)):
result = override_password(result)
else:
result = map(override_password, result)
return result
def create(self, cr, uid, vals, context=None):
user_id = super(res_users, self).create(cr, uid, vals, context=context)
user = self.browse(cr, uid, user_id, context=context)
if user.partner_id.company_id:
user.partner_id.write({'company_id': user.company_id.id})
return user_id
def write(self, cr, uid, ids, values, context=None):
if not hasattr(ids, '__iter__'):
ids = [ids]
if ids == [uid]:
for key in values.keys():
if not (key in self.SELF_WRITEABLE_FIELDS or key.startswith('context_')):
break
else:
if 'company_id' in values:
user = self.browse(cr, SUPERUSER_ID, uid, context=context)
if not (values['company_id'] in user.company_ids.ids):
del values['company_id']
uid = 1 # safe fields only, so we write as super-user to bypass access rights
res = super(res_users, self).write(cr, uid, ids, values, context=context)
if 'company_id' in values:
for user in self.browse(cr, uid, ids, context=context):
# if partner is global we keep it that way
if user.partner_id.company_id and user.partner_id.company_id.id != values['company_id']:
user.partner_id.write({'company_id': user.company_id.id})
# clear caches linked to the users
self.pool['ir.model.access'].call_cache_clearing_methods(cr)
clear = partial(self.pool['ir.rule'].clear_cache, cr)
map(clear, ids)
db = cr.dbname
if db in self._uid_cache:
for id in ids:
if id in self._uid_cache[db]:
del self._uid_cache[db][id]
self.context_get.clear_cache(self)
self.has_group.clear_cache(self)
return res
def unlink(self, cr, uid, ids, context=None):
if 1 in ids:
raise osv.except_osv(_('Can not remove root user!'), _('You can not remove the admin user as it is used internally for resources created by Odoo (updates, module installation, ...)'))
db = cr.dbname
if db in self._uid_cache:
for id in ids:
if id in self._uid_cache[db]:
del self._uid_cache[db][id]
return super(res_users, self).unlink(cr, uid, ids, context=context)
def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
if not args:
args=[]
if not context:
context={}
ids = []
if name and operator in ['=', 'ilike']:
ids = self.search(cr, user, [('login','=',name)]+ args, limit=limit, context=context)
if not ids:
ids = self.search(cr, user, [('name',operator,name)]+ args, limit=limit, context=context)
return self.name_get(cr, user, ids, context=context)
def copy(self, cr, uid, id, default=None, context=None):
user2copy = self.read(cr, uid, [id], ['login','name'])[0]
default = dict(default or {})
if ('name' not in default) and ('partner_id' not in default):
default['name'] = _("%s (copy)") % user2copy['name']
if 'login' not in default:
default['login'] = _("%s (copy)") % user2copy['login']
return super(res_users, self).copy(cr, uid, id, default, context)
@tools.ormcache(skiparg=2)
def context_get(self, cr, uid, context=None):
user = self.browse(cr, SUPERUSER_ID, uid, context)
result = {}
for k in self._fields:
if k.startswith('context_'):
context_key = k[8:]
elif k in ['lang', 'tz']:
context_key = k
else:
context_key = False
if context_key:
res = getattr(user, k) or False
if isinstance(res, models.BaseModel):
res = res.id
result[context_key] = res or False
return result
def action_get(self, cr, uid, context=None):
dataobj = self.pool['ir.model.data']
data_id = dataobj._get_id(cr, SUPERUSER_ID, 'base', 'action_res_users_my')
return dataobj.browse(cr, uid, data_id, context=context).res_id
def check_super(self, passwd):
if passwd == tools.config['admin_passwd']:
return True
else:
raise openerp.exceptions.AccessDenied()
def check_credentials(self, cr, uid, password):
""" Override this method to plug additional authentication methods"""
res = self.search(cr, SUPERUSER_ID, [('id','=',uid),('password','=',password)])
if not res:
raise openerp.exceptions.AccessDenied()
def _login(self, db, login, password):
if not password:
return False
user_id = False
cr = self.pool.cursor()
try:
# autocommit: our single update request will be performed atomically.
# (In this way, there is no opportunity to have two transactions
# interleaving their cr.execute()..cr.commit() calls and have one
# of them rolled back due to a concurrent access.)
cr.autocommit(True)
# check if user exists
res = self.search(cr, SUPERUSER_ID, [('login','=',login)])
if res:
user_id = res[0]
# check credentials
self.check_credentials(cr, user_id, password)
# We effectively unconditionally write the res_users line.
# Even w/ autocommit there's a chance the user row will be locked,
# in which case we can't delay the login just for the purpose of
# update the last login date - hence we use FOR UPDATE NOWAIT to
# try to get the lock - fail-fast
# Failing to acquire the lock on the res_users row probably means
# another request is holding it. No big deal, we don't want to
# prevent/delay login in that case. It will also have been logged
# as a SQL error, if anyone cares.
try:
# NO KEY introduced in PostgreSQL 9.3 http://www.postgresql.org/docs/9.3/static/release-9-3.html#AEN115299
update_clause = 'NO KEY UPDATE' if cr._cnx.server_version >= 90300 else 'UPDATE'
cr.execute("SELECT id FROM res_users WHERE id=%%s FOR %s NOWAIT" % update_clause, (user_id,), log_exceptions=False)
cr.execute("UPDATE res_users SET login_date = now() AT TIME ZONE 'UTC' WHERE id=%s", (user_id,))
self.invalidate_cache(cr, user_id, ['login_date'], [user_id])
except Exception:
_logger.debug("Failed to update last_login for db:%s login:%s", db, login, exc_info=True)
except openerp.exceptions.AccessDenied:
_logger.info("Login failed for db:%s login:%s", db, login)
user_id = False
finally:
cr.close()
return user_id
def authenticate(self, db, login, password, user_agent_env):
"""Verifies and returns the user ID corresponding to the given
``login`` and ``password`` combination, or False if there was
no matching user.
:param str db: the database on which user is trying to authenticate
:param str login: username
:param str password: user password
:param dict user_agent_env: environment dictionary describing any
relevant environment attributes
"""
uid = self._login(db, login, password)
if uid == openerp.SUPERUSER_ID:
# Successfully logged in as admin!
# Attempt to guess the web base url...
if user_agent_env and user_agent_env.get('base_location'):
cr = self.pool.cursor()
try:
base = user_agent_env['base_location']
ICP = self.pool['ir.config_parameter']
if not ICP.get_param(cr, uid, 'web.base.url.freeze'):
ICP.set_param(cr, uid, 'web.base.url', base)
cr.commit()
except Exception:
_logger.exception("Failed to update web.base.url configuration parameter")
finally:
cr.close()
return uid
def check(self, db, uid, passwd):
"""Verifies that the given (uid, password) is authorized for the database ``db`` and
raise an exception if it is not."""
if not passwd:
# empty passwords disallowed for obvious security reasons
raise openerp.exceptions.AccessDenied()
if self._uid_cache.get(db, {}).get(uid) == passwd:
return
cr = self.pool.cursor()
try:
self.check_credentials(cr, uid, passwd)
if self._uid_cache.has_key(db):
self._uid_cache[db][uid] = passwd
else:
self._uid_cache[db] = {uid:passwd}
finally:
cr.close()
def change_password(self, cr, uid, old_passwd, new_passwd, context=None):
"""Change current user password. Old password must be provided explicitly
to prevent hijacking an existing user session, or for cases where the cleartext
password is not used to authenticate requests.
:return: True
:raise: openerp.exceptions.AccessDenied when old password is wrong
:raise: except_osv when new password is not set or empty
"""
self.check(cr.dbname, uid, old_passwd)
if new_passwd:
return self.write(cr, uid, uid, {'password': new_passwd})
raise osv.except_osv(_('Warning!'), _("Setting empty passwords is not allowed for security reasons!"))
def preference_save(self, cr, uid, ids, context=None):
return {
'type': 'ir.actions.client',
'tag': 'reload_context',
}
def preference_change_password(self, cr, uid, ids, context=None):
return {
'type': 'ir.actions.client',
'tag': 'change_password',
'target': 'new',
}
@tools.ormcache(skiparg=2)
def has_group(self, cr, uid, group_ext_id):
"""Checks whether user belongs to given group.
:param str group_ext_id: external ID (XML ID) of the group.
Must be provided in fully-qualified form (``module.ext_id``), as there
is no implicit module to use..
:return: True if the current user is a member of the group with the
given external ID (XML ID), else False.
"""
assert group_ext_id and '.' in group_ext_id, "External ID must be fully qualified"
module, ext_id = group_ext_id.split('.')
cr.execute("""SELECT 1 FROM res_groups_users_rel WHERE uid=%s AND gid IN
(SELECT res_id FROM ir_model_data WHERE module=%s AND name=%s)""",
(uid, module, ext_id))
return bool(cr.fetchone())
#----------------------------------------------------------
# Implied groups
#
# Extension of res.groups and res.users with a relation for "implied"
# or "inherited" groups. Once a user belongs to a group, it
# automatically belongs to the implied groups (transitively).
#----------------------------------------------------------
class cset(object):
""" A cset (constrained set) is a set of elements that may be constrained to
be a subset of other csets. Elements added to a cset are automatically
added to its supersets. Cycles in the subset constraints are supported.
"""
def __init__(self, xs):
self.supersets = set()
self.elements = set(xs)
def subsetof(self, other):
if other is not self:
self.supersets.add(other)
other.update(self.elements)
def update(self, xs):
xs = set(xs) - self.elements
if xs: # xs will eventually be empty in case of a cycle
self.elements.update(xs)
for s in self.supersets:
s.update(xs)
def __iter__(self):
return iter(self.elements)
concat = itertools.chain.from_iterable
class groups_implied(osv.osv):
_inherit = 'res.groups'
def _get_trans_implied(self, cr, uid, ids, field, arg, context=None):
"computes the transitive closure of relation implied_ids"
memo = {} # use a memo for performance and cycle avoidance
def computed_set(g):
if g not in memo:
memo[g] = cset(g.implied_ids)
for h in g.implied_ids:
computed_set(h).subsetof(memo[g])
return memo[g]
res = {}
for g in self.browse(cr, SUPERUSER_ID, ids, context):
res[g.id] = map(int, computed_set(g))
return res
_columns = {
'implied_ids': fields.many2many('res.groups', 'res_groups_implied_rel', 'gid', 'hid',
string='Inherits', help='Users of this group automatically inherit those groups'),
'trans_implied_ids': fields.function(_get_trans_implied,
type='many2many', relation='res.groups', string='Transitively inherits'),
}
def create(self, cr, uid, values, context=None):
users = values.pop('users', None)
gid = super(groups_implied, self).create(cr, uid, values, context)
if users:
# delegate addition of users to add implied groups
self.write(cr, uid, [gid], {'users': users}, context)
return gid
def write(self, cr, uid, ids, values, context=None):
res = super(groups_implied, self).write(cr, uid, ids, values, context)
if values.get('users') or values.get('implied_ids'):
# add all implied groups (to all users of each group)
for g in self.browse(cr, uid, ids, context=context):
gids = map(int, g.trans_implied_ids)
vals = {'users': [(4, u.id) for u in g.users]}
super(groups_implied, self).write(cr, uid, gids, vals, context)
return res
class users_implied(osv.osv):
_inherit = 'res.users'
def create(self, cr, uid, values, context=None):
groups = values.pop('groups_id', None)
user_id = super(users_implied, self).create(cr, uid, values, context)
if groups:
# delegate addition of groups to add implied groups
self.write(cr, uid, [user_id], {'groups_id': groups}, context)
self.pool['ir.ui.view'].clear_cache()
return user_id
def write(self, cr, uid, ids, values, context=None):
if not isinstance(ids,list):
ids = [ids]
res = super(users_implied, self).write(cr, uid, ids, values, context)
if values.get('groups_id'):
# add implied groups for all users
for user in self.browse(cr, uid, ids):
gs = set(concat(g.trans_implied_ids for g in user.groups_id))
vals = {'groups_id': [(4, g.id) for g in gs]}
super(users_implied, self).write(cr, uid, [user.id], vals, context)
self.pool['ir.ui.view'].clear_cache()
return res
#----------------------------------------------------------
# Vitrual checkbox and selection for res.user form view
#
# Extension of res.groups and res.users for the special groups view in the users
# form. This extension presents groups with selection and boolean widgets:
# - Groups are shown by application, with boolean and/or selection fields.
# Selection fields typically defines a role "Name" for the given application.
# - Uncategorized groups are presented as boolean fields and grouped in a
# section "Others".
#
# The user form view is modified by an inherited view (base.user_groups_view);
# the inherited view replaces the field 'groups_id' by a set of reified group
# fields (boolean or selection fields). The arch of that view is regenerated
# each time groups are changed.
#
# Naming conventions for reified groups fields:
# - boolean field 'in_group_ID' is True iff
# ID is in 'groups_id'
# - selection field 'sel_groups_ID1_..._IDk' is ID iff
# ID is in 'groups_id' and ID is maximal in the set {ID1, ..., IDk}
#----------------------------------------------------------
def name_boolean_group(id):
return 'in_group_' + str(id)
def name_selection_groups(ids):
return 'sel_groups_' + '_'.join(map(str, ids))
def is_boolean_group(name):
return name.startswith('in_group_')
def is_selection_groups(name):
return name.startswith('sel_groups_')
def is_reified_group(name):
return is_boolean_group(name) or is_selection_groups(name)
def get_boolean_group(name):
return int(name[9:])
def get_selection_groups(name):
return map(int, name[11:].split('_'))
def partition(f, xs):
"return a pair equivalent to (filter(f, xs), filter(lambda x: not f(x), xs))"
yes, nos = [], []
for x in xs:
(yes if f(x) else nos).append(x)
return yes, nos
def parse_m2m(commands):
"return a list of ids corresponding to a many2many value"
ids = []
for command in commands:
if isinstance(command, (tuple, list)):
if command[0] in (1, 4):
ids.append(command[2])
elif command[0] == 5:
ids = []
elif command[0] == 6:
ids = list(command[2])
else:
ids.append(command)
return ids
class groups_view(osv.osv):
_inherit = 'res.groups'
def create(self, cr, uid, values, context=None):
res = super(groups_view, self).create(cr, uid, values, context)
self.update_user_groups_view(cr, uid, context)
return res
def write(self, cr, uid, ids, values, context=None):
res = super(groups_view, self).write(cr, uid, ids, values, context)
self.update_user_groups_view(cr, uid, context)
return res
def unlink(self, cr, uid, ids, context=None):
res = super(groups_view, self).unlink(cr, uid, ids, context)
self.update_user_groups_view(cr, uid, context)
return res
def update_user_groups_view(self, cr, uid, context=None):
# the view with id 'base.user_groups_view' inherits the user form view,
# and introduces the reified group fields
# we have to try-catch this, because at first init the view does not exist
# but we are already creating some basic groups
view = self.pool['ir.model.data'].xmlid_to_object(cr, SUPERUSER_ID, 'base.user_groups_view', context=context)
if view and view.exists() and view._name == 'ir.ui.view':
xml1, xml2 = [], []
xml1.append(E.separator(string=_('Application'), colspan="4"))
for app, kind, gs in self.get_groups_by_application(cr, uid, context):
# hide groups in category 'Hidden' (except to group_no_one)
attrs = {'groups': 'base.group_no_one'} if app and app.xml_id == 'base.module_category_hidden' else {}
if kind == 'selection':
# application name with a selection field
field_name = name_selection_groups(map(int, gs))
xml1.append(E.field(name=field_name, **attrs))
xml1.append(E.newline())
else:
# application separator with boolean fields
app_name = app and app.name or _('Other')
xml2.append(E.separator(string=app_name, colspan="4", **attrs))
for g in gs:
field_name = name_boolean_group(g.id)
xml2.append(E.field(name=field_name, **attrs))
xml = E.field(*(xml1 + xml2), name="groups_id", position="replace")
xml.addprevious(etree.Comment("GENERATED AUTOMATICALLY BY GROUPS"))
xml_content = etree.tostring(xml, pretty_print=True, xml_declaration=True, encoding="utf-8")
view.write({'arch': xml_content})
return True
def get_application_groups(self, cr, uid, domain=None, context=None):
return self.search(cr, uid, domain or [])
def get_groups_by_application(self, cr, uid, context=None):
""" return all groups classified by application (module category), as a list of pairs:
[(app, kind, [group, ...]), ...],
where app and group are browse records, and kind is either 'boolean' or 'selection'.
Applications are given in sequence order. If kind is 'selection', the groups are
given in reverse implication order.
"""
def linearized(gs):
gs = set(gs)
# determine sequence order: a group should appear after its implied groups
order = dict.fromkeys(gs, 0)
for g in gs:
for h in gs.intersection(g.trans_implied_ids):
order[h] -= 1
# check whether order is total, i.e., sequence orders are distinct
if len(set(order.itervalues())) == len(gs):
return sorted(gs, key=lambda g: order[g])
return None
# classify all groups by application
gids = self.get_application_groups(cr, uid, context=context)
by_app, others = {}, []
for g in self.browse(cr, uid, gids, context):
if g.category_id:
by_app.setdefault(g.category_id, []).append(g)
else:
others.append(g)
# build the result
res = []
apps = sorted(by_app.iterkeys(), key=lambda a: a.sequence or 0)
for app in apps:
gs = linearized(by_app[app])
if gs:
res.append((app, 'selection', gs))
else:
res.append((app, 'boolean', by_app[app]))
if others:
res.append((False, 'boolean', others))
return res
class users_view(osv.osv):
_inherit = 'res.users'
def create(self, cr, uid, values, context=None):
values = self._remove_reified_groups(values)
return super(users_view, self).create(cr, uid, values, context)
def write(self, cr, uid, ids, values, context=None):
values = self._remove_reified_groups(values)
return super(users_view, self).write(cr, uid, ids, values, context)
def _remove_reified_groups(self, values):
""" return `values` without reified group fields """
add, rem = [], []
values1 = {}
for key, val in values.iteritems():
if is_boolean_group(key):
(add if val else rem).append(get_boolean_group(key))
elif is_selection_groups(key):
rem += get_selection_groups(key)
if val:
add.append(val)
else:
values1[key] = val
if 'groups_id' not in values and (add or rem):
# remove group ids in `rem` and add group ids in `add`
values1['groups_id'] = zip(repeat(3), rem) + zip(repeat(4), add)
return values1
def default_get(self, cr, uid, fields, context=None):
group_fields, fields = partition(is_reified_group, fields)
fields1 = (fields + ['groups_id']) if group_fields else fields
values = super(users_view, self).default_get(cr, uid, fields1, context)
self._add_reified_groups(group_fields, values)
# add "default_groups_ref" inside the context to set default value for group_id with xml values
if 'groups_id' in fields and isinstance(context.get("default_groups_ref"), list):
groups = []
ir_model_data = self.pool.get('ir.model.data')
for group_xml_id in context["default_groups_ref"]:
group_split = group_xml_id.split('.')
if len(group_split) != 2:
raise osv.except_osv(_('Invalid context value'), _('Invalid context default_groups_ref value (model.name_id) : "%s"') % group_xml_id)
try:
temp, group_id = ir_model_data.get_object_reference(cr, uid, group_split[0], group_split[1])
except ValueError:
group_id = False
groups += [group_id]
values['groups_id'] = groups
return values
def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):
# determine whether reified groups fields are required, and which ones
fields1 = fields or self.fields_get(cr, uid, context=context).keys()
group_fields, other_fields = partition(is_reified_group, fields1)
# read regular fields (other_fields); add 'groups_id' if necessary
drop_groups_id = False
if group_fields and fields:
if 'groups_id' not in other_fields:
other_fields.append('groups_id')
drop_groups_id = True
else:
other_fields = fields
res = super(users_view, self).read(cr, uid, ids, other_fields, context=context, load=load)
# post-process result to add reified group fields
if group_fields:
for values in (res if isinstance(res, list) else [res]):
self._add_reified_groups(group_fields, values)
if drop_groups_id:
values.pop('groups_id', None)
return res
def _add_reified_groups(self, fields, values):
""" add the given reified group fields into `values` """
gids = set(parse_m2m(values.get('groups_id') or []))
for f in fields:
if is_boolean_group(f):
values[f] = get_boolean_group(f) in gids
elif is_selection_groups(f):
selected = [gid for gid in get_selection_groups(f) if gid in gids]
values[f] = selected and selected[-1] or False
def fields_get(self, cr, uid, allfields=None, context=None, write_access=True):
res = super(users_view, self).fields_get(cr, uid, allfields, context, write_access)
# add reified groups fields
for app, kind, gs in self.pool['res.groups'].get_groups_by_application(cr, uid, context):
if kind == 'selection':
# selection group field
tips = ['%s: %s' % (g.name, g.comment) for g in gs if g.comment]
res[name_selection_groups(map(int, gs))] = {
'type': 'selection',
'string': app and app.name or _('Other'),
'selection': [(False, '')] + [(g.id, g.name) for g in gs],
'help': '\n'.join(tips),
'exportable': False,
'selectable': False,
}
else:
# boolean group fields
for g in gs:
res[name_boolean_group(g.id)] = {
'type': 'boolean',
'string': g.name,
'help': g.comment,
'exportable': False,
'selectable': False,
}
return res
#----------------------------------------------------------
# change password wizard
#----------------------------------------------------------
class change_password_wizard(osv.TransientModel):
"""
A wizard to manage the change of users' passwords
"""
_name = "change.password.wizard"
_description = "Change Password Wizard"
_columns = {
'user_ids': fields.one2many('change.password.user', 'wizard_id', string='Users'),
}
def _default_user_ids(self, cr, uid, context=None):
if context is None:
context = {}
user_model = self.pool['res.users']
user_ids = context.get('active_model') == 'res.users' and context.get('active_ids') or []
return [
(0, 0, {'user_id': user.id, 'user_login': user.login})
for user in user_model.browse(cr, uid, user_ids, context=context)
]
_defaults = {
'user_ids': _default_user_ids,
}
def change_password_button(self, cr, uid, ids, context=None):
wizard = self.browse(cr, uid, ids, context=context)[0]
need_reload = any(uid == user.user_id.id for user in wizard.user_ids)
line_ids = [user.id for user in wizard.user_ids]
self.pool.get('change.password.user').change_password_button(cr, uid, line_ids, context=context)
if need_reload:
return {
'type': 'ir.actions.client',
'tag': 'reload'
}
return {'type': 'ir.actions.act_window_close'}
class change_password_user(osv.TransientModel):
"""
A model to configure users in the change password wizard
"""
_name = 'change.password.user'
_description = 'Change Password Wizard User'
_columns = {
'wizard_id': fields.many2one('change.password.wizard', string='Wizard', required=True),
'user_id': fields.many2one('res.users', string='User', required=True),
'user_login': fields.char('User Login', readonly=True),
'new_passwd': fields.char('New Password'),
}
_defaults = {
'new_passwd': '',
}
def change_password_button(self, cr, uid, ids, context=None):
for line in self.browse(cr, uid, ids, context=context):
line.user_id.write({'password': line.new_passwd})
# don't keep temporary passwords in the database longer than necessary
self.write(cr, uid, ids, {'new_passwd': False}, context=context)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| danielharbor/openerp | openerp/addons/base/res/res_users.py | Python | agpl-3.0 | 44,634 |
// Copyright 2017 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package storage
import (
"github.com/prometheus/prometheus/model/labels"
)
type noopQuerier struct{}
// NoopQuerier is a Querier that does nothing.
func NoopQuerier() Querier {
return noopQuerier{}
}
func (noopQuerier) Select(bool, *SelectHints, ...*labels.Matcher) SeriesSet {
return NoopSeriesSet()
}
func (noopQuerier) LabelValues(string, ...*labels.Matcher) ([]string, Warnings, error) {
return nil, nil, nil
}
func (noopQuerier) LabelNames(...*labels.Matcher) ([]string, Warnings, error) {
return nil, nil, nil
}
func (noopQuerier) Close() error {
return nil
}
type noopChunkQuerier struct{}
// NoopChunkedQuerier is a ChunkQuerier that does nothing.
func NoopChunkedQuerier() ChunkQuerier {
return noopChunkQuerier{}
}
func (noopChunkQuerier) Select(bool, *SelectHints, ...*labels.Matcher) ChunkSeriesSet {
return NoopChunkedSeriesSet()
}
func (noopChunkQuerier) LabelValues(string, ...*labels.Matcher) ([]string, Warnings, error) {
return nil, nil, nil
}
func (noopChunkQuerier) LabelNames(...*labels.Matcher) ([]string, Warnings, error) {
return nil, nil, nil
}
func (noopChunkQuerier) Close() error {
return nil
}
type noopSeriesSet struct{}
// NoopSeriesSet is a SeriesSet that does nothing.
func NoopSeriesSet() SeriesSet {
return noopSeriesSet{}
}
func (noopSeriesSet) Next() bool { return false }
func (noopSeriesSet) At() Series { return nil }
func (noopSeriesSet) Err() error { return nil }
func (noopSeriesSet) Warnings() Warnings { return nil }
type noopChunkedSeriesSet struct{}
// NoopChunkedSeriesSet is a ChunkSeriesSet that does nothing.
func NoopChunkedSeriesSet() ChunkSeriesSet {
return noopChunkedSeriesSet{}
}
func (noopChunkedSeriesSet) Next() bool { return false }
func (noopChunkedSeriesSet) At() ChunkSeries { return nil }
func (noopChunkedSeriesSet) Err() error { return nil }
func (noopChunkedSeriesSet) Warnings() Warnings { return nil }
| grafana/loki | vendor/github.com/prometheus/prometheus/storage/noop.go | GO | agpl-3.0 | 2,503 |
/*
YUI 3.11.0 (build d549e5c)
Copyright 2013 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('tree-openable', function (Y, NAME) {
/*jshint expr:true, onevar:false */
/**
Extension for `Tree` that adds the concept of open/closed state for nodes.
@module tree
@submodule tree-openable
@main tree-openable
**/
/**
Extension for `Tree` that adds the concept of open/closed state for nodes.
@class Tree.Openable
@constructor
@extensionfor Tree
**/
/**
Fired when a node is closed.
@event close
@param {Tree.Node} node Node being closed.
@param {String} src Source of the event.
@preventable _defCloseFn
**/
var EVT_CLOSE = 'close';
/**
Fired when a node is opened.
@event open
@param {Tree.Node} node Node being opened.
@param {String} src Source of the event.
@preventable _defOpenFn
**/
var EVT_OPEN = 'open';
function Openable() {}
Openable.prototype = {
// -- Lifecycle ------------------------------------------------------------
initializer: function () {
this.nodeExtensions = this.nodeExtensions.concat(Y.Tree.Node.Openable);
},
// -- Public Methods -------------------------------------------------------
/**
Closes the specified node if it isn't already closed.
@method closeNode
@param {Tree.Node} node Node to close.
@param {Object} [options] Options.
@param {Boolean} [options.silent=false] If `true`, the `close` event
will be suppressed.
@param {String} [options.src] Source of the change, to be passed along
to the event facade of the resulting event. This can be used to
distinguish between changes triggered by a user and changes
triggered programmatically, for example.
@chainable
**/
closeNode: function (node, options) {
if (node.canHaveChildren && node.isOpen()) {
this._fireTreeEvent(EVT_CLOSE, {
node: node,
src : options && options.src
}, {
defaultFn: this._defCloseFn,
silent : options && options.silent
});
}
return this;
},
/**
Opens the specified node if it isn't already open.
@method openNode
@param {Tree.Node} node Node to open.
@param {Object} [options] Options.
@param {Boolean} [options.silent=false] If `true`, the `open` event
will be suppressed.
@param {String} [options.src] Source of the change, to be passed along
to the event facade of the resulting event. This can be used to
distinguish between changes triggered by a user and changes
triggered programmatically, for example.
@chainable
**/
openNode: function (node, options) {
if (node.canHaveChildren && !node.isOpen()) {
this._fireTreeEvent(EVT_OPEN, {
node: node,
src : options && options.src
}, {
defaultFn: this._defOpenFn,
silent : options && options.silent
});
}
return this;
},
/**
Toggles the open/closed state of the specified node, closing it if it's
currently open or opening it if it's currently closed.
@method toggleOpenNode
@param {Tree.Node} node Node to toggle.
@param {Object} [options] Options.
@param {Boolean} [options.silent=false] If `true`, events will be
suppressed.
@param {String} [options.src] Source of the change, to be passed along
to the event facade of the resulting event. This can be used to
distinguish between changes triggered by a user and changes
triggered programmatically, for example.
@chainable
**/
toggleOpenNode: function (node, options) {
return node.isOpen() ? this.closeNode(node, options) :
this.openNode(node, options);
},
// -- Default Event Handlers -----------------------------------------------
/**
Default handler for the `close` event.
@method _defCloseFn
@param {EventFacade} e
@protected
**/
_defCloseFn: function (e) {
delete e.node.state.open;
},
/**
Default handler for the `open` event.
@method _defOpenFn
@param {EventFacade} e
@protected
**/
_defOpenFn: function (e) {
e.node.state.open = true;
}
};
Y.Tree.Openable = Openable;
/**
@module tree
@submodule tree-openable
**/
/**
`Tree.Node` extension that adds methods useful for nodes in trees that use the
`Tree.Openable` extension.
@class Tree.Node.Openable
@constructor
@extensionfor Tree.Node
**/
function NodeOpenable() {}
NodeOpenable.prototype = {
/**
Closes this node if it's currently open.
@method close
@param {Object} [options] Options.
@param {Boolean} [options.silent=false] If `true`, the `close` event
will be suppressed.
@param {String} [options.src] Source of the change, to be passed along
to the event facade of the resulting event. This can be used to
distinguish between changes triggered by a user and changes
triggered programmatically, for example.
@chainable
**/
close: function (options) {
this.tree.closeNode(this, options);
return this;
},
/**
Returns `true` if this node is currently open.
Note: the root node of a tree is always considered to be open.
@method isOpen
@return {Boolean} `true` if this node is currently open, `false` otherwise.
**/
isOpen: function () {
return !!this.state.open || this.isRoot();
},
/**
Opens this node if it's currently closed.
@method open
@param {Object} [options] Options.
@param {Boolean} [options.silent=false] If `true`, the `open` event
will be suppressed.
@param {String} [options.src] Source of the change, to be passed along
to the event facade of the resulting event. This can be used to
distinguish between changes triggered by a user and changes
triggered programmatically, for example.
@chainable
**/
open: function (options) {
this.tree.openNode(this, options);
return this;
},
/**
Toggles the open/closed state of this node, closing it if it's currently
open or opening it if it's currently closed.
@method toggleOpen
@param {Object} [options] Options.
@param {Boolean} [options.silent=false] If `true`, events will be
suppressed.
@param {String} [options.src] Source of the change, to be passed along
to the event facade of the resulting event. This can be used to
distinguish between changes triggered by a user and changes
triggered programmatically, for example.
@chainable
**/
toggleOpen: function (options) {
this.tree.toggleOpenNode(this, options);
return this;
}
};
Y.Tree.Node.Openable = NodeOpenable;
}, '3.11.0', {"requires": ["tree"]});
| devmix/openjst | server/commons/war/src/main/webapp/ui/lib/yui/build/tree-openable/tree-openable.js | JavaScript | agpl-3.0 | 7,103 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.