repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
viralj/Would-You-Rather-UdacityReactNanodegree
src/components/User.js
import React, {Component} from 'react' import {connect} from 'react-redux' import Rank from './RankComp' import {ViewBox} from './ViewBoxComp' class User extends Component { render() { const {user, questionCount, answerCount} = this.props; const viewName = 'user'; const title = user.name; const avatarURL = user.avatarURL; return ( <ViewBox viewName={viewName} title={title} avatarURL={avatarURL}> <Rank questionCount={questionCount} answerCount={answerCount}/> </ViewBox> ) } } function mapStateToProps({users}, {id}) { const user = users[id]; return { user } } export default connect(mapStateToProps)(User)
OctaviantoVyan/jwswing
WheelCombo/src/java/example/MainPanel.java
<gh_stars>1-10 // -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.event.MouseWheelListener; import javax.swing.*; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); JPanel p = new JPanel(new GridBagLayout()); p.setBorder(BorderFactory.createTitledBorder("JComboBox")); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.insets = new Insets(5, 5, 5, 0); c.anchor = GridBagConstraints.LINE_END; p.add(new JLabel("Wheel:"), c); p.add(new JLabel("Normal:"), c); c.gridx = 1; c.weightx = 1d; c.fill = GridBagConstraints.HORIZONTAL; p.add(makeComboBox(), c); p.add(new JComboBox<>(makeModel()), c); JTextArea textArea = new JTextArea(); add(p, BorderLayout.NORTH); add(new JScrollPane(textArea)); setPreferredSize(new Dimension(320, 240)); } private static JComboBox<String> makeComboBox() { return new JComboBox<String>(makeModel()) { private transient MouseWheelListener handler; @Override public void updateUI() { removeMouseWheelListener(handler); super.updateUI(); handler = e -> { Component c = e.getComponent(); if (c.hasFocus() && c instanceof JComboBox) { JComboBox<?> combo = (JComboBox<?>) c; int idx = combo.getSelectedIndex() + e.getWheelRotation(); if (idx >= 0 && idx < combo.getItemCount()) { combo.setSelectedIndex(idx); } } }; addMouseWheelListener(handler); } }; } private static ComboBoxModel<String> makeModel() { DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(); model.addElement("111111"); model.addElement("22222222"); model.addElement("3333333333"); model.addElement("444444444444"); model.addElement("5555555"); model.addElement("66666666666"); model.addElement("77777777"); model.addElement("88888888888"); return model; } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
MJYCo-Ltd/Map
Plot/Map/Atmosphere.cpp
#include <SceneGraph/ISceneGraph.h> #include <Inner/IOsgSceneNode.h> #include <Inner/ILoadResource.h> #include <osgEarth/VirtualProgram> #include <VersionMathCommon.h> #include <osgEarth/SpatialReference> #include "Atmosphere.h" CAtmosphere::CAtmosphere(ISceneGraph* pSceneGraph) { IPlot* pPlot=pSceneGraph->GetPlot(); m_pEllipsoid=dynamic_cast<IEllipsoidSensor*>(pPlot->CreateSceneNode("IEllipsoidSensor")); m_pEllipsoid->SetDrawType(IEllipsoidSensor::FULL_PART); m_pEllipsoid->SetEquator(R_Earth*1.025); m_pEllipsoid->SetPolar(R_Earth2*1.025); m_pEllipsoid->ShowLine(false); m_pEllipsoid->SetLatSegMents(100); m_pEllipsoid->MergeStateSet(ATMOSPHERE_DRAW_STATE|DONT_WRIT_DEPTH); } void CAtmosphere::MakeAtmosphere() { } osg::Node *CAtmosphere::GetNode() { return(m_pEllipsoid->AsOsgSceneNode()->GetRealNode()); } void CAtmosphere::SetVisible(bool bVisilbe) { m_pEllipsoid->SetVisible(bVisilbe); }
dendisuhubdy/Vitis-AI
Vitis-AI-Library/overview/samples/medicalsegmentation/process_result.hpp
/* * Copyright 2019 Xilinx 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. */ #pragma once #include <vector> #include <sys/stat.h> #include <iostream> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include "vitis/ai/medicalsegmentation.hpp" using namespace cv; using namespace std; Scalar colors[] = { Scalar(255, 0, 0), Scalar(0, 255, 0), Scalar(0, 0, 255), Scalar(255, 0, 255), Scalar(0, 255, 255)}; std::vector<std::string> classTypes = {"BE", "cancer", "HGD" , "polyp", "suspicious"}; std::string filenamepart1 = "testfile"; static cv::Mat process_result(cv::Mat &m1, const vitis::ai::MedicalSegmentationResult &result, bool is_jpeg) { cv::Mat img_save; cv::Mat img_orig(m1); // if dir doesn't exist, create it. for(int i=0; i<6; i++) { std::string path = "results"; if (i!=0) { path=path+ "/" + classTypes[i-1]; } auto ret = mkdir(path.c_str(), 0777); if (!(ret == 0 || (ret == -1 && EEXIST == errno) )) { std::cout <<"error occured when mkdir " << path << std::endl; return cv::Mat(); } if (i==0) continue; std::string fname("results/"+classTypes[i-1]+"/"+filenamepart1+".png"); cv::resize(result.segmentation[i-1], img_save, m1.size(), 0, 0, cv::INTER_LINEAR); cv::imwrite(fname,img_save); // Save the result as an image; auto img_true = cv::imread(fname, 0); // gray vector<vector<Point> > contours; vector<Vec4i> hierarchy; cv::findContours(img_true, contours, hierarchy, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE); if (contours.size()) { cv::drawContours(img_orig, contours, -1, colors[i-1], 3); // auto midVal = int(contours[0].size()/2); // cv2.putText(raw_img ,classTypes[i],(contours[0][midVal][0][0], contours[0][midVal][0][1]), cv2.FONT_HERSHEY_SIMPLEX, 1,(255,255,255),2,cv2.LINE_AA) } } return img_orig; }
Sirherobrine23/Dir819gpl_code
DIR819_v1.06/src/vendor/ralink/mt7510_ptm/7510ptm_loopback.c
<filename>DIR819_v1.06/src/vendor/ralink/mt7510_ptm/7510ptm_loopback.c #include <linux/module.h> #include <linux/kernel.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/spinlock.h> #include <linux/interrupt.h> #include <linux/signal.h> #include <linux/sched.h> #include <linux/mm.h> #include <linux/init.h> #include <linux/timer.h> #include <linux/delay.h> #include <linux/proc_fs.h> #include <linux/dma-mapping.h> #include <linux/version.h> #include <asm/spram.h> #include <asm/io.h> #include <asm/tc3162/tc3162.h> #include <asm/tc3162/ledcetrl.h> #include "../include/tcversion.h" #include <linux/skbuff.h> #include "7510ptm.h" #include "../bufmgr/qdma_api.h" #include "../fe_api/fe_api.h" #define RX_BUF_LEN (2048 - NET_SKB_PAD - 64 - (sizeof(struct skb_shared_info))) #define PKT_PATTERN_NUM 6 #define CHK_BUF() pos = begin + index; if (pos < off) { index = 0; begin = pos; }; if (pos > off + count) goto done; #define INC_PKTTYPE 0 #define RAN_PKTTYPE 1 #define ZERO_PKTTYPE 2 #define FF_PKTTYPE 3 #define FA_PKTTYPE 4 #define AF_PKTTYPE 5 #define LOOP_SLEEP_TIME 500 #define TEST_SLEEP_TIME 5000 #define TX_HOLD_TIME msecs_to_jiffies(1) /* in case QDMA IRQ (default is 512) is full, just put * (TX_QUEUE_LEN-4) packets in each Txq */ #define TX_BURST_LEN (TX_QUEUE_LEN-4) #define MAX_PKT_SIZE 1650 #define BACP_CHECK_STAGE 29 extern uint8 defMacAddr[]; extern struct net_device *mt7510PtmDev[]; extern int mt7510_ptm_tx(struct sk_buff *skb, struct net_device *dev); extern void dump_data(char *p, int len); #ifdef PTM_DEBUG extern int ptmDbgLevel; #endif #ifdef TCSUPPORT_BONDING extern unsigned int pcieVirBaseAddr; #endif static int loopbackPoint = 0; static int testType = -1, nPackets = 0; static int dataPathRxPkts = 0; static uint8 qdmaDmaAvailable = 0; static uint8 qdmaWaitingCnt = 0; static int testPktCnt = 0; static int curTxq; static int wrrQueuePhase, wrrQueueStart; static uint8 txqWrrVal[TX_QUEUE_NUM] = {1,2,3,4,5,6,7,8}; static uint32 txqWrrTotalVal; static int totalTxPkts; static int rxPreemptionPkts; atomic_t isTxHold = ATOMIC_INIT(0); static int bacpCheckStage = 0; static int isAllTestsOnGoing = 0; static int minPktSize = 60, maxPktSize = 1514; static int startPath = 0, endPath = PATH_NUM; static int isCrcCheckTest = 0; static int isWrrFirstTest[PATH_NUM] = {1,1,1,1,1,1,1,1}; uint8 dstMacAddr[] = {0x00, 0xaa, 0xbb, 0x5a, 0x5a, 0x5a}; unsigned int bacpHeader[] = {0x0180c200, 0x00028809, 0x0a0019a7, 0x01010000}; int stopTesting = 0; int ptmPathId = 0, isPtmPathIdSetEnable = 0; static int ptm_pathId_write_proc( struct file *file, const char *buffer, unsigned long count, void *data ) { char valString[8]; if (count > sizeof(valString) - 1) return -EINVAL; if (copy_from_user(valString, buffer, count)) return -EFAULT; valString[count] = '\0'; sscanf(valString, "%d %d", &isPtmPathIdSetEnable, &ptmPathId); if (isPtmPathIdSetEnable == 1) printk("\nPTM PATH ID: %d\n\n", ptmPathId); else printk("\nPathIdSet disabled!\n\n"); return count; } /* "echo M N > /proc/tc3162/ptm_loopback_pathRangeSet" * to allow only (M) ~ (N-1) channel packets can be * sent. */ static int ptm_loopbackPathRangeSet_write_proc( struct file *file, const char *buffer, unsigned long count, void *data ) { char valString[32]; int value1, value2; if (count > sizeof(valString) - 1) return -EINVAL; if (copy_from_user(valString, buffer, count)) return -EFAULT; valString[count] = '\0'; sscanf(valString, "%d %d", &value1, &value2); if (value1 > value2) printk("\nWrong: the first value: %d should be smaller than the second value:%d\n", value1, value2); else { startPath = value1; endPath = value2; printk("\npath range is %d~%d\n", startPath, endPath-1); } return count; } /* Fix packet szie between minPktSize ~ maxPktSize */ static int ptm_loopbackSetPktSize_write_proc( struct file *file, const char *buffer, unsigned long count, void *data ) { char valString[32]; int value1, value2; if (count > sizeof(valString) - 1) return -EINVAL; if (copy_from_user(valString, buffer, count)) return -EFAULT; valString[count] = '\0'; sscanf(valString, "%d %d", &value1, &value2); if (value1 > value2) printk("\nWrong: the first value: %d should be smaller than the second value:%d\n", value1, value2); else if ((value1 < 60) || (value2 > 1514)) printk("\nWrong: The correct packet size should be 60~1514\n"); else { minPktSize = value1; maxPktSize = value2; printk("\nminPktSize: %d\nmaxPktSize: %d\n", minPktSize, maxPktSize); } return count; } /* Decide what is going to be filled in Tx Message * by Byte18~19 of packet's content, * which are test-type dependent */ int loopback_tx_xmit_prepare( struct sk_buff *skb, int *line, uint8 *bearer, int *preemption, int *txq, int *needHwVlanTag, uint32 *vlanTag, uint8 *ipCsIns ) { uint8 *txData; uint16 ethType; txData = skb->data; ethType = *(uint16*)(&txData[12]); if (ethType == ETHER_TYPE_IP) { switch (txData[18]) //test type { case SINGLE_PKT_TESTTYPE: case VLAN_UNTAG_TESTTYPE: case VLAN_DBL_TAG_TESTTYPE: case VLAN_DBL_UNTAG_TESTTYPE: case IPCS_CHECK_TESTTYPE: case BACP_PKT_TESTTYPE: case RUNT_PKT_TESTTYPE: case LONG_PKT_TESTTYPE: case CRCERR_PKT_TESTTYPE: break; case PATH_NO_TESTTYPE: case DATA_PATH_TESTTYPE: case DATA_BURST_TESTTYPE: case MULTI_CHANNEL_TESTTYPE: case PREEMPTION_TESTTYPE: case SP_PRIORITY_TESTTYPE: case WRR_PRIORITY_TESTTYPE: case SP_WRR_TESTTYPE: *txq = (txData[19] >> 4) & 0xf; *needHwVlanTag = 0; break; case VLAN_TAG_TESTTYPE: if ((txData[19]>>4) & 0x1) { *needHwVlanTag = 1; *vlanTag = (ETHER_TYPE_8021Q << 16) | ((*((uint16*)(&txData[20]))) & 0x1fff); } break; case IPCS_INSERT_TESTTYPE: if ((txData[19]>>4)&0x1) *ipCsIns = 1; break; default: printk("\nWrong loopback test type:%d " "for ETHER_TYPE_IP\n", txData[18]); return -1; } } else if (ethType == ETHER_TYPE_8021Q) { txData += 4; switch (txData[18]) { case VLAN_UNTAG_TESTTYPE: *needHwVlanTag = 0; break; case VLAN_DBL_TAG_TESTTYPE: *needHwVlanTag = 1; if (((txData[19]>>4)&0x3) == 1) *vlanTag = (ETHER_TYPE_8021AD << 16) | ((*((uint16*)(&txData[20]))) & 0x1fff); else if (((txData[19]>>4)&0x3) == 3) *vlanTag = (ETHER_TYPE_QINQ << 16) | ((*((uint16*)(&txData[20]))) & 0x1fff); break; default: printk("\nWrong loopback test type:%d " "for ETHER_TYPE_8021Q\n", txData[18]); return -1; } } else if ((ethType == ETHER_TYPE_8021AD) || (ethType == ETHER_TYPE_QINQ)) { txData += 8; *needHwVlanTag = 0; } else if (ethType == ETHER_TYPE_SLOW) { txData += 10; } else { printk("\nWrong ethType:%04x loopback packet, drop it!\n", ethType); return -1; } *line = (txData[19] >> PATH_LINE_SHIFT) & 0x1; *bearer = (txData[19] >> PATH_BEARER_SHIFT) & 0x1; *preemption =(txData[19] >> PATH_PREEMPT_SHIFT) & 0x1; return 0; } #ifdef EXTERNAL_LOOPBACK /* exchange packet's src & dst MAC address * and then send it back to DSLM */ int ptm_externalLoopbackRx( ptmRxMsg_t *curRxMsg, ptmAdapter_t *ptmApt, struct sk_buff *skb, struct sk_buff **skbPtr, struct net_device *dev, uint frameSize ) { uint8 *skbData; uint8 macAddr[6]; uint32 offset; skbData = (uint8*) skb->data; if (skbData[0] == defMacAddr[0] && skbData[1] == defMacAddr[1] && skbData[2] == defMacAddr[2] && skbData[3] == defMacAddr[3] && skbData[4] == defMacAddr[4] && skbData[5] == defMacAddr[5] && skbData[6] == 0x00 && skbData[7] == 0xAA && skbData[8] == 0xBB && skbData[9] == 0x22 && skbData[10] == 0x22 && skbData[11] == 0x22) { if ((curRxMsg->rxMsgW0.word & PTM_RX_W0_ERR_BITS) /*|| (curRxMsg->rxMsgW1.word & PTM_RX_W1_ERR_BITS)*/ ) { *skbPtr = skb; return 1; } memcpy(macAddr, &skbData[0], 6); memcpy(&skbData[0], &skbData[6], 6); memcpy(&skbData[6], macAddr, 6); skb->len = frameSize; *skbPtr = skbmgr_dev_alloc_skb2k(); if (*skbPtr) { //shift to 4-byte alignment offset = ((uint32)((*skbPtr)->tail)) & 0x3; if (offset) skb_reserve(*skbPtr, 4 - offset); mt7510_ptm_tx(skb, dev); return 0; } else { printk("\nFAILED: alloc skb for external loopback\n"); *skbPtr = skb; return 1; } } else //drop packets that aren't for external loopback { *skbPtr = skb; return 1; } } #endif static void bacpHeader_write(unsigned int h0, unsigned int h1, unsigned int h2, unsigned int h3) { bacpHeader[0] = h0; bacpHeader[1] = h1; bacpHeader[2] = h2; bacpHeader[3] = h3; } static void bacpReg_write(unsigned int r0, unsigned int r1, unsigned int r2, unsigned int r3, unsigned int r4) { write_reg_word(PTM_BACP_FIELD_0, r0); write_reg_word(PTM_BACP_FIELD_1, r1); write_reg_word(PTM_BACP_FIELD_2, r2); write_reg_word(PTM_BACP_FIELD_3, r3); write_reg_word(PTM_BACP_FIELD_EN, r4); } static void bacpHeader_read(void) { PTM_DBG(DBG_L1, "\nbacpHeader[0]:0x%.8x\n" "bacpHeader[1]:0x%.8x\n" "bacpHeader[2]:0x%.8x\n" "bacpHeader[3]:0x%.8x\n\n", bacpHeader[0], bacpHeader[1], bacpHeader[2], bacpHeader[3]); } static void bacpReg_read(void) { PTM_DBG(DBG_L1, "\nbacpReg0:0x%.8x\n" "bacpReg1:0x%.8x\n" "bacpReg2:0x%.8x\n" "bacpReg3:0x%.8x\n" "bacpRegEn:0x%.8x\n\n", (unsigned int)read_reg_word(PTM_BACP_FIELD_0), (unsigned int)read_reg_word(PTM_BACP_FIELD_1), (unsigned int)read_reg_word(PTM_BACP_FIELD_2), (unsigned int)read_reg_word(PTM_BACP_FIELD_3), (unsigned int) read_reg_word(PTM_BACP_FIELD_EN)); } static int ptm_loopbackBacpHdrSet_write_proc( struct file *file, const char *buffer, unsigned long count, void *data ) { char valString[64]; if (count > sizeof(valString) - 1) return -EINVAL; if (copy_from_user(valString, buffer, count)) return -EFAULT; valString[count] = '\0'; sscanf(valString, "%x %x %x %x", &bacpHeader[0], &bacpHeader[1], &bacpHeader[2], &bacpHeader[3]); return count; } static int ptm_loopbackBacpRegSet_write_proc( struct file *file, const char *buffer, unsigned long count, void *data ) { char valString[64]; unsigned int bacpReg[5]; if (count > sizeof(valString) - 1) return -EINVAL; if (copy_from_user(valString, buffer, count)) return -EFAULT; valString[count] = '\0'; sscanf(valString, "%x %x %x %x %x", &bacpReg[0], &bacpReg[1], &bacpReg[2], &bacpReg[3], &bacpReg[4]); bacpReg_write(bacpReg[0], bacpReg[1], bacpReg[2], bacpReg[3], bacpReg[4]); bacpCheckStage = 88; return count; } static int ptm_loopbackStopTest_write_proc( struct file *file, const char *buffer, unsigned long count, void *data ) { char valString[4]; if (count > sizeof(valString) - 1) return -EINVAL; if (copy_from_user(valString, buffer, count)) return -EFAULT; valString[count] = '\0'; sscanf(valString, "%d", &stopTesting); return count; } void ptmTcLoopbackPoint_set(void) { #ifndef TCSUPPORT_BONDING uint32 reg; #endif //set for PTM-TC loopback for line0 write_reg_word(0xbf900030, 2); #ifdef TCSUPPORT_BONDING //set for PTM-TC loopback for line1 write_reg_word(pcieVirBaseAddr+0x900030, 2); #else //no dummy R/W for dmt reg = read_reg_word(TPSTC_RX_CFG); reg |= TPSTC_REDUNDANT_MODE; write_reg_word(TPSTC_RX_CFG, reg); #endif printk("\nSetting for loopback at PTM-TC\n"); printk("\nReminder: rmmod dmt.ko when doing loopback!\n\n"); return; } /* "echo N > /proc/tc3162/ptm_loopback_point" * to set loopback point: * when N=1, loopback at QDMA, * when N=2: loopback at GDM (U-MAC), * when N=3: loopback at PTM-TC */ static int ptm_loopbackPoint_write_proc( struct file *file, const char *buffer, unsigned long count, void *data ) { char valString[4]; uint32 reg; if (count > sizeof(valString) - 1) return -EINVAL; if (copy_from_user(valString, buffer, count)) return -EFAULT; valString[count] = '\0'; sscanf(valString, "%d", &loopbackPoint); switch (loopbackPoint) { case 1: //QDMA loopback qdma_loopback_mode(QDMA_LOOPBACK_QDMA); printk("\nloopback at QDMA\n\n"); break; case 2: //GDM (Upper MAC) loopback qdma_loopback_mode(QDMA_LOOPBACK_UMAC); /* disable CRC stripping in GDM, * otherwise RX packet size will be lack of 4 */ reg = fe_reg_read(GDM2_FWD_CFG_OFF); reg &= ~(1<<16); fe_reg_write(GDM2_FWD_CFG_OFF, reg); printk("\nloopback at GDM (U-MAC)\n\n"); break; case 3: ptmTcLoopbackPoint_set(); break; default: printk("\nUsage: echo N > /proc/tc3162/ptm_loopback_point, where:\n" "N==1: loopback at QDMA\n" "N==2: loopback at GDM (U-MAC)\n" "N==3: loopback at PTM-TC\n\n"); break; } return count; } static int ptm_loopback_registersCheck(int tryCnt) { unsigned int reg = PTM_REG_BASE; int i, j; printk("\nStart checking PTM MAC registers for %d times\n", tryCnt); for (j = 0; j < tryCnt; j++) { if ((read_reg_word(reg) & 0x3) != 0x0) { printk("\nWrong default value for 0x%08x:\n" "read_reg_word(reg):0x%08lx\n" "Expected default value: 0x0\n", reg, read_reg_word(reg)); return -1; } //after nas8/nas9 up, PTM_CTRL_REG has become 0x02010101 if (read_reg_word(PTM_CTRL_REG) != 0x02010101) { printk("\nWrong default value for PTM_CTRL_REG(0x%08x):\n" "read_reg_word(PTM_CTRL_REG):0x%08lx\n" "Expected default value: 0x02010101\n", PTM_CTRL_REG, read_reg_word(PTM_CTRL_REG)); return -1; } reg = 0xbfb62010; for (i = 0; i < 5; i++) { if (read_reg_word(reg+(i<<2)) != 0x0) { printk("\nWrong default value for 0x%08x:\n" "read_reg_word(reg):0x%08lx\n" "Expected default value: 0x0\n", reg+(i<<2), read_reg_word(reg+(i<<2))); return -1; } } reg = 0xbfb62080; for (i = 0; i < 7; i++) { if (read_reg_word(reg+(i<<2)) != 0x0) { printk("\nWrong default value for 0x%08x:\n" "read_reg_word(reg):0x%08lx\n" "Expected default value: 0x0\n", reg+(i<<2), read_reg_word(reg+(i<<2))); return -1; } } reg = 0xbfb62100; for (i = 0; i < 9; i++) { if (read_reg_word(reg+(i<<2)) != 0x0) { printk("\nWrong default value for 0x%08x:\n" "read_reg_word(reg):0x%08lx\n" "Expected default value: 0x0\n", reg+(i<<2), read_reg_word(reg+(i<<2))); return -1; } } reg = 0xbfb62130; for (i = 0; i < 9; i++) { if (read_reg_word(reg+(i<<2)) != 0x0) { printk("\nWrong default value for 0x%08x:\n" "read_reg_word(reg):0x%08lx\n" "Expected default value: 0x0\n", reg+(i<<2), read_reg_word(reg+(i<<2))); return -1; } } reg = 0xbfb62160; for (i = 0; i < 9; i++) { if (read_reg_word(reg+(i<<2)) != 0x0) { printk("\nWrong default value for 0x%08x:\n" "read_reg_word(reg):0x%08lx\n" "Expected default value: 0x0\n", reg+(i<<2), read_reg_word(reg+(i<<2))); return -1; } } reg = 0xbfb62190; for (i = 0; i < 9; i++) { if (read_reg_word(reg+(i<<2)) != 0x0) { printk("\nWrong default value for 0x%08x:\n" "read_reg_word(reg):0x%08lx\n" "Expected default value: 0x0\n", reg+(i<<2), read_reg_word(reg+(i<<2))); return -1; } } reg = 0xbfb621c0; for (i = 0; i < 9; i++) { if (read_reg_word(reg+(i<<2)) != 0x0) { printk("\nWrong default value for 0x%08x:\n" "read_reg_word(reg):0x%08lx\n" "Expected default value: 0x0\n", reg+(i<<2), read_reg_word(reg+(i<<2))); return -1; } } /* 0xbfb621e4~e8 are probe signal registers, don't care.*/ } printk("\nregisters check OK for %d times\n", tryCnt); return 0; } static unsigned short in_csum(unsigned short *ptr, int nbytes) { register int sum; /* assumes long == 32 bits */ unsigned short oddbyte; register unsigned short answer; /* assumes u_short == 16 bits */ /* * Our algorithm is simple, using a 32-bit accumulator (sum), * we add sequential 16-bit words to it, and at the end, fold back * all the carry bits from the top 16 bits into the lower 16 bits. */ sum = 0; while (nbytes > 1) { sum += *ptr++; nbytes -= 2; } /* mop up an odd byte, if necessary */ if (nbytes == 1) { oddbyte = 0; /* make sure top half is zero */ *((unsigned char *) &oddbyte) = *(unsigned char *)ptr; /* one byte only */ sum += oddbyte; } /* * Add back carry outs from top 16 bits to low 16 bits. */ sum = (sum >> 16) + (sum & 0xffff); /* add high-16 to low-16 */ sum += (sum >> 16); /* add carry */ answer = ~sum; /* ones-complement, then truncate to 16 bits */ return(answer); } /* * Content format: * -> Byte0~13: Dest MAC Addr, Src MAC Addr, Ethernet Type * -> Byte14[bit0~3]: packet payload type which will decide * the content after 20th byte. * -> Byte14[bit4~7]: IP version. * -> Byte15: base value for content after 20th byte. * -> Byte16~17: packet length. * -> Byte18: test type. * -> Byte19: test-type dependent value. * -> Byte20~ : packet payload. */ static int txCommonContent_fill( struct sk_buff **pSkb, uint8 **pTxData, int pkt, int type, uint16 etherType, int offset, uint32 pktLen ) { uint32 k, txLen, tagId = 0; uint8 baseVal; uint8 *txData; struct sk_buff *skb; int pktType = type & 0xf; uint8 *dstMacPtr = NULL; uint8 *bacpHdr = NULL; skb = dev_alloc_skb(RX_BUF_LEN); if (skb == NULL) { printk("\nFAILED: skb allocation:\n"); return -1; } //when 0, pkt len is decided by packet payload type if (!pktLen) { if (pktType == RAN_PKTTYPE) txLen = random32(); else txLen = pkt; //txLen is 60~1514 by default.(CRC not included) if ( (txLen < minPktSize) || (txLen > maxPktSize) ) { txLen %= (maxPktSize - minPktSize + 1); txLen += minPktSize; } } else txLen = pktLen; txData = skb_put(skb, txLen); /* destination mac should be changed, because * BACP has it own destination mac */ if ((etherType == ETHER_TYPE_SLOW) && (pkt & 1)) dstMacPtr = (uint8 *)&bacpHeader[0]; else dstMacPtr = &dstMacAddr[0]; //destination mac for (k = 0; k < 6; k++) txData[k] = dstMacPtr[k]; //source mac for (k = 6; k < 12; k++) txData[k] = defMacAddr[k-6]; /* byte12~13 are for ethernet type, but in VLAN * & BACP test cases, the rule may be chanegd. */ *((uint16*)(&txData[12])) = etherType; //for VLAN_UNTAG_TESTTYPE if (etherType == ETHER_TYPE_8021Q) { if (pkt & 1) //vlan packets { tagId = random32() & 0x1fff; //13-bit tagId *((uint16*)(&txData[14])) = tagId; *((uint16*)(&txData[16])) = ETHER_TYPE_IP; txData += 4; //shift 4 bytes txLen -= 4; *((uint16*)(&txData[20])) = tagId; } else //normal packets *((uint16*)(&txData[12])) = ETHER_TYPE_IP; } //for VLAN_DBL_TAG_TESTTYPE else if (etherType == ETHER_TYPE_8021AD) { if (((pkt & 3) == 1) || ((pkt & 3) == 3)) { *((uint16*)(&txData[12])) = ETHER_TYPE_8021Q; if ((pkt & 3) == 1) *((uint16*)(&txData[14])) = 0x1234; else *((uint16*)(&txData[14])) = 0x1567; *((uint16*)(&txData[16])) = ETHER_TYPE_IP; txData += 4; //shift 4 bytes txLen -= 4; *((uint16*)(&txData[20])) = (uint16) (random32() & 0x1fff); } else *((uint16*)(&txData[12])) = ETHER_TYPE_IP; } //for VLAN_DBL_UNTAG_TESTTYPE else if (etherType == ETHER_TYPE_QINQ) { if (((pkt & 3) == 1) || ((pkt & 3) == 3)) { if ((pkt & 3) == 1) *((uint16*)(&txData[12])) = ETHER_TYPE_8021AD; tagId = random32() & 0x1fff; //13-bit tagId *((uint16*)(&txData[14])) = tagId; *((uint16*)(&txData[16])) = ETHER_TYPE_8021Q; if ((pkt & 3) == 1) *((uint16*)(&txData[18])) = 0x189a; else *((uint16*)(&txData[18])) = 0x1bcd; *((uint16*)(&txData[20])) = ETHER_TYPE_IP; txData += 8; //shift 8 bytes txLen -= 8; *((uint16*)(&txData[20])) = tagId; } else *((uint16*)(&txData[12])) = ETHER_TYPE_IP; } //for BACP_PKT_TESTTYPE else if (etherType == ETHER_TYPE_SLOW) { if (pkt & 1) //bacp packets { bacpHdr = (uint8 *)&bacpHeader[2]; txData[14] = bacpHdr[0]; //subtype txData[15] = bacpHdr[1]; //ITU OUI txData[16] = bacpHdr[2]; txData[17] = bacpHdr[3]; txData[18] = bacpHdr[4]; //ITU subtype txData[19] = bacpHdr[5]; //BACP version *((uint32*)(&txData[20])) = 0x0; //BACP timestamp txData += 10; //shift 10 bytes txLen -= 10; } else //normanl packets *((uint16*)(&txData[12])) = ETHER_TYPE_IP; } //ip version4 & pkt payload type txData[14] = ((4 << 4) | pktType); //base value for payload switch (pktType) { case INC_PKTTYPE: baseVal = (uint8) (pkt & 0xff); break; case RAN_PKTTYPE: baseVal = (uint8) (random32() & 0xff); break; case ZERO_PKTTYPE: baseVal = 0; break; case FF_PKTTYPE: baseVal = 0xff; break; case FA_PKTTYPE: baseVal = 0x5a; break; case AF_PKTTYPE: baseVal = 0xa5; break; default: printk("\nWrong PKT pattern:\n" "type:%d, pkt:%d\n", pktType, pkt); return -1; } txData[15] = baseVal; //packet length *((uint16*)(&txData[16])) = (uint16) (txLen & 0xffff); /* Fill packet payload: * If payload type is INC or RAN, payload value will * be incremental starting from baseVal, otherwise * payload is baseVal. * Packet payload is starting from byte20, except * VLAN tests. */ for (k = offset; k < txLen; k++) { txData[k] = baseVal; if (pktType == INC_PKTTYPE || pktType == RAN_PKTTYPE) { if (baseVal == 0xff) baseVal = 0; else baseVal++; } } *pSkb = skb; *pTxData = txData; return 0; } /* After sending a packet, wait until the packet * is received by loopback Rx, before a new * packet can be sent */ struct task_struct *txProcess = NULL; static void loopback_pkt_transmit( struct sk_buff *skb, uint8 bearer ) { atomic_set(&isTxHold, 1); txProcess = NULL; mt7510_ptm_tx(skb, mt7510PtmDev[bearer]); while (atomic_read(&isTxHold)) { #if 0 set_current_state(TASK_INTERRUPTIBLE); schedule_timeout(1); //jiffies set_current_state(TASK_RUNNING); #endif #if 1 txProcess = current; if (atomic_read(&isTxHold)) schedule(); #endif } } static void rxWakeUpTx(void) { atomic_set(&isTxHold, 0); if (txProcess) wake_up_process(txProcess); } /* for debug only, not included in real tests */ static int ptm_loopback_singlePkt_tx(uint32 pktLen) { struct sk_buff *skb = NULL; uint8 *txData = NULL; int offset = 20; printk("\nStart %s test\n", __FUNCTION__); if (txCommonContent_fill(&skb, &txData, 0, RAN_PKTTYPE, ETHER_TYPE_IP, offset, pktLen)) return -1; txData[18] = SINGLE_PKT_TESTTYPE; //single packet test type txData[19] = 0; //not used if (!stopTesting) { mt7510_ptm_tx(skb, mt7510PtmDev[PTM_BEARER_0]); } else { printk("\nStop Testing (single packet):\n"); return -1; } printk("\nSinglePkt TX OK with pktLen:%d\n", (int)pktLen); return 0; } static int dataPath_tx( int path, int txq, int type, int pkt ) { struct sk_buff *skb = NULL; uint8 *txData = NULL; uint8 bearer = 0; int offset = 20; if (txCommonContent_fill(&skb, &txData, pkt, type, ETHER_TYPE_IP, offset, 0)) return -1; txData[18] =DATA_PATH_TESTTYPE ; //data path test type txData[19] = (path & 0xf) | ((txq & 0xf) << 4); //path & txq if (!stopTesting) { totalTxPkts++; bearer = (path >> PATH_BEARER_SHIFT) & 0x1; if ((totalTxPkts & 0xffff) != 0xffff) { PTM_DBG(DBG_L1, "%s: path:%d, txq:%d, type:%d, pkt:%d\n", __FUNCTION__, path, txq, type, pkt); } else printk("%s: path:%d, txq:%d, type:%d, pkt:%d\n", __FUNCTION__, path, txq, type, pkt); loopback_pkt_transmit(skb, bearer); } else { printk("\nStop Testing (data path):\n" "path:%d, txq:%d, type:%d, pkt:%d, totalTxPkts:%d\n", path, txq, type, pkt, totalTxPkts); return -1; } return 0; } /* send a packet, wait until the packet is received * before next packet can be sent */ static int ptm_loopback_dataPath_tx(uint32 pktNum) { int nPkts, loop = 0; int pkt, type = 0, path = 0, txq = 0; printk("\nStart %s test\n", __FUNCTION__); if (pktNum == 0) { nPkts = 1500; if (!isAllTestsOnGoing) loop = 1; } else nPkts = pktNum; data_path_loop: for (path = startPath; path < endPath; path++) { for (txq = 0; txq < TX_QUEUE_NUM; txq++) { for (type = 0; type < PKT_PATTERN_NUM; type++) { for (pkt = 0; pkt < nPkts; pkt++) { if (dataPath_tx(path, txq, type, pkt)) return -1; } } } } if (loop) { printk("\nData Path TX Loop %d OK\n", loop); loop++; goto data_path_loop; } printk("\nData Path TX OK with %d pkts!\n", totalTxPkts); return 0; } static int dataBurst_tx( int path, int txq, int type, int pkt ) { struct sk_buff *skb = NULL; uint8 *txData = NULL; uint8 bearer = 0; int offset = 20; if (txCommonContent_fill(&skb, &txData, pkt, type, ETHER_TYPE_IP, offset, 0)) return -1; txData[18] =DATA_BURST_TESTTYPE ; //data burst test type txData[19] = (path & 0xf) | ((txq & 0xf) << 4); //path & txq totalTxPkts++; bearer = (path >> PATH_BEARER_SHIFT) & 0x1; PTM_DBG(DBG_L1, "%s: path:%d, txq:%d, pkt:%d\n", __FUNCTION__, path, txq, pkt); mt7510_ptm_tx(skb, mt7510PtmDev[bearer]); return 0; } /* For each path test: * 1. hold QDMA * 2. send (TX_QUEUE_NUM*TX_BURST_LEN) packets to PSE buffer * 3. turn on QDMA * 4. wait until all loopback packets are receved */ static int ptm_loopback_dataBurst_tx(uint32 pktNum) { int loop = 0; int pkt, path = 0, txq = 0; printk("\nStart %s test\n", __FUNCTION__); if (pktNum == 0) if (!isAllTestsOnGoing) loop = 1; data_burst_loop: /* The number of PTM RX messages should be as many as * (TX_QUEUE_NUM*TX_QUEUE_LEN), otherwise QDMA may * be out of RX descriptors when receiving RX packets, * because the process of receiving a packet is slow! */ for (path = startPath; path < endPath; path++) { qdma_dma_mode(QDMA_DISABLE, QDMA_DISABLE, QDMA_DISABLE); for (txq = 0; txq < TX_QUEUE_NUM; txq++) { for (pkt = 0; pkt < TX_BURST_LEN; pkt++) { if (dataBurst_tx(path, txq, RAN_PKTTYPE, pkt)) return -1; } } testPktCnt = 1; //init testPktCnt dataPathRxPkts = 0; qdmaDmaAvailable = 0; qdmaWaitingCnt = 0; qdma_dma_mode(QDMA_ENABLE, QDMA_ENABLE, QDMA_DISABLE); //noHwFwd while (!qdmaDmaAvailable) { if (++qdmaWaitingCnt == 3) { printk("\nWaiting for too long! (%d pkts sent, %d pkts received)\n", totalTxPkts, dataPathRxPkts); return -1; } msleep(LOOP_SLEEP_TIME); } if (stopTesting) { printk("\nStop Testing (data burst):\n" "path:%d, totalTxPkts:%d\n", path, totalTxPkts); return -1; } } if (loop) { printk("\nData Burst TX Loop %d OK\n", loop); loop++; goto data_burst_loop; } printk("\nData Burst TX OK with %d pkts!\n", totalTxPkts); return 0; } static int multiChannel_tx( int path, int txq, int type, int pkt ) { struct sk_buff *skb = NULL; uint8 *txData = NULL; uint8 bearer = 0; int offset = 20; if (txCommonContent_fill(&skb, &txData, pkt, type, ETHER_TYPE_IP, offset, 0)) return -1; txData[18] = MULTI_CHANNEL_TESTTYPE; //multi channel test type txData[19] = (path & 0xf) | ((txq & 0xf) << 4); //path & txq totalTxPkts++; bearer = (path >> PATH_BEARER_SHIFT) & 0x1; PTM_DBG(DBG_L1, "%s: path:%d, txq:%d, pkt:%d\n", __FUNCTION__, path, txq, pkt); mt7510_ptm_tx(skb, mt7510PtmDev[bearer]); return 0; } /* For every 2 paths, do the following for 1500 times: * 1. hold QDMA * 2. send a packet for path(N) and another packet * for path(N+1) to PSE buffer * 3. turn on QDMA * 4. wait until the 2 loopback packets are receved */ static int ptm_loopback_multiChannel_tx(uint32 pktNum) { int loop = 0; int pkt, path = 0, txq = 0, path2 = 0; printk("\nStart %s test\n", __FUNCTION__); if (pktNum == 0) if (!isAllTestsOnGoing) loop = 1; multi_channel_loop: for (path = startPath; path < endPath; path++) { for (pkt = 0; pkt < 24; pkt++) { txq = pkt & 0x7; qdma_dma_mode(QDMA_DISABLE, QDMA_DISABLE, QDMA_DISABLE); if (multiChannel_tx(path, txq, RAN_PKTTYPE, pkt)) return -1; if ((path+1) == endPath) path2 = startPath; else path2 = path+1; if (multiChannel_tx(path2, txq, RAN_PKTTYPE, pkt)) return -1; testPktCnt = 1; //init testPktCnt qdmaDmaAvailable = 0; qdmaWaitingCnt = 0; qdma_dma_mode(QDMA_ENABLE, QDMA_ENABLE, QDMA_DISABLE); //noHwFwd while (!qdmaDmaAvailable) { if (++qdmaWaitingCnt == 3) { printk("\nWaiting for too long! (%d pkts sent, %d pkts received)\n", totalTxPkts, dataPathRxPkts); return -1; } msleep(LOOP_SLEEP_TIME); } if (stopTesting) { printk("\nStop Testing (multi channel):\n" "path:%d, totalTxPkts:%d\n", path, totalTxPkts); return -1; } } } if (loop) { printk("\nMulti Channel TX Loop %d OK\n", loop); loop++; goto multi_channel_loop; } printk("\nMulti Channel TX OK with %d pkts!\n", totalTxPkts); return 0; } static int ptm_loopback_pathNo_tx(uint32 pktNum) { int nPkts, loop = 0; struct sk_buff *skb = NULL; uint8 *txData = NULL; uint8 bearer; int pkt, path; int offset = 20; printk("\nStart %s test\n", __FUNCTION__); if (pktNum == 0) { nPkts = 1500; if (!isAllTestsOnGoing) loop = 1; } else nPkts = pktNum; path_no_loop: for (pkt = 0; pkt < nPkts; pkt++) { for (path = startPath; path < endPath; path++) { if (txCommonContent_fill(&skb, &txData, pkt, RAN_PKTTYPE, ETHER_TYPE_IP, offset, 0)) return -1; txData[18] = PATH_NO_TESTTYPE; //path_no test type txData[19] = path & 0xf; //path if (!stopTesting) { totalTxPkts++; bearer = (path >> PATH_BEARER_SHIFT) & 0x1; PTM_DBG(DBG_L1, "%s: pkt:%d, path:%d\n", __FUNCTION__, pkt, path); loopback_pkt_transmit(skb, bearer); } else { printk("\nStop Testing (path_no):\n" "pkt:%d, path:%d, totalTxPkts:%d\n", pkt, path, totalTxPkts); return -1; } } } if (loop) { printk("\nPath_No TX Loop %d OK\n", loop); loop++; goto path_no_loop; } printk("\nPath_No TX OK with %d pkts!\n", totalTxPkts); return 0; } static int preemption_tx( int path, int txq, int pkt ) { struct sk_buff *skb = NULL; uint8 *txData = NULL; int offset = 20; int bearer; if (txCommonContent_fill(&skb, &txData, pkt, RAN_PKTTYPE, ETHER_TYPE_IP, offset, 1500)) return -1; txData[18] = PREEMPTION_TESTTYPE; //preemption test type txData[19] = (path & 0xf) | ((txq & 0xf) << 4); //path & txq totalTxPkts++; bearer = (path>>PATH_BEARER_SHIFT) & 0x1; PTM_DBG(DBG_L1, "%s: path:%d, txq:%d, pkt:%d\n", __FUNCTION__, path, txq, pkt); mt7510_ptm_tx(skb, mt7510PtmDev[bearer]); return 0; } /* For a normal path and a preemption path: * 1. hold QDMA * 2. send 60 packets for the normal path and 4 * packets for preemption path to PSE buffer * 3. turn on QDMA * 4. wait until the 4 preemption packets are all * receved before all 60 normal packets are * received. */ static int ptm_loopback_preemption_tx(uint32 pktNum) { int loop = 0; int pkt, txq; int path, pathNo; printk("\nStart ptm_loopback_preemption test\n"); if (pktNum == 0) if (!isAllTestsOnGoing) loop = 1; preemption_loop: /* PTM MAC can support only 2 paths to move at * the same time for 30MHz POF*/ for (txq = 0; txq < TX_QUEUE_NUM; txq++) { for (path = startPath; path < endPath; path++) { rxPreemptionPkts = 0; dataPathRxPkts = 0; PTM_DBG(DBG_L1, "\nPreemption Tx with path%d txq%d\n", path, txq); qdma_dma_mode(QDMA_DISABLE, QDMA_DISABLE, QDMA_DISABLE); /* compare normal & preemptive packets in the same line & bearer. * that is, path0 compares with path1, path2 with path3, path4 * with path5, path6 with path7. */ if (path & 1) { //normal pathNo = path - 1; for (pkt = 0; pkt < 60; pkt++) { if (preemption_tx(pathNo, txq, pkt)) return -1; } //preemption pathNo = path; for (pkt = 0; pkt < 4; pkt++) { if (preemption_tx(pathNo, txq, pkt)) return -1; } } else { //normal pathNo = path; for (pkt = 0; pkt < 60; pkt++) { if (preemption_tx(pathNo, txq, pkt)) return -1; } //preemption pathNo = path + 1; if (pathNo == endPath && startPath != (endPath-1) ) pathNo = startPath; for (pkt = 0; pkt < 4; pkt++) { if (preemption_tx(pathNo, txq, pkt)) return -1; } } qdmaDmaAvailable = 0; qdmaWaitingCnt = 0; qdma_dma_mode(QDMA_ENABLE, QDMA_ENABLE, QDMA_DISABLE); while (!qdmaDmaAvailable) { if (++qdmaWaitingCnt == 3) { printk("\nWaiting for too long! (%d pkts sent, %d normal & %d preemption pkts received)\n", totalTxPkts, dataPathRxPkts, rxPreemptionPkts); return -1; } msleep(LOOP_SLEEP_TIME); } if (stopTesting) { printk("\nStop Testing (preemption):\n" "3 paths from path%d, txq:%d, totalTxPkts:%d\n", path, txq, totalTxPkts); return -1; } } } if (loop) { printk("\nPreemption TX Loop %d OK\n", loop); loop++; goto preemption_loop; } printk("\nPreemption TX OK with %d pkts!\n", totalTxPkts); return 0; } static int spPriority_tx( int path, int txq, int pkt ) { struct sk_buff *skb = NULL; uint8 *txData = NULL; uint8 bearer; int offset = 20; if (txCommonContent_fill(&skb, &txData, pkt, RAN_PKTTYPE, ETHER_TYPE_IP, offset, 0)) return -1; txData[18] = SP_PRIORITY_TESTTYPE; //SP test type txData[19] = (path & 0xf) | ((txq & 0xf) << 4); //path & txq totalTxPkts++; bearer = (path >> (PATH_BEARER_SHIFT)) & 0x1; PTM_DBG(DBG_L1, "%s: path:%d, txq:%d, pkt:%d\n", __FUNCTION__, path, txq, pkt); mt7510_ptm_tx(skb, mt7510PtmDev[bearer]); return 0; } /* For each path test: * 1. set QDMA as Strict Priority mode * 2. enable QDMA TX buffer usage but set threshold to 0 * 3. send low priority and then high priority packets * (total (TX_QUEUE_NUM*TX_BURST_LEN) packets) to * QDMA link manager. * 4. hold QDMA. * 5. release QDMA TX buffer usage * 6. turn on QDMA * 7. wait until all loopback packets are receved * according to their priority. */ static int ptm_loopback_spPriority_tx(uint32 pktNum) { int loop = 0; int pkt, path; int txq; QDMA_TxQosScheduler_T txQos; QDMA_TxBufCtrl_T txBufUsage; printk("\nStart %s test\n", __FUNCTION__); if (pktNum == 0) if (!isAllTestsOnGoing) loop = 1; sp_priority_loop: /* The number of PTM RX messages should be as many as * (TX_QUEUE_NUM*TX_QUEUE_LEN), otherwise QDMA may * be out of RX descriptors when receiving RX packets, * because the process of receiving a packet is slow! */ for (path = startPath; path < endPath; path++) { /* set QDMA as Strip Priority Mode, * so that p7> ... >p0 for each path */ memset(&txQos, 0, sizeof(QDMA_TxQosScheduler_T)); txQos.channel = path; txQos.qosType = QDMA_TXQOS_TYPE_SP; if (qdma_set_tx_qos(&txQos)) { printk("\nERROR(%s): qdma_set_tx_qos for path%d\n", __FUNCTION__, path); return -1; } //init parameters for RX curTxq = 7; /* enable TX buffer usage but set threshold to 0, * then packets will be queued in QDMA link manager * in priority but won't be sent */ memset(&txBufUsage, 0, sizeof(QDMA_TxBufCtrl_T)); txBufUsage.mode = QDMA_ENABLE; if (qdma_set_txbuf_threshold (&txBufUsage)) { printk("\nFAILED(%s): qdma enable txBufUsage\n" , __FUNCTION__); return -1; } //low priority packets go into QDMA first! for (txq = 0; txq < TX_QUEUE_NUM; txq++) { for (pkt = 0; pkt < TX_BURST_LEN; pkt++) { if (spPriority_tx(path, txq, pkt)) return -1; } } qdma_dma_mode(QDMA_DISABLE, QDMA_DISABLE, QDMA_DISABLE); testPktCnt = 1; //initialize testPktCnt dataPathRxPkts = 0; qdmaDmaAvailable = 0; qdmaWaitingCnt = 0; //release TX buffer usage memset(&txBufUsage, 0, sizeof(QDMA_TxBufCtrl_T)); if (qdma_set_txbuf_threshold (&txBufUsage)) { printk("\nFAILED(%s): qdma disable txBufUsage\n" , __FUNCTION__); return -1; } qdma_dma_mode(QDMA_ENABLE, QDMA_ENABLE, QDMA_DISABLE); //noHwFwd while (!qdmaDmaAvailable) { if (++qdmaWaitingCnt == 3) { printk("\nWaiting for too long! (%d pkts sent, %d pkts received)\n", totalTxPkts, dataPathRxPkts); return -1; } msleep(LOOP_SLEEP_TIME); } if (stopTesting) { printk("\nStop Testing (SP priority):\n" "path:%d, totalTxPkts:%d\n", path, totalTxPkts); return -1; } } if (loop) { printk("\nSP priority TX Loop %d OK\n", loop); loop++; goto sp_priority_loop; } printk("\nSP priority TX OK with %d pkts!\n", totalTxPkts); return 0; } static int wrrPriority_tx( int path, int txq, int pkt ) { struct sk_buff *skb = NULL; uint8 *txData = NULL; uint8 bearer; int offset = 20; if (txCommonContent_fill(&skb, &txData, pkt, RAN_PKTTYPE, ETHER_TYPE_IP, offset, 0)) return -1; txData[18] = WRR_PRIORITY_TESTTYPE; //WRR test type txData[19] = (path & 0xf) | ((txq & 0xf) << 4); //path & txq totalTxPkts++; bearer = (path >> (PATH_BEARER_SHIFT)) & 0x1; PTM_DBG(DBG_L1, "%s: path:%d, txq:%d, pkt:%d, totalTxPkts:%d\n", __FUNCTION__, path, txq, pkt, totalTxPkts); mt7510_ptm_tx(skb, mt7510PtmDev[bearer]); return 0; } /* For each path test: * 1. set QDMA as Weighted Round Robin mode * 2. send a packet for every queue of the path. * 2. enable QDMA TX buffer usage but set threshold to 0 * 3. send multiple of txqWrrVal[txqN] packets for txqN * to QDMA link manager. * 4. hold QDMA. * 5. release QDMA TX buffer usage * 6. turn on QDMA * 7. wait until all loopback packets are receved * according to their priority. */ static int ptm_loopback_wrrPriority_tx(uint32 pktNum) { int loop = 0; int pkt, path; int txq, i; QDMA_TxQosScheduler_T txQos; QDMA_TxBufCtrl_T txBufUsage; printk("\nStart %s test\n", __FUNCTION__); if (pktNum == 0) if (!isAllTestsOnGoing) loop = 1; txqWrrTotalVal = 0; for (i = 0; i < TX_QUEUE_NUM; i++) txqWrrTotalVal += txqWrrVal[i]; wrr_priority_loop: for (path = startPath; path < endPath; path++) { /* set QDMA's WRR priority registers, * so that p7: ... :p0 == 8: ... :1 */ memset(&txQos, 0, sizeof(QDMA_TxQosScheduler_T)); txQos.channel = path; txQos.qosType = QDMA_TXQOS_TYPE_WRR; for(i = 0 ; i < TX_QUEUE_NUM ; i++) txQos.queue[i].weight = txqWrrVal[i]; if (qdma_set_tx_qos(&txQos)) { printk("\nERROR(%s): qdma_set_tx_qos for path%d\n" , __FUNCTION__, path); return -1; } else //success { memset(&txQos, 0, sizeof(QDMA_TxQosScheduler_T)); txQos.channel = path; qdma_get_tx_qos(&txQos) ; printk("\nWRR setting OK for Path:%d, Type:%d\n" "Q0:%d, Q1:%d, Q2:%d, Q3:%d, Q4:%d, Q5:%d, Q6:%d, Q7:%d\n\n", path, txQos.qosType, txQos.queue[0].weight, txQos.queue[1].weight, txQos.queue[2].weight, txQos.queue[3].weight, txQos.queue[4].weight, txQos.queue[5].weight, txQos.queue[6].weight, txQos.queue[7].weight); } /* Due to HW's design, HW WRR counters won't be accurate * until every queue (per path) sends a packet */ if (isWrrFirstTest[path]) { qdma_dma_mode(QDMA_DISABLE, QDMA_DISABLE, QDMA_DISABLE); for (txq = 0; txq < TX_QUEUE_NUM; txq++) { if (wrrPriority_tx(path, txq, 0)) return -1; } dataPathRxPkts = 0; qdmaDmaAvailable = 0; qdmaWaitingCnt = 0; qdma_dma_mode(QDMA_ENABLE, QDMA_ENABLE, QDMA_DISABLE); //noHwFwd while (!qdmaDmaAvailable) { if (++qdmaWaitingCnt == 3) { printk("\nWaiting for too long for WRR dirst test for path%d\n", path); return -1; } msleep(LOOP_SLEEP_TIME); } isWrrFirstTest[path] = 0; } /* begin real WRR test */ /* enable TX buffer usage and set threshold to 0, * then packets will be queued in QDMA link manager * in priority but won't be sent */ memset(&txBufUsage, 0, sizeof(QDMA_TxBufCtrl_T)); txBufUsage.mode = QDMA_ENABLE; if (qdma_set_txbuf_threshold (&txBufUsage)) { printk("\nFAILED(%s): qdma enable txBufUsage\n" , __FUNCTION__); return -1; } /* due to HW's design, put multiple txqWrrVal[txqN] * packets for txqN ! So we put 8, 16, 24, 32 * 40, 48, 56, 64 packets in txq0, 1, 2 ,3, 4, * 5, 6, 7 respectively */ for (txq = 0; txq < TX_QUEUE_NUM; txq++) { for (pkt = 0; pkt < (txqWrrVal[txq]<<3); pkt++) { if (wrrPriority_tx(path, txq, pkt)) return -1; } } qdma_dma_mode(QDMA_DISABLE, QDMA_DISABLE, QDMA_DISABLE); //init paremeters wrrQueuePhase = 0; wrrQueueStart = 0; qdmaDmaAvailable = 0; qdmaWaitingCnt = 0; dataPathRxPkts = 0; //release TX buffer usage memset(&txBufUsage, 0, sizeof(QDMA_TxBufCtrl_T)); if (qdma_set_txbuf_threshold (&txBufUsage)) { printk("\nFAILED(%s): qdma disable txBufUsage\n" , __FUNCTION__); return -1; } qdma_dma_mode(QDMA_ENABLE, QDMA_ENABLE, QDMA_DISABLE); //noHwFwd while (!qdmaDmaAvailable) { if (++qdmaWaitingCnt == 3) { printk("\nWaiting for too long! (%d pkts sent, %d pkts received)\n", totalTxPkts, dataPathRxPkts); return -1; } msleep(LOOP_SLEEP_TIME); } if (stopTesting) { printk("\nStop Testing (WRR priority):\n" "path:%d, totalTxPkts:%d\n", path, totalTxPkts); return -1; } } /* WRR counters will be reset * when not looping in the same Path. */ if (endPath > startPath+1) { for (path = startPath; path < endPath; path++) isWrrFirstTest[path] = 1; } if (loop) { printk("\nWRR priority TX Loop %d OK\n", loop); loop++; goto wrr_priority_loop; } printk("\nWRR priority TX OK with %d pkts!\n", totalTxPkts); /* set QDMA QOS registers back to default values * which is QDMA_TXQOS_TYPE_SP */ for (i = startPath; i < endPath; i++) { memset(&txQos, 0, sizeof(QDMA_TxQosScheduler_T)); txQos.channel = i; txQos.qosType = QDMA_TXQOS_TYPE_SP; if (qdma_set_tx_qos(&txQos)) { printk("\nERROR(%s): qdma_set_tx_qos for path%d\n", __FUNCTION__,i); return -1; } } return 0; } static int spWrr_tx( int path, int txq, int pkt ) { struct sk_buff *skb = NULL; uint8 *txData = NULL; uint8 bearer; int offset = 20; if (txCommonContent_fill(&skb, &txData, pkt, RAN_PKTTYPE, ETHER_TYPE_IP, offset, 0)) return -1; txData[18] = SP_WRR_TESTTYPE; //SP+WRR test type txData[19] = (path & 0xf) | ((txq & 0xf) << 4); //path & txq totalTxPkts++; bearer = (path >> (PATH_BEARER_SHIFT)) & 0x1; PTM_DBG(DBG_L1, "%s: path:%d, txq:%d, pkt:%d\n", __FUNCTION__, path, txq, pkt); mt7510_ptm_tx(skb, mt7510PtmDev[bearer]); return 0; } static int spWrr_tx_put(int path) { int txq, pkt; /* Here we focus on q4:q3:q2:q1:q0 == 5:4:3:2:1 */ /* due to HW's design, put multiple of txqWrrVal[txqN] * packets for txqN ! So we put 12, 24, 36, 48 * 60 packets in txq0, 1, 2 ,3, 4 respectively */ for (txq = 0; txq < 5; txq++) { for (pkt = 0; pkt < (txqWrrVal[txq]*12); pkt++) { if (spWrr_tx(path, txq, pkt)) return -1; } } // init variables wrrQueuePhase = 0; wrrQueueStart = 0; dataPathRxPkts = 0; /* Here we focus on q7>q6>q5> q4,q3,q2,q1,q0 */ for (txq = 5; txq < TX_QUEUE_NUM; txq++) { /* in case QDMA IRQ is full, just put TX_BURST_LEN * packets in each Txq */ for (pkt = 0; pkt < TX_BURST_LEN; pkt++) { if (spWrr_tx(path, txq, pkt)) return -1; } } //init parameters for RX curTxq = 7; testPktCnt = 1; //initialize testPktCnt return 0; } /* For each path test: * 1. set QDMA as SP+WRR mode * 2. send a packet for every queue of the path. * 2. enable QDMA TX buffer usage but set threshold to 0 * 3. send multiple of txqWrrVal[txqN] packets for txq0~4 * and then (3*TX_BURST_LEN) packets for txq5~7 * to QDMA link manager. * 4. hold QDMA. * 5. release QDMA TX buffer usage * 6. turn on QDMA * 7. wait until all loopback packets are receved * according to their priority. */ static int ptm_loopback_spWrr_tx(uint32 pktNum) { int loop = 0; int i, path, txq; QDMA_TxQosScheduler_T txQos; QDMA_TxBufCtrl_T txBufUsage; printk("\nStart %s test\n", __FUNCTION__); if (pktNum == 0) if (!isAllTestsOnGoing) loop = 1; txqWrrTotalVal = 0; for (i = 0; i < 5; i++) txqWrrTotalVal += txqWrrVal[i]; spWrr_loop: for (path = startPath; path < endPath; path++) { /* set QDMA's SP+WRR priority registers, * so that p7>p6>p5> p4:p3:p2:p1:p0 == 5:4:3:2:1 */ memset(&txQos, 0, sizeof(QDMA_TxQosScheduler_T)); txQos.channel = path; txQos.qosType = QDMA_TXQOS_TYPE_SPWRR5; for(i = 0 ; i < 5; i++) txQos.queue[i].weight = txqWrrVal[i]; if (qdma_set_tx_qos(&txQos)) { printk("\nERROR(%s): qdma_set_tx_qos for path%d\n" , __FUNCTION__, path); return -1; } else //success { memset(&txQos, 0, sizeof(QDMA_TxQosScheduler_T)); txQos.channel = path; qdma_get_tx_qos(&txQos) ; printk("\nSP+WRR setting OK for Path:%d, Type:%d\n" "Q7> Q6> Q5> Q4:%d, Q3:%d, Q2:%d, Q1:%d, Q0:%d\n\n", path, txQos.qosType, txQos.queue[4].weight, txQos.queue[3].weight, txQos.queue[2].weight, txQos.queue[1].weight, txQos.queue[0].weight); } /* Due to HW's design, HW WRR counters will be * accurate after every queue (per path) sends a packet */ if (isWrrFirstTest[path]) { qdma_dma_mode(QDMA_DISABLE, QDMA_DISABLE, QDMA_DISABLE); for (txq = 0; txq < TX_QUEUE_NUM; txq++) { if (spWrr_tx(path, txq, 0)) return -1; } dataPathRxPkts = 0; qdmaDmaAvailable = 0; qdmaWaitingCnt = 0; qdma_dma_mode(QDMA_ENABLE, QDMA_ENABLE, QDMA_DISABLE); //noHwFwd while (!qdmaDmaAvailable) { if (++qdmaWaitingCnt == 3) { printk("\nWaiting for too long for WRR dirst test for path%d\n", path); return -1; } msleep(LOOP_SLEEP_TIME); } isWrrFirstTest[path] = 0; } /* begine real SP_WRR test */ //init variables qdmaDmaAvailable = 0; qdmaWaitingCnt = 0; /* enable TX buffer usage and set threshold to 0, * then packets will be queued in QDMA link manager * in priority but won't be sent */ memset(&txBufUsage, 0, sizeof(QDMA_TxBufCtrl_T)); txBufUsage.mode = QDMA_ENABLE; if (qdma_set_txbuf_threshold (&txBufUsage)) { printk("\nFAILED(%s): qdma enable txBufUsage\n" , __FUNCTION__); return -1; } if (spWrr_tx_put(path)) return -1; qdma_dma_mode(QDMA_DISABLE, QDMA_DISABLE, QDMA_DISABLE); //release TX buffer usage memset(&txBufUsage, 0, sizeof(QDMA_TxBufCtrl_T)); if (qdma_set_txbuf_threshold (&txBufUsage)) { printk("\nFAILED(%s): qdma disable txBufUsage\n" , __FUNCTION__); return -1; } qdma_dma_mode(QDMA_ENABLE, QDMA_ENABLE, QDMA_DISABLE); //noHwFwd while (!qdmaDmaAvailable) { if (++qdmaWaitingCnt == 3) { printk("\nWaiting for too long! (%d pkts sent)\n", totalTxPkts); return -1; } msleep(LOOP_SLEEP_TIME); } if (stopTesting) { printk("\nStop Testing (SP+WRR priority):\n" "path:%d, totalTxPkts:%d\n", path, totalTxPkts); return -1; } } /* WRR counters will be reset * when not looping in the same Path. */ if (endPath > startPath+1) { for (path = startPath; path < endPath; path++) isWrrFirstTest[path] = 1; } if (loop) { printk("\nSP+WRR priority TX Loop %d OK\n", loop); loop++; goto spWrr_loop; } printk("\nSP+WRR priority TX OK with %d pkts!\n", totalTxPkts); /* set QDMA QOS registers back to default values * which is QDMA_TXQOS_TYPE_SP */ for (i = startPath; i < endPath; i++) { memset(&txQos, 0, sizeof(QDMA_TxQosScheduler_T)); txQos.channel = i; txQos.qosType = QDMA_TXQOS_TYPE_SP; if (qdma_set_tx_qos(&txQos)) { printk("\nERROR(%s): qdma_set_tx_qos for path%d\n", __FUNCTION__,i); return -1; } } return 0; } /* HW to tag. SW to check if the tagging is correct */ static int ptm_loopback_vlanTag_tx(uint32 pktNum) { int nPkts, loop = 0; struct sk_buff *skb = NULL; uint8 *txData = NULL; int pkt, path, bearer; int offset = 22; uint32 reg = 0; printk("\nStart %s test\n", __FUNCTION__); if (pktNum == 0) { nPkts = 1500; if (!isAllTestsOnGoing) loop = 1; } else nPkts = pktNum; /* disable "Extract outer VLAN tag" * in order to use SW to un-tag */ reg = fe_reg_read(CDM_VLAN_GE_OFF); reg &= ~(0x2); fe_reg_write(CDM_VLAN_GE_OFF, reg); vlan_tag_loop: for (path = startPath; path < endPath; path++) { for (pkt = 0; pkt < nPkts; pkt++) { if (txCommonContent_fill(&skb, &txData, pkt, RAN_PKTTYPE, ETHER_TYPE_IP, offset, 0)) return -1; txData[18] = VLAN_TAG_TESTTYPE; //vlan_tag test type //even pkt: HW don't tag, odd pkt: HW tag. txData[19] = (path&0xf) | ((pkt&1)<<4); if ((txData[19]>>4) & 0x1) { //13-bit vlan tag *((uint16*)(&txData[20])) = (uint16) (random32() & 0x1fff); //Rx will receive 4 more bytes *((uint16*)(&txData[16])) += 4; } if (!stopTesting) { totalTxPkts++; bearer = (path >> PATH_BEARER_SHIFT) & 0x1; PTM_DBG(DBG_L1, "%s: path:%d, pkt:%d\n", __FUNCTION__, path, pkt); loopback_pkt_transmit(skb, bearer); } else { printk("\nStop Testing (vlanTag):\n" "path:%d, pkt:%d, totalTxPkts:%d\n", path, pkt, totalTxPkts); return -1; } } } if (loop) { printk("\nVlan_Tag TX Loop %d OK\n", loop); loop++; goto vlan_tag_loop; } printk("\nVlan_Tag TX OK with %d pkts!\n", totalTxPkts); return 0; } /* SW to tag. HW to un-tag for SW to analysize */ static int ptm_loopback_vlanUnTag_tx(uint32 pktNum) { int nPkts, loop = 0; struct sk_buff *skb = NULL; uint8 *txData = NULL; int pkt = 0, path, bearer; int offset = 22; uint32 reg = 0; printk("\nStart %s test\n", __FUNCTION__); if (pktNum == 0) { nPkts = 1500; if (!isAllTestsOnGoing) loop = 1; } else nPkts = pktNum; /* enable "Extract outer VLAN tag" * in order to use HW to un-tag */ reg = fe_reg_read(CDM_VLAN_GE_OFF); reg |= 0x2; fe_reg_write(CDM_VLAN_GE_OFF, reg); vlan_untag_loop: for (path = startPath; path < endPath; path++) { for (pkt = 0; pkt < nPkts; pkt++) { if (txCommonContent_fill(&skb, &txData, pkt, RAN_PKTTYPE, ETHER_TYPE_8021Q, offset, 0)) return -1; txData[18] = VLAN_UNTAG_TESTTYPE; //vlan_untag test type //even pkt: SW don't tag, odd pkt: SW tag. txData[19] = (path&0xf) | ((pkt&0x1)<<4); if (!stopTesting) { totalTxPkts++; bearer = (path >> PATH_BEARER_SHIFT) & 0x1; PTM_DBG(DBG_L1, "%s: path:%d, pkt:%d\n", __FUNCTION__, path, pkt); loopback_pkt_transmit(skb, bearer); } else { printk("\nStop Testing (vlanUnTag):\n" "path:%d, pkt:%d, totalTxPkts:%d\n", path, pkt, totalTxPkts); return -1; } } } if (loop) { printk("\nVlan_UnTag TX Loop %d OK\n", loop); loop++; goto vlan_untag_loop; } printk("\nVlan_UnTag TX OK with %d pkts!\n", totalTxPkts); /* set it back to default value */ reg = fe_reg_read(CDM_VLAN_GE_OFF); reg &= ~(0x2); fe_reg_write(CDM_VLAN_GE_OFF, reg); return 0; } /* HW double tag, SW checkk if the double tagging is correct. */ static int ptm_loopback_vlanDblTag_tx(uint32 pktNum) { int nPkts, loop = 0; struct sk_buff *skb = NULL; uint8 *txData = NULL; int pkt, path, bearer; int offset = 22; uint32 reg = 0; printk("\nStart %s test\n", __FUNCTION__); if (pktNum == 0) { nPkts = 1500; if (!isAllTestsOnGoing) loop = 1; } else nPkts = pktNum; /* disable "Extract outer VLAN tag" for SW to un-tag, * and then set CDMQ_TPID for user-defined VLAN tag */ reg = fe_reg_read(CDM_VLAN_GE_OFF); reg &= ~((0x2) | (0xffff << 16)); reg |= (ETHER_TYPE_QINQ << 16); fe_reg_write(CDM_VLAN_GE_OFF, reg); vlan_dbl_tag_loop: for (path = startPath; path < endPath; path++) { for (pkt = 0; pkt < nPkts; pkt++) { if (txCommonContent_fill(&skb, &txData, pkt, 1, ETHER_TYPE_8021AD, offset, 0)) return -1; //vlan_double_tag test type txData[18] = VLAN_DBL_TAG_TESTTYPE; /* pkt0,2: HW don't tag, * pkt1: HW tag 0x88a8, * pkt3: HW tag 0x9100.*/ txData[19] = (path&0xf) | ((pkt&0x3)<<4); if ((((txData[19]>>4)&0x3) == 1) || (((txData[19]>>4)&0x3) == 3)) *((uint16*)(&txData[16])) += 8; //Rx will receive 4 more bytes for vlanTag & add 4 for prevous minus 4. if (!stopTesting) { totalTxPkts++; bearer = (path >> PATH_BEARER_SHIFT) & 0x1; PTM_DBG(DBG_L1, "%s: path:%d, pkt:%d\n", __FUNCTION__, path, pkt); loopback_pkt_transmit(skb, bearer); } else { printk("\nStop Testing (vlanDblTag):\n" "path:%d, pkt:%d, totalTxPkts:%d\n", path, pkt, totalTxPkts); return -1; } } } if (loop) { printk("\nVlan_Dbl_Tag TX Loop %d OK\n", loop); loop++; goto vlan_dbl_tag_loop; } printk("\nVlan_Dbl_Tag TX OK with %d pkts!\n", totalTxPkts); //set it back to default value fe_reg_write(CDM_VLAN_GE_OFF, 0); return 0; } /* SW double tag, HW only un-tag the outer tag, which is * 8021AD or QinQ, for SW to analysize. */ static int ptm_loopback_vlanDblUnTag_tx(uint32 pktNum) { int nPkts, loop = 0; struct sk_buff *skb = NULL; uint8 *txData = NULL; int pkt, path, bearer; int offset = 22; uint32 reg = 0; printk("\nStart %s test\n", __FUNCTION__); if (pktNum == 0) { nPkts = 1500; if (!isAllTestsOnGoing) loop = 1; } else nPkts = pktNum; /* enable "Extract outer VLAN tag" for HW to un-tag */ reg = fe_reg_read(CDM_VLAN_GE_OFF); reg |= 0x2; fe_reg_write(CDM_VLAN_GE_OFF, reg); /* Extented VLAN TPID for 0x9100 for RX */ reg = fe_reg_read(FE_GLO_CFG_OFF); reg &= ~(0xffff << 16); reg |= (ETHER_TYPE_QINQ << 16); fe_reg_write(FE_GLO_CFG_OFF, reg); vlan_dbl_untag_loop: for (path = startPath; path < endPath; path++) { for (pkt = 0; pkt < nPkts; pkt++) { if (txCommonContent_fill(&skb, &txData, pkt, RAN_PKTTYPE, ETHER_TYPE_QINQ, offset, 0)) return -1; //vlan_bdl_untag test type txData[18] = VLAN_DBL_UNTAG_TESTTYPE; /* pkt0,2: SW don't tag, * pkt1: SW tags 8021AD and 8021Q, * pkt3: SW tags QinQ and 8021Q.*/ txData[19] = (path&0xf) | ((pkt&0x3)<<4); if ((((txData[19]>>4)&0x3) == 1) || (((txData[19]>>4)&0x3) == 3)) *((uint16*)(&txData[16])) += 4; //add 4 for prevous minus 8. if (!stopTesting) { totalTxPkts++; bearer = (path >> PATH_BEARER_SHIFT) & 0x1; PTM_DBG(DBG_L1, "%s: path:%d, pkt:%d\n", __FUNCTION__, path, pkt); loopback_pkt_transmit(skb, bearer); } else { printk("\nStop Testing (vlanDblUnTag):\n" "path:%d, pkt:%d, totalTxPkts:%d\n", path, pkt, totalTxPkts); return -1; } } } if (loop) { printk("\nVlanDblUnTag TX Loop %d OK\n", loop); loop++; goto vlan_dbl_untag_loop; } printk("\nVlanDblUnTag TX OK with %d pkts!\n", totalTxPkts); /* set it back to default values */ fe_reg_write(CDM_VLAN_GE_OFF, 0); reg = fe_reg_read(FE_GLO_CFG_OFF); reg &= ~(0xffff << 16); reg |= (0x8100 << 16); fe_reg_write(FE_GLO_CFG_OFF, reg); return 0; } /* HW insert IP chksum, SW check if the IP chksum is correct */ static int ptm_loopback_ipCsInsert_tx(uint32 pktNum) { int nPkts, loop = 0; struct sk_buff *skb = NULL; uint8 *txData = NULL; int pkt, path, bearer; int offset = 26; printk("\nStart %s test\n", __FUNCTION__); if (pktNum == 0) { nPkts = 1500; if (!isAllTestsOnGoing) loop = 1; } else nPkts = pktNum; ipcs_insert_loop: for (path = startPath; path < endPath; path++) { for (pkt = 0; pkt < nPkts; pkt++) { if (txCommonContent_fill(&skb, &txData, pkt, RAN_PKTTYPE, ETHER_TYPE_IP, offset, 0)) return -1; //HW needs correct ip version & header length to do ip chksum txData[14] = (4 << 4) | (5); txData[18] = IPCS_INSERT_TESTTYPE; //ipcs_insert test type //even pkt: HW don't ipcs insert, odd pkt: HW ipcs insert. txData[19] = (path&0xf) | ((pkt&0x1)<<4); txData[20] = 0x12; txData[21] = 0x34; txData[22] = 0x56; txData[23] = 0x78; //Byte24~25 are left for HW to insert ip chksum, needed to be reset before calculating and inserting. txData[24] = 0; txData[25] = 0; if (!stopTesting) { totalTxPkts++; bearer = (path >> PATH_BEARER_SHIFT) & 0x1; PTM_DBG(DBG_L1, "%s: path:%d, pkt:%d\n", __FUNCTION__, path, pkt); loopback_pkt_transmit(skb, bearer); } else { printk("\nStop Testing (ipCsInsert):\n" "path:%d, pkt:%d, totalTxPkts:%d\n", path, pkt, totalTxPkts); return -1; } } } if (loop) { printk("\nipCsInsert TX Loop %d OK\n", loop); loop++; goto ipcs_insert_loop; } printk("\nipCsInsert TX OK with %d pkts!\n", totalTxPkts); return 0; } /* SW insert IP chksum, HW indicate if IP chksum is correct */ static int ptm_loopback_ipCsCheck_tx(uint32 pktNum) { int nPkts, loop = 0; struct sk_buff *skb = NULL; uint8 *txData = NULL; int pkt, path, bearer; int offset = 26; uint32 reg; printk("\nStart %s test\n", __FUNCTION__); /* don't drop packets with ipv4 checksum error * but indicate those packets in RX message */ reg = fe_reg_read(GDM2_FWD_CFG_OFF); reg &= ~(1<<22); fe_reg_write(GDM2_FWD_CFG_OFF, reg); if (pktNum == 0) { nPkts = 1500; if (!isAllTestsOnGoing) loop = 1; } else nPkts = pktNum; ipcs_check_loop: for (path = startPath; path < endPath; path++) { for (pkt = 0; pkt < nPkts; pkt++) { if (txCommonContent_fill(&skb, &txData, pkt, RAN_PKTTYPE, ETHER_TYPE_IP, offset, 0)) return -1; //HW needs connect ip version & header length to do ip chksum txData[14] = (4 << 4) | (5); txData[18] = IPCS_CHECK_TESTTYPE; //ipcs_check test type txData[19] = (path&0xf) | ((pkt&0x1)<<4); txData[20] = 0xab; txData[21] = 0x34; txData[22] = 0x56; txData[23] = 0x78; //Byte24~25 are left for ip chksum calculated by SW, needed to be reset before calculating. txData[24] = 0; txData[25] = 0; //even pkt: SW insert wrong ip chksum, odd pkt: SW insert correct ip chksum. if ((txData[19]>>4)&0x1) *((uint16*)(&txData[24])) = in_csum((unsigned short *) &txData[14], 20); else *((uint16*)(&txData[24])) = (1 + in_csum((unsigned short *) &txData[14], 20)); if (!stopTesting) { totalTxPkts++; bearer = (path >> PATH_BEARER_SHIFT) & 0x1; PTM_DBG(DBG_L1, "%s: path:%d, pkt:%d\n", __FUNCTION__, path, pkt); loopback_pkt_transmit(skb, bearer); } else { printk("\nStop Testing (ipCsCheck):\n" "path:%d, pkt:%d, totalTxPkts:%d\n", path, pkt, totalTxPkts); return -1; } } } if (loop) { printk("\nipCsCheck TX Loop %d OK\n", loop); loop++; goto ipcs_check_loop; } printk("\nipCsCheck TX OK with %d pkts!\n", totalTxPkts); return 0; } /* case 0~11 will be tested by ptm_loopback_bacpCheck, * case 88 will be tested by ptm_loopbackBacpRegSet */ static int bacpStageChange(void) { switch(bacpCheckStage) { case 0: PTM_DBG(DBG_L1, "bacp test for default\n"); bacpHeader_write(0x0180c200, 0x00028809, 0x0a0019a7, 0x01010000); bacpReg_write(0x0180c200, 0x00028809, 0x0a0019a7, 0x01010000, 0x3f); break; case 1: PTM_DBG(DBG_L1, "bacp test for Dst MAC case 1\n"); bacpHeader_write(0x0180c200, 0x00028809, 0x0a0019a7, 0x01010000); bacpReg_write(0x0180c200, 0x00028809, 0x0a0019a7, 0x01010000, 0x1); break; case 2: PTM_DBG(DBG_L1, "bacp test for Dst MAC case 2\n"); bacpHeader_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000); break; case 3: PTM_DBG(DBG_L1, "bacp test for Org SubType case 1\n"); bacpHeader_write(0x0180c200, 0x00028809, 0x0a0019a7, 0x01010000); bacpReg_write(0x0180c200, 0x00028809, 0x0a0019a7, 0x01010000, 0x4); break; case 4: PTM_DBG(DBG_L1, "bacp test for Org SubType case 2\n"); bacpHeader_write(0x0180c200, 0x00028809, 0x0b0019a7, 0x01010000); break; case 5: PTM_DBG(DBG_L1, "bacp test for ITU OUI case 1\n"); bacpHeader_write(0x0180c200, 0x00028809, 0x0a0019a7, 0x01010000); bacpReg_write(0x0180c200, 0x00028809, 0x0a0019a7, 0x01010000, 0x8); break; case 6: PTM_DBG(DBG_L1, "bacp test for ITU OUI case 2\n"); bacpHeader_write(0x0180c200, 0x00028809, 0x0a0019a8, 0x01010000); break; case 7: PTM_DBG(DBG_L1, "bacp test for ITU SubType case 1\n"); bacpHeader_write(0x0180c200, 0x00028809, 0x0a0019a7, 0x01010000); bacpReg_write(0x0180c200, 0x00028809, 0x0a0019a7, 0x01010000, 0x10); break; case 8: PTM_DBG(DBG_L1, "bacp test for ITU SubType case 2\n"); bacpHeader_write(0x0180c200, 0x00028809, 0x0a0019a7, 0x02010000); break; case 9: PTM_DBG(DBG_L1, "bacp test for BACP version case 1\n"); bacpHeader_write(0x0180c200, 0x00028809, 0x0a0019a7, 0x01010000); bacpReg_write(0x0180c200, 0x00028809, 0x0a0019a7, 0x01010000, 0x20); break; case 10: PTM_DBG(DBG_L1, "bacp test for BACP version case 2\n"); bacpHeader_write(0x0180c200, 0x00028809, 0x0a0019a7, 0x01020000); break; case 11: PTM_DBG(DBG_L1, "for Dst MAC & BACP version case 1\n"); bacpHeader_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000); bacpReg_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000, 0x21); break; case 12: PTM_DBG(DBG_L1, "for Dst MAC & BACP version case 2\n"); bacpHeader_write(0x0180c201, 0x10028809, 0x0a0019a7, 0x01110000); break; case 13: PTM_DBG(DBG_L1, "for Dst MAC & ITU SubType case 1\n"); bacpHeader_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000); bacpReg_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000, 0x11); break; case 14: PTM_DBG(DBG_L1, "for Dst MAC & ITU SubType case 2\n"); bacpHeader_write(0x0180c201, 0x00038809, 0x0a0019a7, 0x11010000); break; case 15: PTM_DBG(DBG_L1, "for Dst MAC & ITU OUI case 1\n"); bacpHeader_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000); bacpReg_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000, 0x9); break; case 16: PTM_DBG(DBG_L1, "for Dst MAC & ITU OUI case 2\n"); bacpHeader_write(0x0180c201, 0x10028809, 0x0a0019b7, 0x01010000); break; case 17: PTM_DBG(DBG_L1, "for Dst MAC & Org SubType case 1\n"); bacpHeader_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000); bacpReg_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000, 0x5); break; case 18: PTM_DBG(DBG_L1, "for Dst MAC & Org SubType case 2\n"); bacpHeader_write(0x0180d201, 0x10028809, 0x1a0019a7, 0x01010000); break; case 19: PTM_DBG(DBG_L1, "for Dst MAC & Org SubType & ITU OUI case 1\n"); bacpHeader_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000); bacpReg_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000, 0xd); break; case 20: PTM_DBG(DBG_L1, "for Dst MAC & Org SubType & ITU OUI case 2\n"); bacpHeader_write(0x0190c301, 0x05228809, 0x3c1119a7, 0x01010000); break; case 21: PTM_DBG(DBG_L1, "for Org SubType & ITU OUI & ITU subType case 1\n"); bacpHeader_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000); bacpReg_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000, 0x1c); break; case 22: PTM_DBG(DBG_L1, "for Org SubType & ITU OUI & ITU subType case 2\n"); bacpHeader_write(0x0180c201, 0x00028809, 0x11aa1aa7, 0xaa010000); break; case 23: PTM_DBG(DBG_L1, "for ITU OUI & ITU subType & BACP version case 1\n"); bacpHeader_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000); bacpReg_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000, 0x38); break; case 24: PTM_DBG(DBG_L1, "for ITU OUI & ITU subType & BACP version case 2\n"); bacpHeader_write(0x0180c201, 0x00028809, 0x0a441177, 0x98760000); break; case 25: PTM_DBG(DBG_L1, "for Org SubType & ITU OUI & ITU subType & BACP version case 1\n"); bacpHeader_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000); bacpReg_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000, 0x3c); break; case 26: PTM_DBG(DBG_L1, "for Org SubType & ITU OUI & ITU subType & BACP version case 2\n"); bacpHeader_write(0x0180c201, 0x00028809, 0x33333333, 0x33330000); break; case 27: PTM_DBG(DBG_L1, "for Dst MAC & ITU OUI & ITU subType & BACP version case 1\n"); bacpHeader_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000); bacpReg_write(0x0180c201, 0x00028809, 0x0a0019a7, 0x01010000, 0x39); break; case 28: PTM_DBG(DBG_L1, "for Dst MAC & ITU OUI & ITU subType & BACP version case 2\n"); bacpHeader_write(0x05555555, 0x55558809, 0x0a555555, 0x55550000); break; case BACP_CHECK_STAGE: PTM_DBG(DBG_L1, "bacp test for default case 2\n"); bacpHeader_write(0x01eeeeee, 0xeeee8809, 0xeeeeeeee, 0xeeee0000); bacpReg_write(0x0180c200, 0x00028809, 0x0a0019a7, 0x01010000, 0x3f); break; case 88: PTM_DBG(DBG_L1, "bacp test by CI command\n"); break; default: printk("\nunknown bacp test case!\n"); return -1; } bacpHeader_read(); bacpReg_read(); return 0; } /* For case 0~11 in bacpStageChange(), * SW insert BACP header and set registers, * HW indicate if the packet is for BACP */ static int ptm_loopback_bacpCheck_tx(uint32 pktNum) { int nPkts, loop = 0; struct sk_buff *skb = NULL; uint8 *txData = NULL; int pkt, path, bearer; int offset = 20; printk("\nStart %s test\n", __FUNCTION__); if (pktNum == 0) { nPkts = 1500; if (!isAllTestsOnGoing) loop = 1; } else nPkts = pktNum; bacpCheckStage = 0; bacp_check_loop: if (bacpStageChange()) return -1; for (path = startPath; path < endPath; path++) { for (pkt = 0; pkt < nPkts; pkt++) { if (txCommonContent_fill(&skb, &txData, pkt, RAN_PKTTYPE, ETHER_TYPE_SLOW, offset, 0)) return -1; txData[18] = BACP_PKT_TESTTYPE; //bacp_check test type //even pkt: data pkt, odd pkt: bacp pkt.(fill bacp header in txCommonContent_fill) txData[19] = (path&0xf) | ((pkt&0x1)<<4); if ((txData[19]>>4)&0x1) *((uint16*)(&txData[16])) += 10; //for previous minus 10. if (!stopTesting) { totalTxPkts++; bearer = (path >> PATH_BEARER_SHIFT) & 0x1; //PTM_DBG(DBG_L1, "%s: path:%d, pkt:%d\n", __FUNCTION__, path, pkt); loopback_pkt_transmit(skb, bearer); } else { printk("\nStop Testing (bacpCheck):\n" "path:%d, pkt:%d, totalTxPkts:%d\n", path, pkt, totalTxPkts); return -1; } } } if (0 <= bacpCheckStage && bacpCheckStage < BACP_CHECK_STAGE) { bacpCheckStage++; goto bacp_check_loop; } if (loop) { printk("\nbacpCheck TX Loop %d OK\n", loop); loop++; bacpCheckStage = 0; goto bacp_check_loop; } printk("\nbacpCheck TX OK with %d pkts!\n", totalTxPkts); //set back to default values bacpHeader_write(0x0180c200, 0x00028809, 0x0a0019a7, 0x01010000); bacpReg_write(0x0180c200, 0x00028809, 0x0a0019a7, 0x01010000, 0x3f); bacpCheckStage = 0; return 0; } /* SW send runt packets, HW indicate if the packet is runt */ static int ptm_loopback_runtCheck_tx(uint32 pktNum) { int nPkts, loop = 0; struct sk_buff *skb = NULL; uint8 *txData = NULL; int pkt, path, bearer; uint32 txLen; int offset = 20; uint32 reg; printk("\nStart %s test\n", __FUNCTION__); /* don't drop packets with len < 60 bytes (not including CRC) * but indicate those packets in RX message */ reg = fe_reg_read(GDM2_FWD_CFG_OFF); reg &= ~(1<<24); fe_reg_write(GDM2_FWD_CFG_OFF, reg); if (pktNum == 0) { nPkts = 1500; if (!isAllTestsOnGoing) loop = 1; } else nPkts = pktNum; runt_check_loop: for (path = startPath; path < endPath; path++) { for (pkt = 0; pkt < nPkts; pkt++) { if (pkt & 1) { //txLen: 21~59 bytes for Runt packets txLen = random32(); if ((txLen < 21) || (txLen > 59)) txLen %= 39; txLen += 21; } else txLen = 0; if (txCommonContent_fill(&skb, &txData, pkt, RAN_PKTTYPE, ETHER_TYPE_IP, offset, txLen)) return -1; txData[18] = RUNT_PKT_TESTTYPE; //runt_check test type txData[19] = (path&0xf) | ((pkt&0x1)<<4); //even pkt: normal pkt, odd pkt: runt pkt. if (!stopTesting) { totalTxPkts++; bearer = (path >> PATH_BEARER_SHIFT) & 0x1; PTM_DBG(DBG_L1, "%s: path:%d, pkt:%d, txLen:%d\n", __FUNCTION__, path, pkt, (int)*((uint16*)(&txData[16]))); loopback_pkt_transmit(skb, bearer); } else { printk("\nStop Testing (runtCheck):\n" "path:%d, pkt:%d, totalTxPkts:%d\n", path, pkt, totalTxPkts); return -1; } } } if (loop) { printk("\nruntCheck TX Loop %d OK\n", loop); loop++; goto runt_check_loop; } printk("\nruntCheck TX OK with %d pkts!\n", totalTxPkts); return 0; } /* SW send long packets, HW indicate if the packet is long */ static int ptm_loopback_longCheck_tx(uint32 pktNum) { int nPkts, loop = 0; struct sk_buff *skb = NULL; uint8 *txData = NULL; int pkt, path, bearer; uint32 txLen; int offset = 20; uint32 reg; printk("\nStart %s test\n", __FUNCTION__); /* don't drop long packets * but indicate those packets in RX message */ reg = fe_reg_read(GDM2_FWD_CFG_OFF); reg &= ~(1<<25); fe_reg_write(GDM2_FWD_CFG_OFF, reg); /* configure packets with len > 1514 bytes * (not including 4-byte CRC) as long packets */ reg = fe_reg_read(GDM2_LEN_CFG_OFF); reg &= ~(0xffff0000); reg |= 0x5ea << 16; fe_reg_write(GDM2_LEN_CFG_OFF, reg); if (pktNum == 0) { nPkts = 1500; if (!isAllTestsOnGoing) loop = 1; } else nPkts = pktNum; long_check_loop: for (path = startPath; path < endPath; path++) { for (pkt = 0; pkt < nPkts; pkt++) { if (pkt & 1) { //txLen: 1515~MAX_PKT_SZIE bytes for Long packets txLen = random32(); if ((txLen < 1515) || (txLen > MAX_PKT_SIZE)) { txLen %= (MAX_PKT_SIZE - 1515 + 1); txLen += 1515; } } else txLen = 0; if (txCommonContent_fill(&skb, &txData, pkt, 1, ETHER_TYPE_IP, offset, txLen)) return -1; txData[18] = LONG_PKT_TESTTYPE; //long_check test type txData[19] = (path&0xf) | ((pkt&0x1)<<4); //even pkt: normal pkt, odd pkt: long pkt. if (!stopTesting) { totalTxPkts++; bearer = (path >> PATH_BEARER_SHIFT) & 0x1; PTM_DBG(DBG_L1, "%s: path:%d, len:%d\n", __FUNCTION__, path, *((uint16*)(&txData[16]))); loopback_pkt_transmit(skb, bearer); } else { printk("\nStop Testing (longCheck):\n" "path:%d, pkt:%d, totalTxPkts:%d\n", path, pkt, totalTxPkts); return -1; } } } if (loop) { printk("\nlongCheck TX Loop %d OK\n", loop); loop++; goto long_check_loop; } printk("\nlongCheck TX OK with %d pkts!\n", totalTxPkts); //set it back to default values reg = fe_reg_read(GDM2_LEN_CFG_OFF); reg &= ~(0xffff0000); reg |= 0x7d0 << 16; fe_reg_write(GDM2_LEN_CFG_OFF, reg); return 0; } /* HW generate CRC packets and then indacate if the * packet is CRC-error. * Please note: during this test, MAC Rx crcErr counters * should count! */ static int ptm_loopback_crcCheck_tx(uint32 pktNum) { int nPkts, loop = 0; struct sk_buff *skb = NULL; uint8 *txData = NULL; int pkt, path, bearer; int offset = 20; uint32 reg; printk("\nStart %s test\n", __FUNCTION__); isCrcCheckTest = 1; if (pktNum == 0) { nPkts = 1500; if (!isAllTestsOnGoing) loop = 1; } else nPkts = pktNum; reg = read_reg_word(PTM_CTRL_REG); crc_check_loop: for (path = startPath; path < endPath; path++) { for (pkt = 0; pkt < nPkts; pkt++) { if (txCommonContent_fill(&skb, &txData, pkt, RAN_PKTTYPE, ETHER_TYPE_IP, offset, 0)) return -1; txData[18] = CRCERR_PKT_TESTTYPE; //crc_check test type txData[19] = (path&0xf) | ((pkt&0x1)<<4); //even pkt: normal pkt, odd pkt: crc pkt. if (pkt &0x1) { /* enable "HW wrong CRC generation" */ reg |= (0x1<<18); write_reg_word(PTM_CTRL_REG, reg); } else { /* disable "HW wrong CRC generation" */ reg &= ~(0x1<<18); write_reg_word(PTM_CTRL_REG, reg); } if (!stopTesting) { totalTxPkts++; bearer = (path >> PATH_BEARER_SHIFT) & 0x1; PTM_DBG(DBG_L1, "%s: path:%d, pkt:%d\n", __FUNCTION__, path, pkt); loopback_pkt_transmit(skb, bearer); } else { printk("\nStop Testing (crcCheck):\n" "path:%d, pkt:%d, totalTxPkts:%d\n", path, pkt, totalTxPkts); return -1; } } } if (loop) { printk("\ncrcCheck TX Loop %d OK\n", loop); loop++; goto crc_check_loop; } printk("\ncrcCheck TX OK with %d pkts!\n", totalTxPkts); //set it back to defualt value reg = read_reg_word(PTM_CTRL_REG); reg &= ~(0x1<<18); write_reg_word(PTM_CTRL_REG, reg); return 0; } static int ptm_loopback_allTests_tx(uint32 pktNum) { int nPackets, loop = 0; printk("\nStart %s test\n", __FUNCTION__); isAllTestsOnGoing = 1; if (pktNum == 0) { nPackets = 1500; loop = 1; } else nPackets = pktNum; all_tests_loop: if (ptm_loopback_dataPath_tx(nPackets)) goto allTests_fail; else msleep(TEST_SLEEP_TIME); if (ptm_loopback_pathNo_tx(nPackets)) goto allTests_fail; else msleep(TEST_SLEEP_TIME); #if !(defined(TCSUPPORT_BONDING) && defined(FPGA_STAGE)) /* Boding's clock in FPGA is slow, so burst mode * based tests can't work, so don't care them! */ if (ptm_loopback_preemption_tx(nPackets)) goto allTests_fail; else msleep(TEST_SLEEP_TIME); if (ptm_loopback_spPriority_tx(nPackets)) goto allTests_fail; else msleep(TEST_SLEEP_TIME); if (ptm_loopback_wrrPriority_tx(nPackets)) goto allTests_fail; else msleep(TEST_SLEEP_TIME); if (ptm_loopback_spWrr_tx(nPackets)) goto allTests_fail; else msleep(TEST_SLEEP_TIME); #endif if (ptm_loopback_vlanTag_tx(nPackets)) goto allTests_fail; else msleep(TEST_SLEEP_TIME); if (ptm_loopback_vlanUnTag_tx(nPackets)) goto allTests_fail; else msleep(TEST_SLEEP_TIME); if (ptm_loopback_vlanDblTag_tx(nPackets)) goto allTests_fail; else msleep(TEST_SLEEP_TIME); if (ptm_loopback_vlanDblUnTag_tx(nPackets)) goto allTests_fail; else msleep(TEST_SLEEP_TIME); if (ptm_loopback_ipCsInsert_tx(nPackets)) goto allTests_fail; else msleep(TEST_SLEEP_TIME); if (ptm_loopback_ipCsCheck_tx(nPackets)) goto allTests_fail; else msleep(TEST_SLEEP_TIME); if (ptm_loopback_bacpCheck_tx(nPackets)) goto allTests_fail; else msleep(TEST_SLEEP_TIME); if (ptm_loopback_runtCheck_tx(nPackets)) goto allTests_fail; else msleep(TEST_SLEEP_TIME); if (ptm_loopback_longCheck_tx(nPackets)) goto allTests_fail; else msleep(TEST_SLEEP_TIME); if (ptm_loopback_crcCheck_tx(nPackets)) goto allTests_fail; else { msleep(TEST_SLEEP_TIME); isCrcCheckTest = 0; } #if !(defined(TCSUPPORT_BONDING) && defined(FPGA_STAGE)) /* Boding's clock in FPGA is slow, so burst mode * based tests can't work, so don't care them! */ if (ptm_loopback_dataBurst_tx(nPackets)) goto allTests_fail; else msleep(TEST_SLEEP_TIME); if (ptm_loopback_multiChannel_tx(nPackets)) goto allTests_fail; else msleep(TEST_SLEEP_TIME); #endif if (loop) { printk("\nallTests TX Loop %d OK\n", loop); loop++; goto all_tests_loop; } printk("\nallTests TX OK\n"); return 0; allTests_fail: return -1; } /* "echo N M > /proc/tc3162/ptm_loopback_test &" to * start loopback test. * Note: N is test case, M is number of test packets */ int ptm_loopbackTest_write_proc( struct file *file, const char *buffer, unsigned long count, void *data ) { char valString[10]; uint32 reg; if (count > sizeof(valString) - 1) return -EINVAL; if (copy_from_user(valString, buffer, count)) return -EFAULT; valString[count] = '\0'; if(sscanf(valString, "%d %d", &testType, &nPackets) != 2) return count; //init variables stopTesting = 0; dataPathRxPkts = 0; totalTxPkts = 0; isAllTestsOnGoing = 0; isCrcCheckTest = 0; /* don't do error drop for udp, tcp, ipv4 checksum * for loopback because loopback packet content * isn't well designed */ reg = fe_reg_read(GDM2_FWD_CFG_OFF); reg &= ~((1<<20) | (1<<21) | (1<<22)); fe_reg_write(GDM2_FWD_CFG_OFF, reg); switch (testType) { case REGISTER_TESTTYPE: ptm_loopback_registersCheck(nPackets); break; case SINGLE_PKT_TESTTYPE: ptm_loopback_singlePkt_tx(nPackets); break; case DATA_PATH_TESTTYPE: ptm_loopback_dataPath_tx(nPackets); break; case DATA_BURST_TESTTYPE: ptm_loopback_dataBurst_tx(nPackets); break; case MULTI_CHANNEL_TESTTYPE: ptm_loopback_multiChannel_tx(nPackets); break; case PATH_NO_TESTTYPE: ptm_loopback_pathNo_tx(nPackets); break; case PREEMPTION_TESTTYPE: ptm_loopback_preemption_tx(nPackets); break; case SP_PRIORITY_TESTTYPE: ptm_loopback_spPriority_tx(nPackets); break; case WRR_PRIORITY_TESTTYPE: ptm_loopback_wrrPriority_tx(nPackets); break; case SP_WRR_TESTTYPE: ptm_loopback_spWrr_tx(nPackets); break; case VLAN_TAG_TESTTYPE: ptm_loopback_vlanTag_tx(nPackets); break; case VLAN_UNTAG_TESTTYPE: ptm_loopback_vlanUnTag_tx(nPackets); break; case VLAN_DBL_TAG_TESTTYPE: ptm_loopback_vlanDblTag_tx(nPackets); break; case VLAN_DBL_UNTAG_TESTTYPE: ptm_loopback_vlanDblUnTag_tx(nPackets); break; case IPCS_INSERT_TESTTYPE: ptm_loopback_ipCsInsert_tx(nPackets); break; case IPCS_CHECK_TESTTYPE: ptm_loopback_ipCsCheck_tx(nPackets); break; case BACP_PKT_TESTTYPE: ptm_loopback_bacpCheck_tx(nPackets); break; case RUNT_PKT_TESTTYPE: ptm_loopback_runtCheck_tx(nPackets); break; case LONG_PKT_TESTTYPE: ptm_loopback_longCheck_tx(nPackets); break; case CRCERR_PKT_TESTTYPE: ptm_loopback_crcCheck_tx(nPackets); break; case ALL_LOOPBACK_TESTTYPE: ptm_loopback_allTests_tx(nPackets); break; default: printk("\nWrong loopback test type: %d\n", testType); break; } return count; } /* "cat /proc/tc3162/ptm_loopback_test &" to * see what loopback tests do we have. */ int ptm_loopbackTest_read_proc( char *buf, char **start, off_t off, int count, int *eof, void *data ) { int index = 0; off_t pos = 0; off_t begin = 0; index += sprintf(buf+index, "\nTest Type IDs:\n"); CHK_BUF(); index += sprintf(buf+index, "REGISTER_TESTTYPE: %d\n", REGISTER_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "DATA_PATH_TESTTYPE: %d\n", DATA_PATH_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "PATH_NO_TESTTYPE: %d\n", PATH_NO_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "PREEMPTION_TESTTYPE: %d\n", PREEMPTION_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "SP_PRIORITY_TESTTYPE: %d\n", SP_PRIORITY_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "WRR_PRIORITY_TESTTYPE: %d\n", WRR_PRIORITY_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "SP_WRR_TESTTYPE: %d\n", SP_WRR_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "VLAN_TAG_TESTTYPE: %d\n", VLAN_TAG_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "VLAN_UNTAG_TESTTYPE: %d\n", VLAN_UNTAG_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "VLAN_DBL_TAG_TESTTYPE: %d\n", VLAN_DBL_TAG_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "VLAN_DBL_UNTAG_TESTTYPE: %d\n", VLAN_DBL_UNTAG_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "IPCS_INSERT_TESTTYPE: %d\n", IPCS_INSERT_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "IPCS_CHECK_TESTTYPE: %d\n", IPCS_CHECK_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "BACP_PKT_TESTTYPE: %d\n", BACP_PKT_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "RUNT_PKT_TESTTYPE: %d\n", RUNT_PKT_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "LONG_PKT_TESTTYPE: %d\n", LONG_PKT_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "CRCERR_PKT_TESTTYPE: %d\n", CRCERR_PKT_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "DATA_BURST_TESTTYPE: %d\n", DATA_BURST_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "MULTI_CHANNEL_TESTTYPE: %d\n", MULTI_CHANNEL_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "SINGLE_PKT_TESTTYPE: %d\n", SINGLE_PKT_TESTTYPE); CHK_BUF(); index += sprintf(buf+index, "ALL_LOOPBACK_TESTTYPE: %d\n\n", ALL_LOOPBACK_TESTTYPE); CHK_BUF(); *eof = 1; done: *start = buf + (off - begin); index -= (off - begin); if (index < 0) index = 0; if (index > count) index = count; return index; } int loopback_proc_init(void) { struct proc_dir_entry *ptmProc; ptmProc = create_proc_entry("tc3162/ptm_loopback_point", 0, NULL); if (!ptmProc) { printk("\nFAILED: create proc for ptm_loopback_point\n"); return -ENOMEM; } ptmProc->write_proc = ptm_loopbackPoint_write_proc; ptmProc = create_proc_entry("tc3162/ptm_loopback_test", 0, NULL); if (!ptmProc) { printk("\nFAILED: create proc for ptm_loopback_test\n"); return -ENOMEM; } ptmProc->read_proc = ptm_loopbackTest_read_proc; ptmProc->write_proc = ptm_loopbackTest_write_proc; ptmProc = create_proc_entry("tc3162/ptm_loopback_stopTest", 0, NULL); if (!ptmProc) { printk("\nFAILED: create proc for ptm_loopback_stopTes\n"); return -ENOMEM; } ptmProc->write_proc = ptm_loopbackStopTest_write_proc; ptmProc = create_proc_entry("tc3162/ptm_loopback_setPktSize", 0, NULL); if (!ptmProc) { printk("\nFAILED: create proc for ptm_loopback_setPktSize\n"); return -ENOMEM; } ptmProc->write_proc = ptm_loopbackSetPktSize_write_proc; ptmProc = create_proc_entry("tc3162/ptm_loopback_bacpHdrSet", 0, NULL); if (!ptmProc) { printk("\nFAILED: create proc for ptm_loopback_bacpHdrSet\n"); return -ENOMEM; } ptmProc->write_proc = ptm_loopbackBacpHdrSet_write_proc; ptmProc = create_proc_entry("tc3162/ptm_loopback_bacpRegSet", 0, NULL); if (!ptmProc) { printk("\nFAILED: create proc for ptm_loopback_bacpRegSet\n"); return -ENOMEM; } ptmProc->write_proc = ptm_loopbackBacpRegSet_write_proc; ptmProc = create_proc_entry("tc3162/ptm_loopback_pathRangeSet", 0, NULL); if (!ptmProc) { printk("\nFAILED: create proc for ptm_loopback_pathRangeSet\n"); return -ENOMEM; } ptmProc->write_proc = ptm_loopbackPathRangeSet_write_proc; ptmProc = create_proc_entry("tc3162/ptm_pathIdSet", 0, NULL); if (!ptmProc) { printk("\nFAILED: create proc for ptm_pathIdSet\n"); return -ENOMEM; } ptmProc->write_proc = ptm_pathId_write_proc; return 0; } void loopback_proc_remove(void) { remove_proc_entry("tc3162/ptm_loopback_point", 0); remove_proc_entry("tc3162/ptm_loopback_test", 0); remove_proc_entry("tc3162/ptm_loopback_stopTest", 0); remove_proc_entry("tc3162/ptm_loopback_setPktSize", 0); remove_proc_entry("tc3162/ptm_loopback_bacpHdrSet", 0); remove_proc_entry("tc3162/ptm_loopback_bacpRegSet", 0); remove_proc_entry("tc3162/ptm_loopback_pathRangeSet", 0); remove_proc_entry("tc3162/ptm_pathIdSet", 0); return; } /* check if packet payload is correct */ static int rxContent_check( uint8 *txData, int offset, uint16 txLen, uint8 baseVal, uint8 type ) { int k; int pktType = type & 0xf; for (k = offset; k < txLen; k++) { if (txData[k] != baseVal) { printk("\nFAILED: (pkt:%d)\n" "txData[%d]:%02X != baseVal:%02X\n", dataPathRxPkts, k, txData[k], baseVal); return -1; } if (pktType == 0 || pktType == 1) { if (baseVal == 0xff) baseVal = 0; else baseVal++; } } return 0; } static int ptm_loopback_singlePkt_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { uint8 *txData; uint8 type; uint8 baseVal; uint16 txLen; txData = skb->data; type = txData[14]; baseVal = txData[15]; txLen = *(uint16*) (&txData[16]); if (rxContent_check(txData, 20, txLen, baseVal, type)) return -1; dataPathRxPkts++; printk("\nsinglePkt RX OK with pktLen:%d\n", (int)txLen); return 0; } static int ptm_loopback_dataPath_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { int path; uint8 *txData; uint8 type; uint8 baseVal; uint16 txLen; path = rxMsg->rxMsgW0.bits.pathNo & 0xf; txData = skb->data; type = txData[14]; baseVal = txData[15]; txLen = *(uint16*) (&txData[16]); if (txData[18] != DATA_PATH_TESTTYPE) { printk("\nFAILED: %s: (path:%d)\n" "txData[18]:%02X != DATA_PATH_TESTTYPE\n", __FUNCTION__, path, txData[18]); return -1; } if (rxContent_check(txData, 20, txLen, baseVal, type)) return -1; dataPathRxPkts++; if ((dataPathRxPkts & 0xffff) != 0xffff) { PTM_DBG(DBG_L1, "%s: %d pkts recvd\n\n", __FUNCTION__, dataPathRxPkts); } else printk("%s: %d pkts recvd\n\n", __FUNCTION__, dataPathRxPkts); /* when the packet is received, un-lock txHold * and then wake up Tx to send next packet */ rxWakeUpTx(); return 0; } static int ptm_loopback_dataBurst_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { int path; uint8 *txData; uint8 type; uint8 baseVal; uint16 txLen; path = rxMsg->rxMsgW0.bits.pathNo & 0xf; txData = skb->data; type = txData[14]; baseVal = txData[15]; txLen = *(uint16*) (&txData[16]); if (txData[18] != DATA_BURST_TESTTYPE) { printk("\nFAILED: %s: (path:%d)\n" "txData[18]:%02X != DATA_BURST_TESTTYPE\n", __FUNCTION__, path, txData[18]); return -1; } if ((txData[19] & 0xf) != path) { printk("\nFAILED: %s:\n" "(txData[19] & 0xf):%d != path:%d\n", __FUNCTION__, (int)(txData[19] & 0xf), path); return -1; } if (rxContent_check(txData, 20, txLen, baseVal, type)) return -1; testPktCnt++; dataPathRxPkts++; PTM_DBG(DBG_L1, "%s: %d pkts recvd\n\n", __FUNCTION__, dataPathRxPkts); //turn on QDMA when all packets are received. if ((testPktCnt-1) == (TX_QUEUE_NUM * TX_BURST_LEN)) { printk("\ndataBurst test for path%d is finished\n\n", path); qdmaDmaAvailable = 1; } return 0; } static int ptm_loopback_multiChannel_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { int path; uint8 *txData; uint8 type; uint8 baseVal; uint16 txLen; path = rxMsg->rxMsgW0.bits.pathNo & 0xf; txData = skb->data; type = txData[14]; baseVal = txData[15]; txLen = *(uint16*) (&txData[16]); if (txData[18] != MULTI_CHANNEL_TESTTYPE) { printk("\nFAILED: %s: (path:%d)\n" "txData[18]:%02X != MULTI_CHANNEL_TESTTYPE\n", __FUNCTION__, path, txData[18]); return -1; } if ((txData[19] & 0xf) != path) { printk("\nFAILED: %s:\n" "(txData[19] & 0xf):%d != path:%d\n", __FUNCTION__, (int)(txData[19] & 0xf), path); return -1; } if (rxContent_check(txData, 20, txLen, baseVal, type)) return -1; testPktCnt++; dataPathRxPkts++; PTM_DBG(DBG_L1, "%s: %d pkts recvd\n\n", __FUNCTION__, dataPathRxPkts); if ((testPktCnt-1) == 2) qdmaDmaAvailable = 1; return 0; } static int ptm_loopback_pathNo_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { int path; uint8 *txData; uint8 type; uint8 baseVal; uint16 txLen; path = rxMsg->rxMsgW0.bits.pathNo; txData = skb->data; type = txData[14]; baseVal = txData[15]; txLen = *(uint16*) (&txData[16]); if (txData[18] != PATH_NO_TESTTYPE) { printk("\nFAILED: %s: (path:%d)\n" "txData[18]:%02X != PATH_NO_TESTTYPE\n", __FUNCTION__, path, txData[18]); return -1; } if (path != (txData[19] & 0xf)) { printk("\nFAILED: %s:\n" "path:%d != (txData[19] & 0xf):%d\n", __FUNCTION__, path, (int)(txData[19] & 0xf)); return -1; } if (rxContent_check(txData, 20, txLen, baseVal, type)) return -1; dataPathRxPkts++; PTM_DBG(DBG_L1, "%s: %d pkts recvd\n", __FUNCTION__, dataPathRxPkts); /* when the packet is received, un-lock txHold * and then wake up Tx to send next packet */ rxWakeUpTx(); return 0; } /* check if all preemption packets are received * before all normal packets are comming */ static int ptm_loopback_preemption_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { int path; int preemption; uint8 *txData; uint8 baseVal; uint16 txLen; path = rxMsg->rxMsgW0.bits.pathNo; preemption = (path & 0x1); txData = skb->data; baseVal = txData[15]; txLen = *(uint16*) (&txData[16]); if (txData[18] != PREEMPTION_TESTTYPE) { printk("\nFAILED: %s: (path:%d)\n" "txData[18]:%02X != PREEMPTION_TESTTYPE\n", __FUNCTION__, path, txData[18]); return -1; } if (path != (txData[19] & 0xf)) { printk("\nFAILED: %s:\n" " path:%d != (txData[19] & 0xf):%d\n", __FUNCTION__, path, (int)(txData[19] & 0xf)); return -1; } if (rxContent_check(txData, 20, txLen, baseVal, 1)) return -1; if (preemption) { rxPreemptionPkts++; PTM_DBG(DBG_L1, "\nPreemption pkt:%d recevied\n", rxPreemptionPkts); } else { dataPathRxPkts++; //normal packets PTM_DBG(DBG_L1, "\nNormal pkt:%d recevied\n", dataPathRxPkts); } if (rxPreemptionPkts == 4) { rxPreemptionPkts++; //prevent to come here again. if (dataPathRxPkts >= 60) { printk("\nFailed: Preemption test\n"); return -1; } } if ((rxPreemptionPkts + dataPathRxPkts) == 65) { PTM_DBG(DBG_L1, "\nPreemption Rx OK\n"); qdmaDmaAvailable = 1; } return 0; } /* check if packet comming sequence is * (TX_BURST_LEN packets for txq7) -> * (TX_BURST_LEN packets for txq6) -> * ............................. * (TX_BURST_LEN packets for txq0) */ static int ptm_loopback_spPriority_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { int path, txq; uint8 *txData; uint8 baseVal; uint16 txLen; path = rxMsg->rxMsgW0.bits.pathNo; txData = skb->data; baseVal = txData[15]; txLen = *(uint16*) (&txData[16]); txq = ((txData[19] >> 4) & 0xf); if (txData[18] != SP_PRIORITY_TESTTYPE) { printk("\nFAILED: %s: (path:%d)\n" "txData[18]:%02X != SP_PRIORITY_TESTTYPE\n", __FUNCTION__, path, txData[18]); return -1; } if (path != (txData[19] & 0xf)) { printk("\nFAILED: %s:\n" " path:%d != (txData[19] & 0xf):%d\n", __FUNCTION__, path, (int)(txData[19] & 0xf)); return -1; } /* check if rx packets' priority is p7>p6>...>p0 */ //txq7 pkts expected if (testPktCnt <= (TX_BURST_LEN * 1)) { if (txq != 7) { printk("\nFAILED: pkt:%d should be txq7 pkt, not txq%d pkt\n", testPktCnt, txq); return -1; } if (testPktCnt == (TX_BURST_LEN * 1)) curTxq -= 1; } //txq6 pkts expected else if (((TX_BURST_LEN * 1) < testPktCnt) && (testPktCnt <= (TX_BURST_LEN << 1))) { if (txq != 6) { printk("\nFAILED: pkt:%d should be txq6 pkt, not txq%d pkt\n", testPktCnt, txq); return -1; } if (testPktCnt == (TX_BURST_LEN << 1)) curTxq -= 1; } //txq5 pkts expected else if (((TX_BURST_LEN << 1) < testPktCnt) && (testPktCnt <= (TX_BURST_LEN * 3))) { if (txq != 5) { printk("\nFAILED: pkt:%d should be txq5 pkt, not txq%d pkt\n", testPktCnt, txq); return -1; } if (testPktCnt == (TX_BURST_LEN * 3)) curTxq -= 1; } //txq4 pkts expected else if (((TX_BURST_LEN * 3) < testPktCnt) && (testPktCnt <= (TX_BURST_LEN << 2))) { if (txq != 4) { printk("\nFAILED: pkt:%d should be txq4 pkt, not txq%d pkt\n", testPktCnt, txq); return -1; } if (testPktCnt == (TX_BURST_LEN << 2)) curTxq -= 1; } //txq3 pkts expected else if (((TX_BURST_LEN << 2) < testPktCnt) && (testPktCnt <= (TX_BURST_LEN * 5))) { if (txq != 3) { printk("\nFAILED: pkt:%d should be txq3 pkt, not txq%d pkt\n", testPktCnt, txq); return -1; } if (testPktCnt == (TX_BURST_LEN * 5)) curTxq -= 1; } //txq2 pkts expected else if (((TX_BURST_LEN * 5) < testPktCnt) && (testPktCnt <= (TX_BURST_LEN * 6))) { if (txq != 2) { printk("\nFAILED: pkt:%d should be txq2 pkt, not txq%d pkt\n", testPktCnt, txq); return -1; } if (testPktCnt == (TX_BURST_LEN * 6)) curTxq -= 1; } //txq1 pkts expected else if (((TX_BURST_LEN * 6) < testPktCnt) && (testPktCnt <= (TX_BURST_LEN * 7))) { if (txq != 1) { printk("\nFAILED: pkt:%d should be txq1 pkt, not txq%d pkt\n", testPktCnt, txq); return -1; } if (testPktCnt == (TX_BURST_LEN * 7)) curTxq -= 1; } //txq0 pkts expected else if (((TX_BURST_LEN * 7) < testPktCnt) && (testPktCnt <= (TX_BURST_LEN << 3))) { if (txq != 0) { printk("\nFAILED: pkt:%d should be txq0 pkt, not txq%d pkt\n", testPktCnt, txq); return -1; } if (testPktCnt == (TX_BURST_LEN << 3)) curTxq -= 1; } //unknown pkts else { printk("\nFAILED: pkt:%d is not known pkt (txq:%d)\n", testPktCnt, txq); return -1; } if (rxContent_check(txData, 20, txLen, baseVal, 1)) return -1; testPktCnt++; dataPathRxPkts++; PTM_DBG(DBG_L1, "%s: %d pkts (txq%d) recvd\n", __FUNCTION__, dataPathRxPkts, txq); if (testPktCnt == (TX_QUEUE_NUM * TX_BURST_LEN)) { printk("\nspPriority test for path%d is finished\n\n", path); qdmaDmaAvailable = 1; } return 0; } /* check if packet comming sequence is * txq0 -> txq1 -> txq2 -> .... -> txq7 -> * txq1 -> txq2 -> .... -> txq7 -> * txq2 -> txq3 -> .... -> txq7 -> * ........................... * txq7 -> * txq0 -> txq1 -> txq2 -> .... -> txq7 -> * ............................ */ static int ptm_loopback_wrrPriority_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { int path, txq; uint8 *txData; uint8 baseVal; uint16 txLen; path = rxMsg->rxMsgW0.bits.pathNo; txData = skb->data; baseVal = txData[15]; txLen = *(uint16*) (&txData[16]); txq = ((txData[19] >> 4) & 0xf); if (txData[18] != WRR_PRIORITY_TESTTYPE) { printk("\nFAILED: %s: (path:%d)\n" "txData[18]:%02X != WRR_PRIORITY_TESTTYPE\n", __FUNCTION__, path, txData[18]); return -1; } if (path != (txData[19] & 0xf)) { printk("\nFAILED: %s:\n" " path:%d != (txData[19] & 0xf):%d\n", __FUNCTION__, path, (int)(txData[19] & 0xf)); return -1; } if (isWrrFirstTest[path]) { dataPathRxPkts++; PTM_DBG(DBG_L1, "%d pkts (path%d txq%d) recvd\n", dataPathRxPkts, path, txq); if (dataPathRxPkts == TX_QUEUE_NUM) { printk("\nWRR first Test for path%d is finished\n\n", path); qdmaDmaAvailable = 1; } return 0; } switch (wrrQueuePhase) { case 7: //txq7 pkts case 6: //txq6 pkts case 5: //txq5 pkts case 4: //txq4 pkts case 3: //txq3 pkts case 2: //txq2 pkts case 1: //txq1 pkts case 0: //txq0 pkts if (wrrQueuePhase != txq) { printk("\nFAILED: pkt:%d should be txq%d pkt, not txq%d pkt\n", dataPathRxPkts, wrrQueuePhase, txq); return 0; } wrrQueuePhase++; if (wrrQueuePhase == TX_QUEUE_NUM) { wrrQueueStart++; if (wrrQueueStart == TX_QUEUE_NUM) wrrQueueStart = 0; wrrQueuePhase = wrrQueueStart; } break; default: //unKnown pkts printk("\nFAILED: pkt:%d is not known pkt\n", dataPathRxPkts); return -1; } if (rxContent_check(txData, 20, txLen, baseVal, 1)) return -1; dataPathRxPkts++; PTM_DBG(DBG_L1, "%s: %d pkts (txq%d) recvd\n", __FUNCTION__, dataPathRxPkts, txq); if (dataPathRxPkts == (txqWrrTotalVal<<3)) { printk("\nWRR test for path%d is finished\n\n", path); qdmaDmaAvailable = 1; } return 0; } /* check if packet comming sequence is * (TX_BURST_LEN packets for txq7) -> * (TX_BURST_LEN packets for txq6) -> * (TX_BURST_LEN packets for txq5) -> * txq0 -> txq1 -> txq2 -> txq3 -> txq4 -> * txq1 -> txq2 -> txq3 -> txq4 -> * txq2 -> txq3 -> txq4 -> * txq3 -> txq4 -> * txq4 -> * txq0 -> txq1 -> txq2 -> txq3 -> txq4 -> * ............................ */ static int ptm_loopback_spWrr_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { int path, txq; uint8 *txData; uint8 baseVal; uint16 txLen; path = rxMsg->rxMsgW0.bits.pathNo; txData = skb->data; baseVal = txData[15]; txLen = *(uint16*) (&txData[16]); txq = ((txData[19] >> 4) & 0xf); if (txData[18] != SP_WRR_TESTTYPE) { printk("\nFAILED: %s: (path:%d)\n" "txData[18]:%02X != SP_WRR_TESTTYPE\n", __FUNCTION__, path, txData[18]); return -1; } if (path != (txData[19] & 0xf)) { printk("\nFAILED: %s:\n" " path:%d != (txData[19] & 0xf):%d\n", __FUNCTION__, path, (int)(txData[19] & 0xf)); return -1; } if (isWrrFirstTest[path]) { dataPathRxPkts++; PTM_DBG(DBG_L1, "%d pkts (path%d txq%d) recvd\n", dataPathRxPkts, path, txq); if (dataPathRxPkts == TX_QUEUE_NUM) { printk("\nSP_WRR first Test for WRR for path%d is finished\n\n", path); qdmaDmaAvailable = 1; } return 0; } //txq7 pkts expected if (testPktCnt <= (TX_BURST_LEN * 1)) { if (txq != 7) { printk("\nFAILED: pkt:%d should be txq7 pkt," " not txq%d pkt\n", testPktCnt, txq); return -1; } if (testPktCnt == (TX_BURST_LEN * 1)) curTxq -= 1; } //txq6 pkts expected else if (((TX_BURST_LEN * 1) < testPktCnt) && (testPktCnt <= (TX_BURST_LEN << 1))) { if (txq != 6) { printk("\nFAILED: pkt:%d should be txq6 pkt," " not txq%d pkt\n", testPktCnt, txq); return -1; } if (testPktCnt == (TX_BURST_LEN << 1)) curTxq -= 1; } //txq5 pkts expected else if (((TX_BURST_LEN << 1) < testPktCnt) && (testPktCnt <= (TX_BURST_LEN * 3))) { if (txq != 5) { printk("\nFAILED: pkt:%d should be txq5 pkt," " not txq%d pkt\n", testPktCnt, txq); return -1; } if (testPktCnt == (TX_BURST_LEN * 3)) curTxq -= 1; } //txq4~txq0 pkts expected for WRR else { switch (wrrQueuePhase) { case 4: //txq4 pkts case 3: //txq3 pkts case 2: //txq2 pkts case 1: //txq1 pkts case 0: //txq0 pkts if (txq != wrrQueuePhase) { printk("\nFAILED: pkt:%d should be txq%d pkt," "not txq%d pkt\n", dataPathRxPkts, wrrQueuePhase, txq); return 0; } wrrQueuePhase++; if (wrrQueuePhase == 5) { wrrQueueStart++; if (wrrQueueStart == 5) wrrQueueStart = 0; wrrQueuePhase = wrrQueueStart; } break; default: //not known pkts printk("\nFAILED: pkt:%d is not known pkt\n", dataPathRxPkts); return -1; } } if (rxContent_check(txData, 20, txLen, baseVal, 1)) return -1; testPktCnt++; dataPathRxPkts++; PTM_DBG(DBG_L1, "%s: %d pkts (txq%d) recvd\n", __FUNCTION__, dataPathRxPkts, txq); if (dataPathRxPkts == ((txqWrrTotalVal*12)+(3*TX_BURST_LEN))) { printk("\nSP_WRR RX for path%d is finished\n\n", path); qdmaDmaAvailable = 1; } return 0; } static int ptm_loopback_vlanTag_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { uint8 *txData; uint8 type; uint8 baseVal; uint16 txLen, vlanTag = 0; int path; txData = skb->data; path = rxMsg->rxMsgW0.bits.pathNo; if (*(uint16*)(&txData[12]) == ETHER_TYPE_8021Q) { vlanTag = (*(uint16*) (&txData[14])) & 0x1fff; txData += 4; //vlanTag shifts 4 bytes! (*(uint16*) (&txData[16])) -= 4; if (((txData[19]>>4) & 0x1) == 0) { printk("\nFAILED: %s: HW shouldn't insert VLAN tag!\n", __FUNCTION__); return -1; } } else //ETHER_TYPE_IP { if (((txData[19]>>4) & 0x1)) { printk("\nFAILED: %s: HW should insert VLAN tag!\n", __FUNCTION__); return -1; } } type = txData[14]; baseVal = txData[15]; txLen = (*(uint16*) (&txData[16])); if (txData[18] != VLAN_TAG_TESTTYPE) { printk("\nFAILED: %s:\n" "txData[18]:%02X != VLAN_TAG_TESTTYPE\n", __FUNCTION__, txData[18]); return -1; } if (((txData[19]>>4) & 0x1)) { if (vlanTag != (*(uint16*) (&txData[20]))) { printk("\nFAILED: %s:\n" "vlanTag:%d != (*(uint16*) (&txData[20])):%d\n", __FUNCTION__, vlanTag, (*(uint16*) (&txData[20]))); return -1; } } if ((txData[19] & 0xf) != path) { printk("\nFAILED: %s:\n" "(txData[19]&0xf):%02X != path:%d\n", __FUNCTION__, txData[19]&0xf, path); return -1; } if (rxContent_check(txData, 22, txLen, baseVal, type)) return -1; dataPathRxPkts++; PTM_DBG(DBG_L1, "%s: %d pkts recvd\n", __FUNCTION__, dataPathRxPkts); /* when the packet is received, un-lock txHold * and then wake up Tx to send next packet */ rxWakeUpTx(); return 0; } static int ptm_loopback_vlanUnTag_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { uint8 *txData; uint8 type; uint8 baseVal; uint16 txLen; uint16 vlanTag = 0; int path; txData = skb->data; type = txData[14]; baseVal = txData[15]; txLen = *(uint16*) (&txData[16]); path = rxMsg->rxMsgW0.bits.pathNo; if (txData[18] != VLAN_UNTAG_TESTTYPE) { printk("\nFAILED: %s:\n" "txData[18]:%02X != VLAN_UNTAG_TESTTYPE\n", __FUNCTION__, txData[18]); return -1; } if ((txData[19] & 0xf) != path) { printk("\nFAILED: %s:\n" "(txData[19]&0xf):%02X != path:%d\n", __FUNCTION__, txData[19]&0xf, path); return -1; } if (((txData[19]>>4) & 0x1)) { if (!rxMsg->rxMsgW2.bits.vlanHit) { printk("\nFAILED: %s: vlanHit bit should be set!\n", __FUNCTION__); return -1; } if (rxMsg->rxMsgW2.bits.vlanTpID != 0) { printk("\nFAILED: %s: vlanTpId:%d should be 0 (for 0x8100)!\n", __FUNCTION__, rxMsg->rxMsgW2.bits.vlanTpID); return -1; } vlanTag = (*(uint16*) (&txData[20])) & 0x1fff; if ((rxMsg->rxMsgW2.bits.vlanTag & 0x1fff) != vlanTag) { printk("\nFAILED: %s\n" "rxMsg->rxMsgW2.vlanTag:%.8x != vlanTag:%.8x", __FUNCTION__, rxMsg->rxMsgW2.bits.vlanTag & 0x1fff, vlanTag); return -1; } } else { if (rxMsg->rxMsgW2.bits.vlanHit) { printk("\nFAILED: %s: vlanHit bit shouldn't be set!\n", __FUNCTION__); return -1; } } if (rxContent_check(txData, 22, txLen, baseVal, type)) return -1; dataPathRxPkts++; PTM_DBG(DBG_L1, "%s: %d pkts recvd\n", __FUNCTION__, dataPathRxPkts); /* when the packet is received, un-lock txHold * and then wake up Tx to send next packet */ rxWakeUpTx(); return 0; } static int ptm_loopback_vlanDblTag_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { /* only packets with ETHER_TYPE_8021AD, ETHER_TYPE_QINQ, * or ETHER_TYPE_IP can go into this funation */ uint8 *txData; uint8 type; uint8 baseVal; uint16 txLen, vlanTag = 0; int path; txData = skb->data; path = rxMsg->rxMsgW0.bits.pathNo; if (*(uint16*)(&txData[12]) == ETHER_TYPE_8021AD) { vlanTag = (*(uint16*) (&txData[14])) & 0x1fff; if ((*(uint16*)(&txData[16]) != ETHER_TYPE_8021Q) || (*(uint16*)(&txData[18]) != 0x1234)) { printk("\nFAILED: %s: 8021Q tagId should be 0x1234!\n", __FUNCTION__); return -1; } txData += 8; //vlanTag shifts 8 bytes! (*(uint16*) (&txData[16])) -= 8; if ((((txData[19]>>4)&0x3) != 1)) { printk("\nFAILED: %s: HW skhould insert 8021AD tag!\n", __FUNCTION__); return -1; } } else if (*(uint16*)(&txData[12]) == ETHER_TYPE_QINQ) { vlanTag = (*(uint16*) (&txData[14])) & 0x1fff; if ((*(uint16*)(&txData[16]) != ETHER_TYPE_8021Q) || (*(uint16*)(&txData[18]) != 0x1567)) { printk("\nFAILED: %s: 8021Q tagId should be 0x1567!\n", __FUNCTION__); return -1; } txData += 8; //vlanTag shifts 8 bytes! (*(uint16*) (&txData[16])) -= 8; if ((((txData[19]>>4)&0x3) != 3)) { printk("\nFAILED: %s: HW should insert QinQ tag!\n", __FUNCTION__); return -1; } } else //ETHER_TYPE_IP { if ((((txData[19]>>4)&0x3) != 0) && (((txData[19]>>4)&0x3) != 2)) { printk("\nFAILED: %s: HW should insert DBL VLAN tag!\n", __FUNCTION__); return -1; } } type = txData[14]; baseVal = txData[15]; txLen = (*(uint16*) (&txData[16])); if (txData[18] != VLAN_DBL_TAG_TESTTYPE) { printk("\nFAILED: %s:\n" "txData[18]:%02X != VLAN_DBL_TAG_TESTTYPE\n", __FUNCTION__, txData[18]); return -1; } if ((txData[19] & 0xf) != path) { printk("\nFAILED: %s:\n" "(txData[19]&0xf):%02X != path:%d\n", __FUNCTION__, txData[19]&0xf, path); return -1; } if ((((txData[19]>>4)&0x3) == 1) || (((txData[19]>>4)&0x3) == 3)) { if (vlanTag != (*(uint16*) (&txData[20]))) { printk("\nFAILED: %s:\n" "vlanTag:%d != (*(uint16*) (&txData[20])):%d\n", __FUNCTION__, vlanTag, (*(uint16*) (&txData[20]))); return -1; } } if (rxContent_check(txData, 22, txLen, baseVal, type)) return -1; dataPathRxPkts++; PTM_DBG(DBG_L1, "%s: %d pkts recvd\n", __FUNCTION__, dataPathRxPkts); /* when the packet is received, un-lock txHold * and then wake up Tx to send next packet */ rxWakeUpTx(); return 0; } static int ptm_loopback_vlanDblUnTag_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { /* only packets with ETHER_TYPE_8021Q * or ETHER_TYPE_IP can go into this funation */ uint8 *txData; uint8 type; uint8 baseVal; uint16 txLen; uint16 vTag = 0; uint16 vlanTag = 0; int path; txData = skb->data; path = rxMsg->rxMsgW0.bits.pathNo; if (*(uint16*)(&txData[12]) == ETHER_TYPE_8021Q) { vTag = *(uint16*)(&txData[14]); txData += 4; } type = txData[14]; baseVal = txData[15]; txLen = *(uint16*) (&txData[16]); if (txData[18] != VLAN_DBL_UNTAG_TESTTYPE) { printk("\nFAILED: %s:\n" "txData[18]:%02X != VLAN_DBL_UNTAG_TESTTYPE\n", __FUNCTION__, txData[18]); return -1; } if ((txData[19] & 0xf) != path) { printk("\nFAILED: %s:\n" "(txData[19]&0xf):%02X != path:%d\n", __FUNCTION__, txData[19]&0xf, path); return -1; } if (((txData[19]>>4)&0x3) == 1) { if (vTag != 0x189a) { printk("\nFAILED: %s: 8021Q tagId should be 0x189a!\n", __FUNCTION__); return -1; } if (!rxMsg->rxMsgW2.bits.vlanHit) { printk("\nFAILED (TPID_0x88a8): %s: vlanHit bit should be set!\n", __FUNCTION__); return -1; } if (rxMsg->rxMsgW2.bits.vlanTpID != 1) { printk("\nFAILED: %s: vlanTpId should be 1!\n", __FUNCTION__); return -1; } vlanTag = (*(uint16*) (&txData[20])) & 0x1fff; if ((rxMsg->rxMsgW2.bits.vlanTag & 0x1fff) != vlanTag) { printk("\nFAILED (TPID_0x88a8): %s\n" "rxMsg->rxMsgW2.vlanTag:%.8x != vlanTag:%.8x", __FUNCTION__, rxMsg->rxMsgW2.bits.vlanTag & 0x1fff, vlanTag); return -1; } txLen -= 4; } else if (((txData[19]>>4)&0x3) == 3) { if ((((txData[19]>>4)&0x3) == 3) && (vTag != 0x1bcd)) { printk("\nFAILED: %s: 8021Q tagId should be 0x1bcd!\n", __FUNCTION__); return -1; } if (!rxMsg->rxMsgW2.bits.vlanHit) { printk("\nFAILED (TPID_0x9100): %s: vlanHit bit should be set!\n", __FUNCTION__); return -1; } if (rxMsg->rxMsgW2.bits.vlanTpID != 2) { printk("\nFAILED: %s: vlanTpId should be 2!\n", __FUNCTION__); return -1; } vlanTag = (*(uint16*) (&txData[20])) & 0x1fff; if ((rxMsg->rxMsgW2.bits.vlanTag & 0x1fff) != vlanTag) { printk("\nFAILED (TPID_0x9100): %s\n" "rxMsg->rxMsgW2.vlanTag:%.8x != vlanTag:%.8x", __FUNCTION__, rxMsg->rxMsgW2.bits.vlanTag & 0x1fff, vlanTag); return -1; } txLen -= 4; } else { if (rxMsg->rxMsgW2.bits.vlanHit) { printk("\nFAILED: %s: vlanHit bit shouldn't be set!\n", __FUNCTION__); return -1; } } if (rxContent_check(txData, 22, txLen, baseVal, type)) return -1; dataPathRxPkts++; PTM_DBG(DBG_L1, "%s: %d pkts recvd\n", __FUNCTION__, dataPathRxPkts); /* when the packet is received, un-lock txHold * and then wake up Tx to send next packet */ rxWakeUpTx(); return 0; } static int ptm_loopback_ipCsInsert_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { uint8 *txData; uint8 type; uint8 baseVal; uint16 txLen, ipCs = 0; unsigned short chksum; int path; txData = skb->data; path = rxMsg->rxMsgW0.bits.pathNo; //txData[14] is changed in TX, so don't use. type = RAN_PKTTYPE; baseVal = txData[15]; txLen = (*(uint16*) (&txData[16])); if (txData[18] != IPCS_INSERT_TESTTYPE) { printk("\nFAILED: %s:\n" "txData[18]:%02X != IPCS_INSERT_TESTTYPE\n", __FUNCTION__, txData[18]); return -1; } if ((txData[19] & 0xf) != path) { printk("\nFAILED: %s:\n" "(txData[19]&0xf):%02X != path:%d\n", __FUNCTION__, txData[19]&0xf, path); return -1; } if ((txData[19]>>4)&0x1) { ipCs = (*(uint16*) (&txData[24])); (*(uint16*) (&txData[24])) = 0; chksum = in_csum((unsigned short *) &txData[14], 20); if (ipCs != chksum) { printk("\nFAILED: %s:\n" "ipCs:%.4x != chksum:%.4x\n", __FUNCTION__, ipCs, chksum); return -1; } } else { if ((*(uint16*) (&txData[24])) != 0) { printk("\nFAILED: %s:\n" "txData[24-25]:%.4x should be 0\n", __FUNCTION__, *(uint16*) (&txData[24])); return -1; } } if (rxContent_check(txData, 26, txLen, baseVal, type)) return -1; dataPathRxPkts++; PTM_DBG(DBG_L1, "%s: %d pkts recvd\n", __FUNCTION__, dataPathRxPkts); /* when the packet is received, un-lock txHold * and then wake up Tx to send next packet */ rxWakeUpTx(); return 0; } static int ptm_loopback_ipCsCheck_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { uint8 *txData; uint8 type; uint8 baseVal; uint16 txLen; int path; txData = skb->data; path = rxMsg->rxMsgW0.bits.pathNo; //txData[14] is changed in ipCsCheck_tx, so don't use. type = RAN_PKTTYPE; baseVal = txData[15]; txLen = (*(uint16*) (&txData[16])); if (txData[18] != IPCS_CHECK_TESTTYPE) { printk("\nFAILED: %s:\n" "txData[18]:%02X != IPCS_CHECK_TESTTYPE\n", __FUNCTION__, txData[18]); return -1; } if ((txData[19] & 0xf) != path) { printk("\nFAILED: %s:\n" "(txData[19]&0xf):%02X != path:%d\n", __FUNCTION__, txData[19]&0xf, path); return -1; } if ((txData[19]>>4)&0x1) { if (rxMsg->rxMsgW1.bits.ip4CsErr) { printk("\nFAILED: %s:\n" "ipCsErr bit shouldn't be set\n", __FUNCTION__); return -1; } } else { if (!rxMsg->rxMsgW1.bits.ip4CsErr) { printk("\nFAILED: %s:\n" "ipCsErr bit should be set\n", __FUNCTION__); return -1; } } if (rxContent_check(txData, 26, txLen, baseVal, type)) return -1; dataPathRxPkts++; PTM_DBG(DBG_L1, "%s: %d pkts recvd\n", __FUNCTION__, dataPathRxPkts); /* when the packet is received, un-lock txHold * and then wake up Tx to send next packet */ rxWakeUpTx(); return 0; } /* There are five parts for BACP header, which are * DST_MAC, ORG_SUB, ITU_OUI, ITU_SUB, VERSION. * Only if the BACP header matchs the enable parts * in BACP registers, the packet is for BACP. * Note: for disable parts, we don't care, so we * suoopse they are Hits */ static int ptm_loopback_bacpCheck_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { uint8 *txData; uint8 type; uint8 baseVal; uint16 txLen; int path; uint8 *bacpHdr = NULL, *regP = NULL; uint32 reg0, reg1, reg2, reg3, regEn; int macHit=0, orgHit=0, ituoHit=0, itusHit=0, bacpHit=0; txData = skb->data; path = rxMsg->rxMsgW0.bits.pathNo; reg0 = read_reg_word(PTM_BACP_FIELD_0); reg1 = read_reg_word(PTM_BACP_FIELD_1); reg2 = read_reg_word(PTM_BACP_FIELD_2); reg3 = read_reg_word(PTM_BACP_FIELD_3); regEn = read_reg_word(PTM_BACP_FIELD_EN); if ((!rxMsg->rxMsgW0.bits.isBacp && rxMsg->rxMsgW0.bits.isRaw) || (rxMsg->rxMsgW0.bits.isBacp && !rxMsg->rxMsgW0.bits.isRaw)) { printk("\nFAILED: isBacp bit & isRaw bit should both hit or un-hit at the same time\n"); return -1; } if (regEn & BACP_DST_MAC_EN) //Dest MAC check Enable { bacpHdr = (uint8 *)&bacpHeader[1]; regP = (uint8 *)&reg1; if (bacpHeader[0] == reg0 && bacpHdr[0] == regP[0] && bacpHdr[1] == regP[1]) macHit = 1; } else macHit = 1; //don't care if (regEn & BACP_ORG_SUB_EN) //Org SubType check Enable { bacpHdr = (uint8 *)&bacpHeader[2]; regP = (uint8 *)&reg2; if (bacpHdr[0] == regP[0]) orgHit = 1; } else orgHit = 1; //don't care if (regEn & BACP_ITU_OUI_EN) //ITU OUI check Enable { bacpHdr = (uint8 *)&bacpHeader[2]; regP = (uint8 *)&reg2; if (bacpHdr[1] == regP[1] && bacpHdr[2] == regP[2] && bacpHdr[3] == regP[3]) ituoHit = 1; } else ituoHit = 1; //dont care if (regEn & BACP_ITU_SUB_EN) //ITU SubType check Enable { bacpHdr = (uint8 *)&bacpHeader[3]; regP = (uint8 *)&reg3; if (bacpHdr[0] == regP[0]) itusHit = 1; } else itusHit = 1; //dont care if (regEn & BACP_VERSION_EN) //BACP version check Enable { bacpHdr = (uint8 *)&bacpHeader[3]; regP = (uint8 *)&reg3; if (bacpHdr[1] == regP[1]) bacpHit = 1; } else bacpHit = 1; //dont care if (*(uint16*)(&txData[12]) == ETHER_TYPE_SLOW) { /* Only if the BACP header matchs the enable parts * in BACP registers, the packet is for BACP */ if (macHit && orgHit && ituoHit && itusHit && bacpHit) { if (!rxMsg->rxMsgW0.bits.isBacp) { printk("\nFAILED: isBacp bit should be set\n"); return -1; } } else { if (rxMsg->rxMsgW0.bits.isBacp) { printk("\nFAILED: isBacp bit shouldn't be set\n" "macHit:%d, orgHit:%d, ituoHit:%d, itusHit:%d, bacpHit:%d\n", macHit, orgHit, ituoHit, itusHit, bacpHit); return -1; } } txData += 10; //shift 10 bytes (*(uint16*) (&txData[16])) -= 10; if (!((txData[19]>>4)&0x1)) { printk("\nFAILED: %s:\n" "This shouldn't be a BACP packet!\n", __FUNCTION__); } } else //ETHER_TYPE_IP { if (rxMsg->rxMsgW0.bits.isBacp) { regP = (uint8 *)&reg3; /* normal packets' path_no is in the position * of bacp version, so bacp hit may be * triggered, so double check. */ if (path != regP[1]) { printk("\nFAILED: %s: isBacp bit shouldn't be set for normal packet!\n", __FUNCTION__); return -1; } } if ((txData[19]>>4)&0x1) { printk("\nFAILED: %s:\n" "This should be a BACP packet!\n", __FUNCTION__); } } type = txData[14]; baseVal = txData[15]; txLen = (*(uint16*) (&txData[16])); if (txData[18] != BACP_PKT_TESTTYPE) { printk("\nFAILED: %s:\n" "txData[18]:%02X != BACP_PKT_TESTTYPE\n", __FUNCTION__, txData[18]); return -1; } if ((txData[19] & 0xf) != path) { printk("\nFAILED: %s:\n" "(txData[19]&0xf):%02X != path:%d\n", __FUNCTION__, txData[19]&0xf, path); return -1; } if (rxContent_check(txData, 20, txLen, baseVal, type)) return -1; dataPathRxPkts++; //PTM_DBG(DBG_L1, "%s: %d pkts recvd\n", __FUNCTION__, dataPathRxPkts); /* when the packet is received, un-lock txHold * and then wake up Tx to send next packet */ rxWakeUpTx(); return 0; } static int ptm_loopback_runtCheck_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { uint8 *txData; uint8 type; uint8 baseVal; uint16 txLen; int path; txData = skb->data; path = rxMsg->rxMsgW0.bits.pathNo; type = txData[14]; baseVal = txData[15]; txLen = (*(uint16*) (&txData[16])); if (txData[18] != RUNT_PKT_TESTTYPE) { printk("\nFAILED: %s:\n" "txData[18]:%02X != RUNT_PKT_TESTTYPE\n", __FUNCTION__, txData[18]); return -1; } if ((txData[19] & 0xf) != path) { printk("\nFAILED: %s:\n" "(txData[19]&0xf):%02X != path:%d\n", __FUNCTION__, txData[19]&0xf, path); return -1; } if ((txData[19]>>4)&0x1) { if (!rxMsg->rxMsgW0.bits.isRunt) { printk("\nFAILED: %s: isRunt bit should be set!\n", __FUNCTION__); return -1; } if (txLen > 59) { printk("\nFAILED: %s: txLen:%d is too long!\n", __FUNCTION__, txLen); return -1; } } else { if (rxMsg->rxMsgW0.bits.isRunt) { printk("\nFAILED: %s: isRunt bit shouldn't be set!\n", __FUNCTION__); return -1; } if (txLen < 60) { printk("\nFAILED: %s: txLen:%d is too short!\n", __FUNCTION__, txLen); return -1; } } if (rxContent_check(txData, 20, txLen, baseVal, type)) return -1; dataPathRxPkts++; PTM_DBG(DBG_L1, "%s: %d pkts recvd\n", __FUNCTION__, dataPathRxPkts); /* when the packet is received, un-lock txHold * and then wake up Tx to send next packet */ rxWakeUpTx(); return 0; } static int ptm_loopback_longCheck_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { uint8 *txData; uint8 type; uint8 baseVal; uint16 txLen; int path; txData = skb->data; path = rxMsg->rxMsgW0.bits.pathNo; type = txData[14]; baseVal = txData[15]; txLen = (*(uint16*) (&txData[16])); if (txData[18] != LONG_PKT_TESTTYPE) { printk("\nFAILED: %s:\n" "txData[18]:%02X != LONG_PKT_TESTTYPE\n", __FUNCTION__, txData[18]); return -1; } if ((txData[19] & 0xf) != path) { printk("\nFAILED: %s:\n" "(txData[19]&0xf):%02X != path:%d\n", __FUNCTION__, txData[19]&0xf, path); return -1; } if ((txData[19]>>4)&0x1) { if (!rxMsg->rxMsgW0.bits.isLong) { printk("\nFAILED: %s: isLong bit should be set!\n", __FUNCTION__); return -1; } if (!( (1515 <= txLen) && (txLen <= MAX_PKT_SIZE) )) { printk("\nFAILED: %s: txLen:%d is out of expectation!\n", __FUNCTION__, txLen); return -1; } } else { if (rxMsg->rxMsgW0.bits.isLong) { printk("\nFAILED: %s: isLong bit shouldn't be set!\n", __FUNCTION__); return -1; } if (txLen > 1514) { printk("\nFAILED: %s: txLen:%d is too long!\n", __FUNCTION__, txLen); return -1; } } if (rxContent_check(txData, 20, txLen, baseVal, type)) return -1; dataPathRxPkts++; PTM_DBG(DBG_L1, "%s: %d pkts recvd\n", __FUNCTION__, dataPathRxPkts); /* when the packet is received, un-lock txHold * and then wake up Tx to send next packet */ rxWakeUpTx(); return 0; } static int ptm_loopback_crcCheck_rx( ptmRxMsg_t *rxMsg, struct sk_buff *skb ) { uint8 *txData; uint8 type; uint8 baseVal; uint16 txLen; int path; txData = skb->data; path = rxMsg->rxMsgW0.bits.pathNo; type = txData[14]; baseVal = txData[15]; txLen = (*(uint16*) (&txData[16])); if (txData[18] != CRCERR_PKT_TESTTYPE) { printk("\nFAILED: %s:\n" "txData[18]:%02X != CRCERR_PKT_TESTTYPE\n", __FUNCTION__, txData[18]); return -1; } if ((txData[19] & 0xf) != path) { printk("\nFAILED: %s:\n" "(txData[19]&0xf):%02X != path:%d\n", __FUNCTION__, txData[19]&0xf, path); return -1; } if ((txData[19]>>4)&0x1) { if (!rxMsg->rxMsgW0.bits.crcErr) { printk("\nFAILED: %s: crcErr bit should be set!\n", __FUNCTION__); return -1; } } else { if (rxMsg->rxMsgW0.bits.crcErr) { printk("\nFAILED: %s: crcErr bit shouldn't be set!\n", __FUNCTION__); return -1; } } if (rxContent_check(txData, 20, txLen, baseVal, type)) return -1; dataPathRxPkts++; PTM_DBG(DBG_L1, "%s: %d pkts recvd\n", __FUNCTION__, dataPathRxPkts); /* when the packet is received, un-lock txHold * and then wake up Tx to send next packet */ rxWakeUpTx(); return 0; } /* the Rx entrance for loopback packets */ int ptm_loopback_rx( ptmRxMsg_t *rxMsg, uint32 rxMsgLen, struct sk_buff *skb, uint32 frameSize ) { uint8 *txData, *macAddr = &dstMacAddr[0]; int k; int lenOffset; if (rxMsg == NULL) { printk("\nERROR: rxMsg is NULL at %s\n", __FUNCTION__); goto stop_testing; } if (skb == NULL) { printk("\nERROR: skb is NULL at %s\n", __FUNCTION__); goto stop_testing; } txData = skb->data; //check rx msg len if (rxMsgLen != sizeof(ptmRxMsg_t)) { printk("\nWrong rxMsgLen:%d\n" "sizeof(ptmRxMsg_t):%d\n" , (int)rxMsgLen, sizeof(ptmRxMsg_t)); goto stop_testing; } //check rx CRC msg error if (!isCrcCheckTest && rxMsg->rxMsgW0.bits.crcErr) { printk("\nFAILED: CRC ERROR\n"); goto stop_testing; } //check destion mac if (*(uint16*)(&txData[12]) == ETHER_TYPE_SLOW) macAddr = (uint8 *)&bacpHeader[0]; for (k = 0; k < 6; k++) { if (txData[k] != macAddr[k]) { printk("\nWrong Dst MAC:\n"); printk("txData[0~5]: "); for (k = 0; k < 6; k++) printk("%02X ", txData[k]); printk("\ndstMacAddr: "); for (k = 0; k < 6; k++) printk("%02X ", macAddr[k]); printk("\n"); goto stop_testing; } } //check source mac for (k = 6; k < 12; k++) { if (txData[k] != defMacAddr[k-6]) { printk("\nWrong Src MAC:\n"); printk("txData[6~11]: "); for (k = 6; k < 12; k++) printk("%02X ", txData[k]); printk("\nsrcMacAddr: "); for (k = 6; k < 12; k++) printk("%02X ", defMacAddr[k-6]); printk("\n"); goto stop_testing; } } //decide offset for checking frame size if (*(uint16*)(&txData[12]) == ETHER_TYPE_IP) lenOffset = 16; else if (*(uint16*)(&txData[12]) == ETHER_TYPE_8021Q) lenOffset = 20; else if ((*(uint16*)(&txData[12]) == ETHER_TYPE_8021AD) || (*(uint16*)(&txData[12]) == ETHER_TYPE_QINQ)) lenOffset = 24; else if (*(uint16*)(&txData[12]) == ETHER_TYPE_SLOW) lenOffset = 26; else { printk("\nWrong Ether type:%d\n", txData[12]); goto stop_testing; } //BACP is raw packet, so FE won't strip its 4-byte CRC if (rxMsg->rxMsgW0.bits.isRaw) frameSize -= 4; //check frame size if ((*(uint16*)(&txData[lenOffset])) != frameSize) { printk("\nWrong frame size:\n" "txData[%d-%d]:%d != frameSize:%d\n", lenOffset, lenOffset+1, *(uint16*)(&txData[lenOffset]), (int)frameSize); goto stop_testing; } //decide what kind of test is for this packet. if (*(uint16*)(&txData[12]) == ETHER_TYPE_IP) { switch (txData[18]) //test type { case SINGLE_PKT_TESTTYPE: if (ptm_loopback_singlePkt_rx(rxMsg, skb)) goto stop_testing; break; case DATA_PATH_TESTTYPE: if (ptm_loopback_dataPath_rx(rxMsg, skb)) goto stop_testing; break; case DATA_BURST_TESTTYPE: if (ptm_loopback_dataBurst_rx(rxMsg, skb)) goto stop_testing; break; case MULTI_CHANNEL_TESTTYPE: if (ptm_loopback_multiChannel_rx(rxMsg, skb)) goto stop_testing; break; case PATH_NO_TESTTYPE: if (ptm_loopback_pathNo_rx(rxMsg, skb)) goto stop_testing; break; case PREEMPTION_TESTTYPE: if (ptm_loopback_preemption_rx(rxMsg, skb)) goto stop_testing; break; case SP_PRIORITY_TESTTYPE: if (ptm_loopback_spPriority_rx(rxMsg, skb)) goto stop_testing; break; case WRR_PRIORITY_TESTTYPE: if (ptm_loopback_wrrPriority_rx(rxMsg, skb)) goto stop_testing; break; case SP_WRR_TESTTYPE: if (ptm_loopback_spWrr_rx(rxMsg, skb)) goto stop_testing; break; case VLAN_TAG_TESTTYPE: if (ptm_loopback_vlanTag_rx(rxMsg, skb)) goto stop_testing; break; case VLAN_UNTAG_TESTTYPE: if (ptm_loopback_vlanUnTag_rx(rxMsg, skb)) goto stop_testing; break; case VLAN_DBL_TAG_TESTTYPE: if (ptm_loopback_vlanDblTag_rx(rxMsg, skb)) goto stop_testing; break; case VLAN_DBL_UNTAG_TESTTYPE: if (ptm_loopback_vlanDblUnTag_rx(rxMsg, skb)) goto stop_testing; break; case IPCS_INSERT_TESTTYPE: if (ptm_loopback_ipCsInsert_rx(rxMsg, skb)) goto stop_testing; break; case IPCS_CHECK_TESTTYPE: if (ptm_loopback_ipCsCheck_rx(rxMsg, skb)) goto stop_testing; break; case BACP_PKT_TESTTYPE: if (ptm_loopback_bacpCheck_rx(rxMsg, skb)) goto stop_testing; break; case RUNT_PKT_TESTTYPE: if (ptm_loopback_runtCheck_rx(rxMsg, skb)) goto stop_testing; break; case LONG_PKT_TESTTYPE: if (ptm_loopback_longCheck_rx(rxMsg, skb)) goto stop_testing; break; case CRCERR_PKT_TESTTYPE: if (ptm_loopback_crcCheck_rx(rxMsg, skb)) goto stop_testing; break; default: printk("\nWrong test type:%d for ETHER_TYPE_IP\n", txData[18]); goto stop_testing; } } else if (*(uint16*)(&txData[12]) == ETHER_TYPE_8021Q) { txData += 4; //shift 4 bytes switch (txData[18]) //test type { case VLAN_TAG_TESTTYPE: if (ptm_loopback_vlanTag_rx(rxMsg, skb)) goto stop_testing; break; case VLAN_UNTAG_TESTTYPE: printk("\nFAILED: HW didn't un-tag correctly\n"); goto stop_testing; case VLAN_DBL_TAG_TESTTYPE: printk("\nFAILED: HW didn't double tag correctly\n"); goto stop_testing; case VLAN_DBL_UNTAG_TESTTYPE: if (ptm_loopback_vlanDblUnTag_rx(rxMsg, skb)) goto stop_testing; break; default: printk("\nWrong test type:%d for ETHER_TYPE_8021Q\n", txData[18]); goto stop_testing; } } else if ((*(uint16*)(&txData[12]) == ETHER_TYPE_8021AD) || (*(uint16*)(&txData[12]) == ETHER_TYPE_QINQ)) { txData += 8; //shift 8 bytes switch (txData[18]) //test type { case VLAN_DBL_TAG_TESTTYPE: if (ptm_loopback_vlanDblTag_rx(rxMsg, skb)) goto stop_testing; break; case VLAN_DBL_UNTAG_TESTTYPE: printk("\nFAILED: HW didn't double untag correctly\n"); goto stop_testing; default: printk("\nWrong test type:%d for 8021AD/QINQ\n", txData[18]); goto stop_testing; } } else if (*(uint16*)(&txData[12]) == ETHER_TYPE_SLOW) { if (ptm_loopback_bacpCheck_rx(rxMsg, skb)) goto stop_testing; } else { printk("\nWrong ether type:%d\n", txData[12]); goto stop_testing; } return 0; stop_testing: stopTesting = 1; printk("\n%d pkts have received OK\n", dataPathRxPkts); printk("\nDump RX Message:\n"); dump_data((char*)rxMsg, rxMsgLen); printk("\nDump skb->data:\n"); dump_data(skb->data, frameSize); return -1; }
Vorringer/oci-go-sdk
blockchain/scale_blockchain_platform_details.go
<reponame>Vorringer/oci-go-sdk // Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved. // This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. // Code generated. DO NOT EDIT. // Blockchain Platform Control Plane API // // Blockchain Platform Control Plane API // package blockchain import ( "github.com/oracle/oci-go-sdk/v46/common" ) // ScaleBlockchainPlatformDetails Scale operation details for a blockchain platform. The scale operation payload has multiple options // - Add one or more Ordering Service Node (addOsns) // - Add one or more Peers (addPeers) // - Add more replicas of CA, Console and Rest Proxy (addReplicas) // - Add more storage to the platform (addStorage) // - Modify the CPU allocation for Peer Nodes (modifyPeers) // - Remove one or more replicas of CA, Console and Rest Proxy (removeReplicas) // - Remove one or more Ordering Service Node (removeOsns) // - Remove one or more Peers (removePeers). // The scale operation payload must have at least one of the above options. type ScaleBlockchainPlatformDetails struct { // new OSNs to add AddOsns []CreateOsnDetails `mandatory:"false" json:"addOsns"` AddReplicas *ReplicaDetails `mandatory:"false" json:"addReplicas"` // new Peers to add AddPeers []CreatePeerDetails `mandatory:"false" json:"addPeers"` AddStorage *ScaleStorageDetails `mandatory:"false" json:"addStorage"` // modify ocpu allocation to existing Peers ModifyPeers []ModifyPeerDetails `mandatory:"false" json:"modifyPeers"` RemoveReplicas *ReplicaDetails `mandatory:"false" json:"removeReplicas"` // OSN id list to remove RemoveOsns []string `mandatory:"false" json:"removeOsns"` // Peer id list to remove RemovePeers []string `mandatory:"false" json:"removePeers"` } func (m ScaleBlockchainPlatformDetails) String() string { return common.PointerString(m) }
GG-chen/MVPApp
app/src/main/java/com/chen/mvp/module/news/newslist/INewsListView.java
package com.chen.mvp.module.news.newslist; import com.chen.mvp.adapter.item.NewsMultiItem; import com.chen.mvp.api.bean.NewsInfo; import com.chen.mvp.module.base.ILoadDataView; import java.util.List; /** * Created by chen on 2017/9/9. */ public interface INewsListView extends ILoadDataView<List<NewsMultiItem>> { /** * 加载广告数据 * @param newsBean 新闻 */ void loadAdData(NewsInfo newsBean); }
rrkommer/gwiki
gwiki/src/main/java/de/micromata/genome/gwiki/page/search/SearchMatcherFactory.java
// // Copyright (C) 2010-2016 <NAME> & Micromata GmbH // // 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 de.micromata.genome.gwiki.page.search; import java.util.List; import de.micromata.genome.util.matcher.Matcher; import de.micromata.genome.util.matcher.MatcherFactory; import de.micromata.genome.util.matcher.OrMatcher; import de.micromata.genome.util.matcher.string.ContainsMatcher; import de.micromata.genome.util.types.Converter; /** * Factory to create matchers. * * @author <NAME> (<EMAIL>) * */ public class SearchMatcherFactory implements MatcherFactory<String> { public Matcher<String> createMatcher(String pattern) { List<String> parts = Converter.parseStringTokens(pattern, " ", false); Matcher<String> lm = null;// new OrMatcher<String>(); for (String p : parts) { if (lm == null) { lm = new ContainsMatcher<String>(p); } else { lm = new OrMatcher<String>(lm, new ContainsMatcher<String>(p)); } } return lm; } public String getRuleString(Matcher<String> matcher) { return "not supported"; } }
tglatt/emjpm
packages/knex/migrations/20190813180823_view_mesure_gestionnaire_view.js
exports.up = async function(knex) { return knex.raw(` CREATE VIEW view_mesure_gestionnaire AS SELECT dep.id department_id, dep.nom dep_nom, 'ANTENNE' discriminator, ser.id source_id, ser.mesures_awaiting, ser.mesures_in_progress, ser.mesures_max FROM service_antenne ser, departements dep WHERE dep.code = substring(ser.address_zip_code, 0, 3) union SELECT dep.id department_id, dep.nom dep_nom,'MANDATAIRE' discriminator, man.id source_id, man.mesures_en_attente mesures_awaiting, man.mesures_en_cours mesures_in_progress, man.dispo_max mesures_max FROM mandataires man, departements dep WHERE dep.code = substring(man.code_postal, 0, 3) `); }; exports.down = function(knex) { return knex.raw(` DROP VIEW view_mesure_gestionnaire `); };
refactormyself/java-smt-stage
src/org/sosy_lab/java_smt/basicimpl/withAssumptionsWrapper/InterpolatingProverWithAssumptionsWrapper.java
/* * JavaSMT is an API wrapper for a collection of SMT solvers. * This file is part of JavaSMT. * * Copyright (C) 2007-2016 <NAME> * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sosy_lab.java_smt.basicimpl.withAssumptionsWrapper; import static com.google.common.base.Preconditions.checkNotNull; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.BooleanFormulaManager; import org.sosy_lab.java_smt.api.FormulaManager; import org.sosy_lab.java_smt.api.FunctionDeclaration; import org.sosy_lab.java_smt.api.FunctionDeclarationKind; import org.sosy_lab.java_smt.api.InterpolatingProverEnvironment; import org.sosy_lab.java_smt.api.SolverException; import org.sosy_lab.java_smt.api.visitors.BooleanFormulaTransformationVisitor; public class InterpolatingProverWithAssumptionsWrapper<T> extends BasicProverWithAssumptionsWrapper<T, InterpolatingProverEnvironment<T>> implements InterpolatingProverEnvironment<T> { private final List<T> solverAssumptionsFromPush; private final FormulaManager fmgr; private final BooleanFormulaManager bmgr; public InterpolatingProverWithAssumptionsWrapper( InterpolatingProverEnvironment<T> pDelegate, FormulaManager pFmgr) { super(pDelegate); solverAssumptionsFromPush = new ArrayList<>(); fmgr = checkNotNull(pFmgr); bmgr = fmgr.getBooleanFormulaManager(); } @Override public BooleanFormula getInterpolant(Collection<T> pFormulasOfA) throws SolverException, InterruptedException { List<T> completeListOfA = new ArrayList<>(pFormulasOfA); completeListOfA.addAll(solverAssumptionsFromPush); BooleanFormula interpolant = delegate.getInterpolant(completeListOfA); // remove assumption variables from the rawInterpolant if necessary if (!solverAssumptionsAsFormula.isEmpty()) { interpolant = bmgr.transformRecursively(interpolant, new RemoveAssumptionsFromFormulaVisitor()); } return interpolant; } @Override public List<BooleanFormula> getSeqInterpolants(List<? extends Collection<T>> pPartitionedFormulas) throws SolverException, InterruptedException { if (solverAssumptionsAsFormula.isEmpty()) { return delegate.getSeqInterpolants(pPartitionedFormulas); } else { throw new UnsupportedOperationException(); } } @Override public List<BooleanFormula> getTreeInterpolants( List<? extends Collection<T>> pPartitionedFormulas, int[] pStartOfSubTree) throws SolverException, InterruptedException { if (solverAssumptionsAsFormula.isEmpty()) { return delegate.getTreeInterpolants(pPartitionedFormulas, pStartOfSubTree); } else { throw new UnsupportedOperationException(); } } @Override protected void registerPushedFormula(T pPushResult) { solverAssumptionsFromPush.add(pPushResult); } @Override protected void clearAssumptions() { super.clearAssumptions(); solverAssumptionsFromPush.clear(); } class RemoveAssumptionsFromFormulaVisitor extends BooleanFormulaTransformationVisitor { private RemoveAssumptionsFromFormulaVisitor() { super(fmgr); } @Override public BooleanFormula visitAtom(BooleanFormula atom, FunctionDeclaration<BooleanFormula> decl) { if (decl.getKind() == FunctionDeclarationKind.VAR) { String varName = decl.getName(); // TODO is it sound to replace a variable with TRUE? if (solverAssumptionsContainsVar(varName)) { return bmgr.makeBoolean(true); } else { return bmgr.makeVariable(varName); } } else { return atom; } } private boolean solverAssumptionsContainsVar(String variableName) { for (BooleanFormula solverVar : solverAssumptionsAsFormula) { if (fmgr.extractVariables(solverVar).keySet().contains(variableName)) { return true; } } return false; } } }
griffero/hound
lib/error_message_translation.rb
<gh_stars>1-10 module ErrorMessageTranslation ERROR_CODE_AND_MESSAGE = /.*(\d{3})\s\-\s(.*)\s\/\/.*/ FORBIDDEN_ERROR_CODE = "403" def self.from_error_response(error) matches = error.message.match(ERROR_CODE_AND_MESSAGE) if matches.present? && matches.captures[0] == FORBIDDEN_ERROR_CODE matches.captures[1] end end end
tdrwenski/netcdf-java
visad/mcidas/src/test/java/ucar/nc2/TestPointDatasets.java
/* * Copyright (c) 1998-2020 <NAME> and University Corporation for Atmospheric Research/Unidata * See LICENSE for license information. */ package ucar.nc2; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ucar.nc2.constants.FeatureType; import ucar.unidata.util.test.CheckPointFeatureDataset; import ucar.unidata.util.test.TestDir; import ucar.unidata.util.test.category.NeedsCdmUnitTest; @RunWith(Parameterized.class) @Category(NeedsCdmUnitTest.class) public class TestPointDatasets { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @Parameterized.Parameters(name = "{0}") public static List<Object[]> getTestParameters() { List<Object[]> result = new ArrayList<>(); // gempack sounding result.add(new Object[] {TestDir.cdmUnitTestDir + "ft/sounding/gempak/19580807_upa.ncml", FeatureType.STATION_PROFILE, 8769}); // gempak surface result.add(new Object[] {TestDir.cdmUnitTestDir + "ft/point/gempak/2009103008_sb.gem", FeatureType.POINT, 3337}); result.add(new Object[] {TestDir.cdmUnitTestDir + "ft/point/gempak/2009110100_ship.gem", FeatureType.POINT, 938}); result.add(new Object[] {TestDir.cdmUnitTestDir + "ft/station/gempak/20091030_syn.gem", FeatureType.POINT, 55856}); result .add(new Object[] {TestDir.cdmUnitTestDir + "ft/station/gempak/20091030_syn.gem", FeatureType.STATION, 28328}); result.add(new Object[] {TestDir.cdmUnitTestDir + "ft/sounding/gempak/19580807_upa.ncml", FeatureType.STATION_PROFILE, 8769}); return result; } private final String location; private final FeatureType ftype; private final int countExpected; private final boolean show = false; public TestPointDatasets(String location, FeatureType ftype, int countExpected) { this.location = location; this.ftype = ftype; this.countExpected = countExpected; } @Test public void checkPointFeatureDataset() throws IOException { CheckPointFeatureDataset checker = new CheckPointFeatureDataset(location, ftype, show); Assert.assertEquals("npoints", countExpected, checker.check()); } }
grappendorf/coyoho-server
db/migrate/20160305213550_remove_devise.rb
<gh_stars>0 class RemoveDevise < ActiveRecord::Migration def up remove_column :users, :reset_password_token remove_column :users, :reset_password_sent_at remove_column :users, :remember_created_at remove_column :users, :sign_in_count remove_column :users, :current_sign_in_at remove_column :users, :current_sign_in_ip remove_column :users, :last_sign_in_at remove_column :users, :last_sign_in_ip end def down end end
ArekkuusuJerii/TECProyect
src/Utils/RunnableCode.java
package Utils; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.Timer; /** * Descripción: Runnable de Cierre de Sesión * */ @CleanupDone public class RunnableCode implements Runnable { @Override public void run() { timerJPane(1).start(); JOptionPane.showOptionDialog(null, "Reiniciando...", "Restart", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new Object[]{}, null); } /** * Descripción: Muestra JOptionPane por segundos, luego lo elimina. * * @param n // Tiempo de vida del mensaje */ private Timer timerJPane(int n) { ActionListener cerrar = (ActionEvent e) -> { Window[] wind = Window.getWindows(); for (Window window : wind) { if (window instanceof JDialog) { JDialog dialog = (JDialog) window; if (dialog.getContentPane().getComponentCount() == 1 && dialog.getContentPane().getComponent(0) instanceof JOptionPane) { dialog.dispose(); } } } }; Timer t = new Timer(n * 1000, cerrar); t.setRepeats(false); return t; } }
AxonTeam/AxonCore
src/Libraries/LibraryInterface.js
<filename>src/Libraries/LibraryInterface.js import NotImplementedException from '../Errors/NotImplementedException'; class LibraryInterface { constructor(axonClient) { this._axon = axonClient; } get botClient() { return this._axon.botClient; } // eslint-disable-next-line no-unused-vars onMessageCreate(func) { throw new NotImplementedException(); } // eslint-disable-next-line no-unused-vars onceReady(func) { throw new NotImplementedException(); } } export default LibraryInterface;
freman/genesysapi
models/text_bot_flow_turn_response.go
// Code generated by go-swagger; DO NOT EDIT. package models // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "encoding/json" "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" "github.com/go-openapi/validate" ) // TextBotFlowTurnResponse Information related to a success bot flow turn request. // // swagger:model TextBotFlowTurnResponse type TextBotFlowTurnResponse struct { // The ID of the bot flow turn. If additional turns are needed, supply this ID as the previous turn in your next turn request. // Required: true ID *string `json:"id"` // The next action directive for this turn if it is a Disconnect type. NextActionDisconnect *TextBotDisconnectAction `json:"nextActionDisconnect,omitempty"` // The next action directive for this turn if it is an Exit type. NextActionExit *TextBotExitAction `json:"nextActionExit,omitempty"` // Indicates the suggested next action. If appropriate, the matching output event object includes additional information. // Required: true // Enum: [NoOp Disconnect WaitForInput Exit] NextActionType *string `json:"nextActionType"` // The next action directive for this turn if it is a WaitForInput type. NextActionWaitForInput *TextBotWaitForInputAction `json:"nextActionWaitForInput,omitempty"` // The reference to a previous turn, if applicable. PreviousTurn *TextBotTurnReference `json:"previousTurn,omitempty"` // The output prompts for this turn. Prompts *TextBotOutputPrompts `json:"prompts,omitempty"` } // Validate validates this text bot flow turn response func (m *TextBotFlowTurnResponse) Validate(formats strfmt.Registry) error { var res []error if err := m.validateID(formats); err != nil { res = append(res, err) } if err := m.validateNextActionDisconnect(formats); err != nil { res = append(res, err) } if err := m.validateNextActionExit(formats); err != nil { res = append(res, err) } if err := m.validateNextActionType(formats); err != nil { res = append(res, err) } if err := m.validateNextActionWaitForInput(formats); err != nil { res = append(res, err) } if err := m.validatePreviousTurn(formats); err != nil { res = append(res, err) } if err := m.validatePrompts(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *TextBotFlowTurnResponse) validateID(formats strfmt.Registry) error { if err := validate.Required("id", "body", m.ID); err != nil { return err } return nil } func (m *TextBotFlowTurnResponse) validateNextActionDisconnect(formats strfmt.Registry) error { if swag.IsZero(m.NextActionDisconnect) { // not required return nil } if m.NextActionDisconnect != nil { if err := m.NextActionDisconnect.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("nextActionDisconnect") } return err } } return nil } func (m *TextBotFlowTurnResponse) validateNextActionExit(formats strfmt.Registry) error { if swag.IsZero(m.NextActionExit) { // not required return nil } if m.NextActionExit != nil { if err := m.NextActionExit.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("nextActionExit") } return err } } return nil } var textBotFlowTurnResponseTypeNextActionTypePropEnum []interface{} func init() { var res []string if err := json.Unmarshal([]byte(`["NoOp","Disconnect","WaitForInput","Exit"]`), &res); err != nil { panic(err) } for _, v := range res { textBotFlowTurnResponseTypeNextActionTypePropEnum = append(textBotFlowTurnResponseTypeNextActionTypePropEnum, v) } } const ( // TextBotFlowTurnResponseNextActionTypeNoOp captures enum value "NoOp" TextBotFlowTurnResponseNextActionTypeNoOp string = "NoOp" // TextBotFlowTurnResponseNextActionTypeDisconnect captures enum value "Disconnect" TextBotFlowTurnResponseNextActionTypeDisconnect string = "Disconnect" // TextBotFlowTurnResponseNextActionTypeWaitForInput captures enum value "WaitForInput" TextBotFlowTurnResponseNextActionTypeWaitForInput string = "WaitForInput" // TextBotFlowTurnResponseNextActionTypeExit captures enum value "Exit" TextBotFlowTurnResponseNextActionTypeExit string = "Exit" ) // prop value enum func (m *TextBotFlowTurnResponse) validateNextActionTypeEnum(path, location string, value string) error { if err := validate.EnumCase(path, location, value, textBotFlowTurnResponseTypeNextActionTypePropEnum, true); err != nil { return err } return nil } func (m *TextBotFlowTurnResponse) validateNextActionType(formats strfmt.Registry) error { if err := validate.Required("nextActionType", "body", m.NextActionType); err != nil { return err } // value enum if err := m.validateNextActionTypeEnum("nextActionType", "body", *m.NextActionType); err != nil { return err } return nil } func (m *TextBotFlowTurnResponse) validateNextActionWaitForInput(formats strfmt.Registry) error { if swag.IsZero(m.NextActionWaitForInput) { // not required return nil } if m.NextActionWaitForInput != nil { if err := m.NextActionWaitForInput.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("nextActionWaitForInput") } return err } } return nil } func (m *TextBotFlowTurnResponse) validatePreviousTurn(formats strfmt.Registry) error { if swag.IsZero(m.PreviousTurn) { // not required return nil } if m.PreviousTurn != nil { if err := m.PreviousTurn.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("previousTurn") } return err } } return nil } func (m *TextBotFlowTurnResponse) validatePrompts(formats strfmt.Registry) error { if swag.IsZero(m.Prompts) { // not required return nil } if m.Prompts != nil { if err := m.Prompts.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("prompts") } return err } } return nil } // MarshalBinary interface implementation func (m *TextBotFlowTurnResponse) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *TextBotFlowTurnResponse) UnmarshalBinary(b []byte) error { var res TextBotFlowTurnResponse if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }
mxmo0rhuhn/map-reduce
mapreduce-client-socket/src/main/java/ch/zhaw/mapreduce/plugins/socket/SocketClientBinder.java
package ch.zhaw.mapreduce.plugins.socket; import java.util.logging.Logger; import de.root1.simon.Lookup; public class SocketClientBinder { private static final Logger LOG = Logger.getLogger(SocketClientBinder.class.getName()); private final Lookup lookup; private final String agentRegistratorSimonBinding; private AgentRegistrator regServer; SocketClientBinder(Lookup lookup, String agentRegistratorSimonBinding) { this.lookup = lookup; this.agentRegistratorSimonBinding = agentRegistratorSimonBinding; } public void bind() throws Exception { this.regServer = (AgentRegistrator) this.lookup.lookup(agentRegistratorSimonBinding); } public void registerAgent(SocketAgent agent) { LOG.entering(getClass().getName(), "registerAgent", agent); this.regServer.register(agent); LOG.exiting(getClass().getName(), "registerAgent", agent); } public void release() { this.lookup.release(this.regServer); } }
nbrookie/cardsy
src/utils/cardUtils.js
<reponame>nbrookie/cardsy import string from "./stringUtils" import templates from "./templates" /** * cardsy.getType * * Accepts a card number as a string or an integer and returns the * card type as a capitalised string (e.g. "VISA"). If the card * number matches no card type patterns it returns null. * * @param {string|number} number - A card number * * @returns {string|null} The matching card type as found in template.js */ const getType = (number) => { const template = getTemplateByNumber(number) return template ? template.type : null } /** * getTemplateByNumber (Private) * * Accepts a card number as a string or an integer and returns the template * of the matching card type as found in src/utils/template.js. If the * card number matches no card type patterns it returns null. * * @param {string|number} number - A card number * * @returns {object|null} The card template as found in src/utils/template.js */ const getTemplateByNumber = (number) => { if (!number) { return null } number = string.stripWhiteSpace(number) return templates.find((template) => template.pattern.test(number)) } /** * getTemplateByType (Private) * * Accepts a card type as a string and returns the matching * template as found in src/utils/template.js. If the * type passed is not supported it returns null. * * @param {string} type - A capitalised card type (e.g. "VISA") * * @returns {object|null} The card template as found in src/utils/template.js */ const getTemplateByType = (type) => { return templates.find((template) => template.type === type) } /** * getAutoCompleteMonth (Private) * * Accepts an expiry month as a string or integer and tries * to return a two character string description of that * month. Any month that can be described in a single * digit gets prefixed with a zero e.g. "3" => "03" * * @param {string|number} month - Card expiry date month * * @returns {string} The formatted expiry month */ const getAutoCompleteMonth = (month) => { month = string.stripNonNumeric(month) if(parseInt(month[0]) > 1) { month = "0" + month } month = string.trimToLength(month, 2) return month } /** * luhnCheck (Private) * * Accepts a card number as a string or integer and returns a boolean * value for isValid based on whether the number passes a Luhn check. * * https://en.wikipedia.org/wiki/Luhn_algorithm * * @param {string|number} number - A card number * * @returns {boolean} Does card number pass a Luhn check */ const luhnCheck = (number) => { let digit let odd = true let sum = 0 let digits = (number + "").split("").reverse() for (let i = 0; i < digits.length; i++) { digit = parseInt(digits[i], 10) if ((odd = !odd)) { digit *= 2 } if (digit > 9) { digit -= 9 } sum += digit } return sum % 10 === 0 } module.exports = { getTemplate : { byNumber : getTemplateByNumber, byType : getTemplateByType }, getType, getAutoCompleteMonth, luhnCheck }
yzhang226/quark
quark-core/src/main/java/org/lightning/quark/core/row/CdcInfo.java
package org.lightning.quark.core.row; import lombok.Getter; import lombok.Setter; import org.lightning.quark.core.model.db.PKData; import java.util.Date; import java.util.Objects; /** * SQL Server - model for Change Capture Data * Created by cook on 2018/2/27 */ @Getter @Setter public class CdcInfo { /** 更改提交的LSN。在同一事务中提交的更改将共享同一个提交 LSN 值 */ private byte[] startLsn; /** 一个事务内可能有多个更改发生,这个值用于对它们进行排序 */ private byte[] seqval; /** * 一次cdc的主键(s) */ private PKData pk; /** * 更新时间 */ private Date updateTime; /** * 更改操作的类型: 1 = 删除 2 = 插入 3 = 更新(捕获的列值是执行更新操作前的值) 4 = 更新(捕获的列值是执行更新操作后的值) */ private int operation; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; CdcInfo cdcInfo = (CdcInfo) o; return Objects.equals(pk, cdcInfo.pk); } @Override public int hashCode() { return Objects.hash(pk); } }
italiangrid/voms-admin-server
voms-admin-server/src/main/java/org/glite/security/voms/admin/integration/orgdb/OrgDBMembershipSynchronizationTask.java
/** * Copyright (c) <NAME> Fisica Nucleare (INFN). 2006-2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.glite.security.voms.admin.integration.orgdb; import java.util.concurrent.TimeUnit; import org.glite.security.voms.admin.integration.orgdb.dao.OrgDBDAOFactory; import org.glite.security.voms.admin.integration.orgdb.dao.OrgDBVOMSPersonDAO; import org.glite.security.voms.admin.integration.orgdb.database.OrgDBError; import org.glite.security.voms.admin.integration.orgdb.database.OrgDBSessionFactory; import org.glite.security.voms.admin.integration.orgdb.model.Participation; import org.glite.security.voms.admin.integration.orgdb.model.VOMSOrgDBPerson; import org.glite.security.voms.admin.integration.orgdb.strategies.OrgDBMembershipSynchronizationStrategy; import org.glite.security.voms.admin.integration.orgdb.strategies.OrgDBMissingMembershipRecordStrategy; import org.glite.security.voms.admin.integration.orgdb.strategies.OrgDbExpiredParticipationStrategy; import org.glite.security.voms.admin.persistence.dao.VOMSUserDAO; import org.glite.security.voms.admin.persistence.model.VOMSUser; import org.hibernate.ScrollableResults; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OrgDBMembershipSynchronizationTask implements Runnable { public static final Logger log = LoggerFactory .getLogger(OrgDBMembershipSynchronizationTask.class); public static final int UPDATE_COUNT_BATCH = 50; protected String experimentName; protected OrgDBMissingMembershipRecordStrategy missingMembershipStrategy; protected OrgDbExpiredParticipationStrategy expiredParticipationStrategy; protected OrgDBMembershipSynchronizationStrategy synchronizationStrategy; public OrgDBMembershipSynchronizationTask(String experiment, OrgDBMissingMembershipRecordStrategy invalidMembershipStrategy, OrgDbExpiredParticipationStrategy expiredParticaptionStrategy, OrgDBMembershipSynchronizationStrategy membershipSynchronizationStrategy) { experimentName = experiment; this.missingMembershipStrategy = invalidMembershipStrategy; this.expiredParticipationStrategy = expiredParticaptionStrategy; this.synchronizationStrategy = membershipSynchronizationStrategy; } protected VOMSOrgDBPerson lookupOrgDBPerson(VOMSUser u, Session s) { OrgDBVOMSPersonDAO dao = OrgDBDAOFactory.instance() .getVOMSPersonDAO(); dao.setSession(s); VOMSOrgDBPerson orgdbPerson = null; try { if (u.getOrgDbId() != null) { orgdbPerson = dao.findById(u.getOrgDbId(), false); if (orgdbPerson == null) { log.warn( "No OrgDB person found for id '{}' linked to VOMS membership {}", u.getOrgDbId(), u.toString()); } } if (orgdbPerson == null) { log.warn("Looking up orgdb membership by user email address. User: {}", u.toString()); orgdbPerson = dao.findPersonByEmail(u.getEmailAddress()); } } catch (Throwable ex) { log.error("Exception caught while looking up OrgDB user for VOMS user {}", u); log.error("Exception caught while looking up OrgDB user: {}", ex.getMessage(), ex); orgdbPerson = null; } return orgdbPerson; } public void run() { SessionFactory sf = OrgDBSessionFactory.getSessionFactory(); long startTime = System.currentTimeMillis(); try { if (sf.openSession() == null) { throw new OrgDBError("Error opening session to OrgDB"); } sf.getCurrentSession() .beginTransaction(); ScrollableResults allUserCursor = VOMSUserDAO.instance() .findAllWithCursor(); int updateCount = 0; while (allUserCursor.next()) { OrgDBVOMSPersonDAO dao = OrgDBDAOFactory.instance().getVOMSPersonDAO(); VOMSUser u = (VOMSUser) allUserCursor.get(0); VOMSOrgDBPerson orgDbPerson = lookupOrgDBPerson(u, sf.getCurrentSession()); if (orgDbPerson != null) { updateCount++; Participation validParticipation = dao.findValidParticipationInExperiment( orgDbPerson, experimentName); synchronizationStrategy.synchronizeMemberInformation(u, orgDbPerson, experimentName, validParticipation); if (validParticipation == null){ expiredParticipationStrategy.handleOrgDbExpiredParticipation(u, orgDbPerson, experimentName); } // Flush some updates out and release memory if (updateCount % UPDATE_COUNT_BATCH == 0) { log.debug("Flushing session after {} updates.", updateCount); sf.getCurrentSession() .flush(); sf.getCurrentSession() .clear(); } } else { log.warn("No OrgDB record found for user {}.", u); missingMembershipStrategy.handleMissingMembershipRecord(u); } } sf.getCurrentSession() .getTransaction() .commit(); } catch (OrgDBError e) { log.error("OrgDB exception caught: {}", e.getMessage()); if (log.isDebugEnabled()) { log.error("OrgDB exception caught: {}", e.getMessage(), e); } try { sf.getCurrentSession() .getTransaction() .rollback(); } catch (Throwable t) { log.error("Error rolling back OrgDB transaction: {}", t.getMessage(), t); } } finally { sf.getCurrentSession() .close(); long elapsedTime = System.currentTimeMillis() - startTime; log.info("OrgDB synchronization took {} seconds.", TimeUnit.MILLISECONDS.toSeconds(elapsedTime)); } } }
coleygroup/rxn-ebm
rxnebm/data/preprocess/clean_smiles.py
""" This module contains functions to clean a raw dataset of reaction SMILES strings, which includes operations such as removing atom mapping and checking for invalid molecule SMILES. There is also a function to generate a list of SMILES strings of all unique molecules in the given dataset. NOTE: in rxn-ebm, a 'dataset' refers to the combination of 'train', 'valid', and 'test', (which are each called a 'phase') e.g. USPTO_50k is a dataset. """ import argparse import csv import os import pickle import random import re import sys from concurrent.futures import ProcessPoolExecutor as Pool from pathlib import Path from typing import List, Optional, Tuple, Union import numpy as np import rdkit from rdkit import Chem from rdkit.Chem import rdChemReactions from tqdm import tqdm Mol = rdkit.Chem.rdchem.Mol ################################### ######### HELPER FUNCTIONS ######## ################################### def parse_args(): parser = argparse.ArgumentParser("clean_smiles") # file paths parser.add_argument("--raw_smi_pre", help="File prefix of original raw rxn_smi csv", type=str, default="schneider50k") parser.add_argument("--clean_smi_pre", help="File prefix of cleaned rxn_smi pickle", type=str, default="50k_clean_rxnsmi_noreagent_allmapped") parser.add_argument("--raw_smi_root", help="Full path to folder containing raw rxn_smi csv", type=str) parser.add_argument("--clean_smi_root", help="Full path to folder that will contain cleaned rxn_smi pickle", type=str) # args for clean_rxn_smis_50k_all_phases parser.add_argument("--split_mode", help='Whether to keep rxn_smi with multiple products: "single" or "multi"', type=str, default="multi") parser.add_argument("--lines_to_skip", help="Number of lines to skip", type=int, default=1) parser.add_argument("--keep_reag", help="Whether to keep reagents in output SMILES string", type=bool, default=False) parser.add_argument("--keep_all_rcts", help="Whether to keep all rcts even if they don't contribute atoms to product", type=bool, default=False) parser.add_argument("--remove_dup_rxns", help="Whether to remove duplicate rxn_smi", type=bool, default=True) parser.add_argument("--remove_rct_mapping", help="Whether to remove atom map if atom in rct is not in product", type=bool, default=True) parser.add_argument("--remove_all_mapping", help="Whether to remove all atom map", type=bool, default=False) parser.add_argument("--save_idxs", help="Whether to save all bad indices to a file in same dir as clean_smi", type=bool, default=False) parser.add_argument("--parallelize", help="Whether to parallelize computation across all available cpus", type=bool, default=True) return parser.parse_args() def remove_mapping(rxn_smi: str, keep_reagents: bool = False) -> str: """ Removes all atom mapping from the reaction SMILES string Parameters ---------- rxn_smi : str The reaction SMILES string whose atom mapping is to be removed keep_reagents : bool (Default = False) whether to keep the reagents in the output reaction SMILES string Returns ------- str The reaction SMILES string with all atom mapping removed Also see: clean_rxn_smis_50k_one_phase, clean_rxn_smis_FULL_one_phase """ rxn = rdChemReactions.ReactionFromSmarts(rxn_smi, useSmiles=True) if not keep_reagents: rxn.RemoveAgentTemplates() prods = [mol for mol in rxn.GetProducts()] for prod in prods: for atom in prod.GetAtoms(): if atom.HasProp("molAtomMapNumber"): atom.ClearProp("molAtomMapNumber") rcts = [mol for mol in rxn.GetReactants()] for rct in rcts: for atom in rct.GetAtoms(): if atom.HasProp("molAtomMapNumber"): atom.ClearProp("molAtomMapNumber") return rdChemReactions.ReactionToSmiles(rxn) def move_reagents( mol_prod: Mol, reactants: List[Mol], original_reagents: List[str], keep_reagents: bool = False, keep_all_rcts: bool = False, remove_rct_mapping: bool = True, ) -> str: """ Adapted func from <NAME>'s GLN - gln/data_process/clean_uspto.py --> get_rxn_smiles() to additionally keep track of reagents (reactants that don't appear in products) Gets rid of reactants when they don't contribute to the product Parameters ---------- mol_prod : Mol product molecule reactants : List[Mol] list of reactant molecules original_reagents : List[str] list of reagents in the original reaction (from 'rcts>reagents>prods'), each element of list = 1 reagent keep_reagents : bool (Default = True) whether to keep reagents in the output SMILES string keep_all_rcts : bool (Default = False) whether to keep all reactants, regardless of whether they contribute any atoms to the product NOTE: GLN removes non-contributing reactants in their clean_uspto.py's main() remove_rct_mapping : bool (Default = True) whether to remove atom mapping if atom in reactant is not in product (i.e. leaving groups) NOTE: GLN removes these atom mapping in their clean_uspto.py's get_rxn_smiles() Returns ------- str reaction SMILES string with only reactants that contribute to the product, the other molecules being moved to reagents (if keep_reagents is True) Also see: clean_rxn_smis_from_csv """ prod_smi = Chem.MolToSmiles(mol_prod, True) prod_maps = set(re.findall(r"\:([[0-9]+)\]", prod_smi)) reactants_smi_list = [] reagent_smi_list = [] if original_reagents: reagent_smi_list.append(original_reagents) for mol in reactants: if mol is None: continue used = False for a in mol.GetAtoms(): if a.HasProp("molAtomMapNumber"): if a.GetProp("molAtomMapNumber") in prod_maps: used = True # removes atom mapping if atom in reactant is not in product elif remove_rct_mapping: a.ClearProp("molAtomMapNumber") if keep_all_rcts: # keep all rcts rgdless of contribution to prod atoms reactants_smi_list.append(Chem.MolToSmiles(mol, True)) elif used: reactants_smi_list.append(Chem.MolToSmiles(mol, True)) else: reagent_smi_list.append(Chem.MolToSmiles(mol, True)) reactants_smi = ".".join(reactants_smi_list) if not keep_reagents: return "{}>>{}".format(reactants_smi, prod_smi) if reagent_smi_list: reagents_smi = ".".join(reagent_smi_list) else: reagents_smi = "" return "{}>{}>{}".format(reactants_smi, reagents_smi, prod_smi) ################################### ########### USPTO_50k ############# ################################### def clean_rxn_smis_50k_one_phase( path_to_rxn_smis: Union[str, bytes, os.PathLike], lines_to_skip: int = 1, dataset_name: str = "50k", keep_reagents: bool = False, keep_all_rcts: bool = False, remove_rct_mapping: bool = True, remove_all_mapping: bool = False, ): """ Adapted function from Hanjun Dai's GLN: gln/data_process/clean_uspto.py --> main() NOTE: reads csv file twice, first time to get total line count for tqdm, second time to do the actual work This may not be practical with extremely large csv files Cleans reaction SMILES strings by removing those with: bad product (SMILES not parsable by rdkit) too small products, like 'O' (='H2O'), 'N'(='NH3'), i.e. a large reactant fails to be recorded as a product It also checks these, but does not remove them, since atom mapping is not needed for rxn-ebm: missing atom mapping (not all atoms in the product molecule have atom mapping), bad atom mapping (not 1:1 between reactants and products) Lastly, it also keeps track of duplicate, cleaned reaction SMILES strings and their indices in the original CSV file Parameters ---------- path_to_rxn_smis : str full path to the CSV file containing the reaction SMILES strings there will be one CSV file each for train, valid and test, coordinated by clean_rxn_smis_all_phases lines_to_skip : int (Default = 1) how many header lines to skip in the CSV file This is 1 for USPTO_50k (schneider), but 3 for USPTO_STEREO, and 1 for USPTO_FULL (GLN) Unfortunately, this cannot be reliably extracted from some automatic algorithm, as every CSV file can be differently formatted split_mode : str (Default = 'multi') whether to keep and process reaction SMILES containing multiple products, or ignore them Choose between 'single' and 'multi' keep_reagents : bool (Default = False) whether to keep reagents in the output SMILES keep_all_rcts : bool (Default = False) whether to keep all reactants, regardless of whether they contribute any atoms to the product NOTE: GLN removes non-contributing reactants in their clean_uspto.py's main() remove_rct_mapping : bool (Default = True) whether to remove atom mapping if atom in reactant is not in product (i.e. leaving groups) NOTE: GLN removes these atom mapping in their clean_uspto.py's get_rxn_smiles() remove_all_mapping : bool (Default = False) whether to remove all atom mapping from the reaction SMILES, if True, remove_rct_mapping will be automatically set to True Returns ------- clean_list : List[str] list of cleaned reaction SMILES strings with possible duplicates NOTE: for USPTO_50k from schneider50k, only 4 reaction SMILES should be removed for having too small products set_clean_list : List[str] list of cleaned reaction SMILES strings without duplicates this will be used if remove_dup_rxns is set to True in clean_rxn_smis_all_phases() bad_mapping_idxs : List[int] indices of reaction SMILES strings in original dataset with bad atom mapping (product atom id's do not all match reactant atom id's) bad_prod_idxs : List[int] indices of reaction SMILES strings in original dataset with bad products (not parsable by RDKit) too_small_idxs : List[int] indices of reaction SMILES strings in original dataset with too small products (product SMILES string smaller than 3 characters) missing_map_idxs : List[int] indices of reaction SMILES strings in original dataset with missing atom mapping dup_rxn_idxs : List[int] indices of reaction SMILES strings in original dataset that are duplicates of an already cleaned & extracted reaction SMILES string Also see: move_reagents, remove_mapping """ if remove_all_mapping: remove_rct_mapping = True pt = re.compile(r":(\d+)]") clean_list, set_clean_list = [], set() bad_mapping, bad_mapping_idxs = 0, [] bad_prod, bad_prod_idxs = 0, [] missing_map, missing_map_idxs = 0, [] too_small, too_small_idxs = 0, [] dup_rxn_idxs = [] extracted = 0 with open(path_to_rxn_smis, "r") as csv_file: total_lines = len(csv_file.readlines()) - lines_to_skip with open(path_to_rxn_smis, "r") as csv_file: reader = csv.reader(csv_file, delimiter="\t") for line in range(lines_to_skip): header = next(reader) # skip first row of csv file for i, row in enumerate(tqdm(reader, total=total_lines)): rxn_smi = row[0].split(",")[2] # second column of the csv file all_rcts_smi, all_reag_smi, prods_smi = rxn_smi.split(">") rids = ",".join(sorted(re.findall(pt, all_rcts_smi))) pids = ",".join(sorted(re.findall(pt, prods_smi))) if ( rids != pids ): # atom mapping is not 1:1, but for rxn-ebm, this is not important bad_mapping += 1 bad_mapping_idxs.append(i) all_rcts_mol = [Chem.MolFromSmiles(smi) for smi in all_rcts_smi.split(".")] for prod_smi in prods_smi.split("."): mol_prod = Chem.MolFromSmiles(prod_smi) if ( mol_prod is None ): # rdkit is not able to parse the product, critical! bad_prod += 1 bad_prod_idxs.append(i) continue # check if all atoms in product have atom mapping, but for # rxn-ebm, this is not important if not all( [a.HasProp("molAtomMapNumber") for a in mol_prod.GetAtoms()] ): missing_map += 1 missing_map_idxs.append(i) rxn_smi = move_reagents( mol_prod, all_rcts_mol, all_reag_smi, keep_reagents, keep_all_rcts, remove_rct_mapping, ) temp_rxn_smi = remove_mapping(rxn_smi, keep_reagents=keep_reagents) if ( len(temp_rxn_smi.split(">")[-1]) < 3 ): # check length of product SMILES string too_small += 1 # e.g. 'Br', 'O', 'I' too_small_idxs.append(i) continue if remove_all_mapping: rxn_smi = temp_rxn_smi clean_list.append(rxn_smi) if rxn_smi not in set_clean_list: set_clean_list.add(rxn_smi) else: dup_rxn_idxs.append(i) extracted += 1 print("# clean rxn: ", len(clean_list)) print("# unique rxn:", len(set_clean_list)) print("bad mapping: ", bad_mapping) print("bad prod: ", bad_prod) print("too small: ", too_small) print("missing map: ", missing_map) print("raw rxn extracted: ", extracted, "\n") return ( clean_list, list(set_clean_list), bad_mapping_idxs, bad_prod_idxs, too_small_idxs, missing_map_idxs, dup_rxn_idxs, ) def clean_rxn_smis_50k_all_phases( input_file_prefix: str = "schneider50k", output_file_prefix: str = "50k_clean_rxnsmi_noreagent_allmapped", input_root: Optional[Union[str, bytes, os.PathLike]] = None, output_root: Optional[Union[str, bytes, os.PathLike]] = None, lines_to_skip: Optional[int] = 1, keep_reagents: bool = False, keep_all_rcts: bool = False, remove_dup_rxns: bool = True, remove_rct_mapping: bool = True, remove_all_mapping: bool = False, save_idxs: bool = False, parallelize: bool = True, **kwargs ): """NOTE: assumes file extension is .csv. GLN uses .rsmi for USPTO_FULL, but it's actually .csv file Parameters ---------- input_file_prefix : str (Default = 'schneider50k') file prefix of the original raw, unclean, reaction SMILES csv file for USPTO_50k this function appends phase = ['train', 'valid', 'test'] --> {raw_data_file_prefix}_{phase}.csv output_file_prefix : str (Default = '50k_clean_rxnsmi_noreagent_allmapped') file prefix of the output, cleaned reaction SMILES pickle file recommended format: '{dataset_name}_clean_rxnsmi_{any_tags}' example tags include 'noreagent', 'nostereo' input_root : Optional[Union[str, bytes, os.PathLike]] (Default = None) full file path to the folder containing the original raw data csv if None, we assume the original directory structure of rxn-ebm package, and set this to: path/to/rxnebm/data/original_data output_root : Optional[Union[str, bytes, os.PathLike]] (Default = None) full file path to the folder containing the output cleaned data pickle if None, we assume the original directory structure of rxn-ebm package, and set this to: path/to/rxnebm/data/cleaned_data lines_to_skip : int (Default = 1) how many header lines to skip in the CSV file This is 1 for USPTO_50k (schneider), but 3 for USPTO_STEREO, and 1 for USPTO_FULL (GLN) Unfortunately, this cannot be reliably extracted from some automatic algorithm, as every CSV file can be differently formatted keep_reagents : bool (Default = False) whether to keep reagents in the output SMILES string keep_all_rcts : bool (Default = False) whether to keep all reactants, regardless of whether they contribute any atoms to the product NOTE: GLN removes non-contributing reactants in their clean_uspto.py's main() remove_dup_rxns : bool (Default = True) whether to remove duplicate rxn_smi remove_rct_mapping : bool (Default = True) whether to remove atom mapping if atom in reactant is not in product (i.e. leaving groups) NOTE: GLN removes these atom mapping in their clean_uspto.py's get_rxn_smiles() remove_all_mapping : bool (Default = False) whether to remove all atom mapping from the reaction SMILES, if True, remove_rct_mapping will be automatically set to True save_idxs : bool (Default = True) whether to save all bad idxs to a file in the same directory as the output file parallelize : bool (Default = True) whether to parallelize the computation across all possible workers Also see: clean_rxn_smis_50k_one_phase """ if remove_all_mapping: remove_rct_mapping = True if input_root is None: input_root = Path(__file__).resolve().parents[2] / "data" / "original_data" if output_root is None: output_root = Path(__file__).resolve().parents[2] / "data" / "cleaned_data" phase_to_compute = ["train", "valid", "test"] for phase in ["train", "valid", "test"]: if (output_root / f"{output_file_prefix}_{phase}.pickle").exists(): print(f"At: {output_root / output_file_prefix}_{phase}.pickle") print("The cleaned_rxn_smi file already exists!") phase_to_compute.remove(phase) if len(phase_to_compute) == 0: return if parallelize: try: num_workers = len(os.sched_getaffinity(0)) except AttributeError: num_workers = os.cpu_count() print(f"Parallelizing over {num_workers} cores") else: print(f"Not parallelizing!") num_workers = 1 cleaned_rxn_smis = {"train": None, "valid": None, "test": None} for phase in phase_to_compute: print(f"Processing {phase}") with Pool(max_workers=num_workers) as client: future = client.submit( clean_rxn_smis_50k_one_phase, input_root / f"{input_file_prefix}_{phase}.csv", lines_to_skip=lines_to_skip, keep_reagents=keep_reagents, keep_all_rcts=keep_all_rcts, remove_rct_mapping=remove_rct_mapping, remove_all_mapping=remove_all_mapping, ) if remove_dup_rxns: # [1] is set_clean_list cleaned_rxn_smis[phase] = future.result()[1] else: cleaned_rxn_smis[phase] = future.result()[0] if save_idxs: bad_idxs = {} bad_idxs["bad_mapping_idxs"] = future.result()[2] bad_idxs["bad_prod_idxs"] = future.result()[3] bad_idxs["too_small_idxs"] = future.result()[4] bad_idxs["missing_map_idxs"] = future.result()[5] bad_idxs["dup_rxn_idxs"] = future.result()[6] with open( output_root / f"{output_file_prefix}_{phase}_badidxs.pickle", "wb" ) as handle: pickle.dump(bad_idxs, handle, protocol=pickle.HIGHEST_PROTOCOL) with open(output_root / f"{output_file_prefix}_{phase}.pickle", "wb") as handle: pickle.dump( cleaned_rxn_smis[phase], handle, protocol=pickle.HIGHEST_PROTOCOL ) ################################### ######### HELPER FUNCTIONS ######## ################################### def remove_overlapping_rxn_smis( rxn_smi_file_prefix: str = "50k_clean_rxnsmi_noreagent_allmapped", root: Optional[Union[str, bytes, os.PathLike]] = None, save_idxs: bool = False, ): """ Removes rxn_smi from train that overlap with valid/test, and rxn_smi from valid that overlap with test Has option to save indices of the removed rxn_smi as a separate pickle file for traceability """ if root is None: root = Path(__file__).resolve().parents[2] / "data" / "cleaned_data" else: root = Path(root) if ( root / f'{rxn_smi_file_prefix}_overlap_idxs.pickle' ).exists(): print(f"At: {root / f'{rxn_smi_file_prefix}_overlap_idxs.pickle'}") print("The overlap_idxs file already exists!") return rxn_smi_phases = {'train': None, 'valid': None, 'test': None} rxn_smi_phases_set = {'train': None, 'valid': None, 'test': None} for phase in rxn_smi_phases: with open(root / f'{rxn_smi_file_prefix}_{phase}.pickle', 'rb') as handle: rxn_smi_phases[phase] = pickle.load(handle) rxn_smi_phases_set[phase] = set(rxn_smi_phases[phase]) # speed up membership testing overlap_idxs = {'test_in_train': [], 'test_in_valid': [], 'valid_in_train': []} for i, rxn_smi in enumerate(tqdm(rxn_smi_phases['test'])): if rxn_smi in rxn_smi_phases_set['train']: overlap_idx = rxn_smi_phases['train'].index(rxn_smi) overlap_idxs['test_in_train'].append(overlap_idx) rxn_smi_phases['train'].pop(overlap_idx) elif rxn_smi in rxn_smi_phases_set['valid']: overlap_idx = rxn_smi_phases['valid'].index(rxn_smi) overlap_idxs['test_in_valid'].append(overlap_idx) rxn_smi_phases['valid'].pop(overlap_idx) for i, rxn_smi in enumerate(tqdm(rxn_smi_phases['valid'])): if rxn_smi in rxn_smi_phases_set['train']: overlap_idx = rxn_smi_phases['train'].index(rxn_smi) overlap_idxs['valid_in_train'].append(overlap_idx) rxn_smi_phases['train'].pop(overlap_idx) for key, value in overlap_idxs.items(): print(key, len(value)) for phase in rxn_smi_phases: print(phase, len(rxn_smi_phases[phase])) with open(root / f'{rxn_smi_file_prefix}_{phase}.pickle', 'wb') as handle: pickle.dump(rxn_smi_phases[phase], handle) if save_idxs: with open(root / f'{rxn_smi_file_prefix}_overlap_idxs.pickle', 'wb') as handle: pickle.dump(overlap_idxs, handle) if __name__ == "__main__": args = parse_args() if args.clean_smi_root: print(f"Making dir {args.clean_smi_root}") os.makedirs(args.clean_smi_root, exist_ok=True) clean_rxn_smis_50k_all_phases( args.raw_smi_pre, args.clean_smi_pre, # '50k_clean_rxnsmi_noreagent_allmapped', lines_to_skip=args.lines_to_skip, keep_all_rcts=args.keep_all_rcts, # remove_dup_rxns=args.remove_dup_rxns, # remove_rct_mapping=args.remove_rct_mapping, # remove_all_mapping=args.remove_all_mapping # ) remove_overlapping_rxn_smis( rxn_smi_file_prefix=args.clean_smi_pre, #'50k_clean_rxnsmi_noreagent_allmapped', root=args.clean_smi_root, )
lixiao7215981/LXFrameWork_OC
LXFrameWork_OC/LXFrameWork_OC/LXFrameWork/Class/Category/NSString+Extension.h
// // NSString+Extension.h // LiXiao // // Created by 李晓 on 14-10-18. // Copyright (c) 2014年 itcast. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface NSString (Size) /** * 生成唯一的 UUID */ + (NSString *) uuidString; /** * 获取设备沙盒路径 */ + (NSString *)getApplicationDocumentsDirectory; /** * 将 String 类型进行 Base64 编码 NSUTF8StringEncoding * * @param input 编码前 String * * @return 编码后 String */ + (NSString*)encodeBase64String:(NSString *)input; /** * 将 String 类型进行 Base64 解码 NSUTF8StringEncoding * * @param input 解码前 String * * @return 解码后 String */ + (NSString*)decodeBase64String:(NSString *)input; /** * 将 Data 类型进行 Base64 编码 NSUTF8StringEncoding * * @param input 编码前 String * * @return 编码后 String */ + (NSString*)encodeBase64Data:(NSData *)data; /** * 将 Data 类型进行 Base64 解码 NSUTF8StringEncoding * * @param input 解码前 String * * @return 解码后 String */ + (NSString*)decodeBase64Data:(NSData *)base64Data; /** * 将十六进制转换为普通字符串 * * @return UTF-8 类型普通字符串 */ - (NSString *)toStringFromHexString; /** * 将字符串转换为十六进制字符串 * * @return 十六进制字符串 */ - (NSString *)toHexStringFromString; /** * 将 base64 加密符串转换为十六进制字符串 * * @return 十六进制字符串 */ - (NSString *)toHexStringFromBase64String; /** * 将 Data类型加密符串转换为十六进制字符串 * * @return 十六进制字符串 */ - (NSString *) toHexStringFromData:(NSData *) data; /** * 转换成金额string * * @return ¥ 字体小于后台金额 */ - (NSAttributedString *) toMoneyString; /** * 去掉字符串左右两边的空格 * * @return 去掉空格后的字符串 */ - (NSString *) toClearBlankString; /** * 删掉字符串前边多余的 "0" */ - (NSString *) removeStringFrontZero; /** * 将NSString 转化为NSData 二进制 */ - (NSData *) stringHexToBytes; /** * 将 年月日时分秒时间转换为 仅年月日的时间 */ - (NSString *)FormatterYYYYMMDD; /** * 将 String 类型转化位 Date 类型 YYYY-MM-DD HH:mm:ss */ - (NSDate *) FormatterDateFromYMDHMS; /** * 将 String 类型转化位 Date 类型 YYYY-MM-DD */ - (NSDate *) FormatterDateFromYMD; /** * 根据传入的字体计算所占大小 * */ - (CGSize) sizeWithFont:(UIFont *) font; /** * 根据传入的字体计算所占大小 * width : 传入最大宽度计算出高度 */ - (CGSize) sizeWithFont:(UIFont *)font Width:(CGFloat) width; /** * 对 url 进行编码 * */ - (NSString *)encodeToPercentEscapeString; /** * 对 url 进行解码 * */ - (NSString *)decodeFromPercentEscapeString; @end
lingjf/h2un
test/test_matcher_cast_number2.cpp
<reponame>lingjf/h2un<filename>test/test_matcher_cast_number2.cpp #include "../source/h2_unit.cpp" #include "test_types.hpp" CASE(cast number2) { NUMBER0_DECL_LIST; NUMBER1_DECL_LIST; #define TheCheck(x, y) OK(x, y); H2Fullmesh(TheCheck, (NUMBER1_VAR_LIST)); #undef TheCheck }
nerdfiles/ng-amd-microservices-seed
server/mockRoutes.js
<gh_stars>0 var fs = require('fs'); var _ = require('lodash'); module.exports = function (app) { app.get('/api/v0/orders/:id?', function (request, response, next) { var id = request.params.id || null; var _json; var json; if (id) { try { _json = JSON.parse(fs.readFileSync(__dirname + '/../mocks/orders/' + id + '.json', 'utf8')); _.extend(_json, { status: 200 }); } catch (e) { _json = { status: 404, error: e }; } finally { json = _json; } } else if (!id) { json = { status: 200 } return response .status(json.status) .json( { _links: { self: { href: 'api/v0/orders' } }, _embedded: { 'api/v0/orders': [ { id: 42, title: 'Some item' } ] } } ) } response .setHeader('Content-Type', 'application/json'); response .status(json.status) .send(JSON.stringify(json, null, 3)); }); app.get('/api/v0/api-gateway/fugvjdxtri', function (request, response, next) { response.setHeader('Content-Type', 'application/json'); var json = JSON.parse(fs.readFileSync(__dirname + '/../mocks/api-gateway.json', 'utf8')); response.send(JSON.stringify(json, null, 3)); }); };
CiscoTestAutomation/genielibs
pkgs/sdk-pkg/src/genie/libs/sdk/apis/iosxe/cef/verify.py
import logging # Genie from genie.utils.timeout import Timeout from genie.metaparser.util.exceptions import SchemaEmptyParserError from genie.libs.sdk.libs.utils.normalize import GroupKeys # pyATS from pyats.utils.objects import find, R # CEF from genie.libs.sdk.apis.iosxe.cef.get import get_cef_repair_path_of_route log = logging.getLogger(__name__) def is_routing_repair_path_in_cef( device, prefix, max_time=60, check_interval=10, vrf='default', address_family='ipv4', ): """ Verify 'repair path' is presente in express forwarding Args: device ('obj'): Device object route ('str'): Route address max_time ('int'): Max time in seconds retrieving and checking output check_interval ('int') vrf ('str'): VRF name address_family ('str'): Address family Raises: None Returns: True False """ timeout = Timeout(max_time=max_time, interval=check_interval) while timeout.iterate(): is_present = get_cef_repair_path_of_route( device=device, prefix=prefix, vrf=vrf, address_family=address_family, ) if is_present: return True timeout.sleep() return False def verify_cef_internal_label_stack(device, vrf, prefix, stack, max_time=60, check_interval=15): """ Verify stack is programmed for prefix Args: device (`obj`): Device object vrf (`str`): VRF to check prefix (`str`): Prefix to check stack (`list`): Stack list to verify exists max_time (`int`): Maximum time to keep checking check_interval (`int`): How long to wait between checks Raises: N/A Returns: True/False """ reqs = R( [ "vrf", "(?P<vrf>{vrf})".format(vrf=vrf), "address_family", "(?P<address_family>.*)", "prefix", "(?P<prefix>.*)", "output_chain", "tag_midchain", "(?P<tag_midchain>.*)", "label", "(?P<label>.*)" ] ) timeout = Timeout(max_time, check_interval) while timeout.iterate(): try: out = device.parse('show ip cef vrf {vrf} {prefix} internal'\ .format(vrf=vrf, prefix=prefix)) except SchemaEmptyParserError: log.info("Parser output is empty") timeout.sleep() continue stack_copy = list(stack) found = find([out], reqs, filter_=False, all_keys=True) if found: for label in found[0][0]: for stack_item in stack_copy: if str(stack_item) in label: # If item found, break to prevent else block from running stack_copy.remove(stack_item) break else: # If the label is not any of the stack_items break # to prevent running next else block break else: # If items exist in stack copy that means the stack # from output had less items than expected if not stack_copy: return True else: log.info( 'The following labels are not in the output: {labels}' .format(labels=stack_copy)) timeout.sleep() return False def verify_cef_outgoing_interface(device, vrf, dst_pfx, out_intf, max_time=15, check_interval=5): """Verify outgoing interfaces for a particular prefix in cef Args: device (`obj`): Device object vrf (`str`): Vrf dst_pfx (`str`): destination prefix out_intf(`list`): List of outgoing interface to be checked, max_time (int): Maximum wait time for the trigger, in second. Default: 15 check_interval (int): Wait time between iterations when looping is needed, in second. Default: 5 Returns: True False True if outgoing interfaces is as expected, false in all other cases """ timeout = Timeout(max_time, check_interval) while timeout.iterate(): out = None res=1 try: out = device.parse("show ip cef vrf {vrf} {dst_pfx}"\ .format(vrf=vrf, dst_pfx=dst_pfx)) except SchemaEmptyParserError: pass if out: try: intfs=out.q.get_values('outgoing_interface') for intf in out_intf: if intf in intfs: log.info( "Got the expected outgoing interface {intf}"\ .format(intf=intf)) else: log.info("Outgoing interface {intf} not found"\ .format(intf=intf)) continue return True except KeyError: pass timeout.sleep() return False
team-miracle/android-libs
api-stubs_intermediates/srcjars/android/service/usb/UsbSettingsDevicePermissionProto.java
// Generated by protoc-gen-javastream. DO NOT MODIFY. // source: frameworks/base/core/proto/android/service/usb.proto package android.service.usb; /** @hide */ // message UsbSettingsDevicePermissionProto public final class UsbSettingsDevicePermissionProto { // optional string device_name = 1; public static final long DEVICE_NAME = 0x0000010900000001L; // repeated int32 uids = 2; public static final long UIDS = 0x0000020500000002L; }
realwnc/bose
src/com/mids/controller/sys/LoginController.java
<filename>src/com/mids/controller/sys/LoginController.java package com.mids.controller.sys; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.mids.ConstantsCode; import com.mids.common.Result; import com.mids.util.CaptchaUtil; import com.mids.util.MyFastjsonUtil; import com.mids.util.RandomString; import com.mids.util.RandomUtils; import com.mids.util.crypt.MyAESUtils; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.DisabledAccountException; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @description:登录退出 * @author:wncheng * @date:2015/10/1 14:51 */ @Controller @RequestMapping("/sys") public class LoginController { private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class); /** * 首页 * * @return */ /* @RequestMapping(value = "/") public String index() { LOGGER.debug("redirect:/index.do"); return "redirect:/index.do"; } */ /** * 首页 * * @param model * @return */ @RequestMapping(value = "/index") public String index(Model model) { LOGGER.debug("index"); return "/sys/main"; } /** * GET 登录 * * @param model * @param request * @return */ @RequestMapping(value = "/login", method = RequestMethod.GET) public String login(Model model, HttpServletRequest request) { LOGGER.info("--------->GET请求登录"); String uuid = RandomUtils.generateUUID().toLowerCase(); model.addAttribute("csrftoken", uuid); request.getSession().setAttribute("csrftoken", uuid); String aeskey = MyAESUtils.KEY; model.addAttribute("aeskey", aeskey); request.getSession().setAttribute("aeskey", aeskey); //return "/sys/login"; return "/sys/notlogin";//转到登录jsp,不用action是为了逃避shiro登录拦截 } /** * POST 登录 shiro 写法 * * @param username 用户名 * @param password 密码 * @param request * @param model * @return */ @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json; charset=utf-8") @ResponseBody public Result loginPost(String username, String password, String valcode, HttpServletRequest request, Model model, String csrftoken) { LOGGER.info("POST请求登录"); Result result = new Result(); if(StringUtils.isBlank(csrftoken) == true) { result.setMsg("非法请求"); return result; } String server_csrftoken = request.getSession().getAttribute("csrftoken").toString(); if(server_csrftoken.equalsIgnoreCase(csrftoken) == false) { result.setMsg("非法请求"); return result; } if (StringUtils.isBlank(username)) { result.setMsg("用户名不能为空"); return result; } if (StringUtils.isBlank(password)) { result.setMsg("密码不能为空"); return result; } if (StringUtils.isBlank(valcode)) { result.setMsg("验证码不能为空"); return result; } String sessvalcode = request.getSession(true).getAttribute("randomString").toString(); if(valcode.equalsIgnoreCase(sessvalcode) == false) { result.setMsg("验证码错误"); return result; } request.getSession(true).setAttribute("randomString", RandomString.GenerateRandStr(6)); try { username = MyAESUtils.aesDecrypt(username); Subject user = SecurityUtils.getSubject(); //String pwd=DigestUtils.md5Hex(password); //char[] pwdCharArray=DigestUtils.md5Hex(password).toCharArray(); UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray()); token.setRememberMe(true); user.login(token); user.getSession().setAttribute("username", username); } catch (UnknownAccountException e) { LOGGER.error("账号不存在:{}", e); result.setMsg("用户名或密码错误"); return result; } catch (DisabledAccountException e) { LOGGER.error("账号未启用:{}", e); result.setMsg("用户名或密码错误"); return result; } catch (IncorrectCredentialsException e) { LOGGER.error("密码错误:{}", e); result.setMsg("用户名或密码错误"); return result; } catch (Exception e) { LOGGER.error("未知错误,请联系管理员:{}", e); result.setMsg("未知错误,请联系管理员"); return result; } result.setSuccess(true); return result; } /** * 未授权 * * @param model * @return */ @RequestMapping(value = "/unauth") public String unauth(Model model) { if (SecurityUtils.getSubject().isAuthenticated() == false) { return "redirect:/sys/login"; } return "/unauth"; } /** * 退出 * * @param request * @return */ @RequestMapping(value = "/logout") @ResponseBody public Result logout(HttpServletRequest request) { LOGGER.info("登出"); Subject subject = SecurityUtils.getSubject(); Result result = new Result(); subject.logout(); result.setSuccess(true); return result; } @RequestMapping(value = "/register", method = RequestMethod.POST, produces = "application/json; charset=utf-8") @ResponseBody public void register(HttpServletRequest request, HttpServletResponse response, @RequestBody String postData){ int retcode=ConstantsCode.RETCODE_SUCCEED; String retmsg=ConstantsCode.globalMapErrorCode.get(ConstantsCode.RETCODE_SUCCEED); Map<String, Object> rootmap = new HashMap<String, Object>(); Map<String, Object> reqMap=null; try { reqMap = MyFastjsonUtil.json2Map(postData); } catch (Exception e) { retcode=ConstantsCode.RETCODE_EXCEPTION; retmsg=ConstantsCode.globalMapErrorCode.get(ConstantsCode.RETCODE_EXCEPTION); LOGGER.error("===>weixin user login exception...", e); } //if(requestParamMap==null || !requestParamMap.containsKey("mobile")) if(reqMap==null) { LOGGER.debug("==>reqeuest parameter is invalid!!!"); rootmap.put("retcode", ConstantsCode.RETCODE_ERROR_PARAMETER); rootmap.put("retmsg", ConstantsCode.globalMapErrorCode.get(ConstantsCode.RETCODE_ERROR_PARAMETER)); MyFastjsonUtil.sendJsonToResponse(rootmap, response); return; } try { } catch (Exception e) { retcode=ConstantsCode.RETCODE_EXCEPTION; retmsg=ConstantsCode.globalMapErrorCode.get(ConstantsCode.RETCODE_EXCEPTION); LOGGER.error("===>weixin user login exception...", e); } rootmap.put("retcode", retcode); rootmap.put("retmsg", retmsg); MyFastjsonUtil.sendJsonToResponse(rootmap, response); } @RequestMapping(value = "/captcha", method = RequestMethod.GET) @ResponseBody public void captcha(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CaptchaUtil.outputCaptcha(request, response); } }
bpbpublications/TEST-YOUR-SKILLS-IN-PYTHON-LANGUAGE
Chapter 04/ch4_3_13.py
<filename>Chapter 04/ch4_3_13.py print(bool (-5)) #True
gopala-kr/CR-101
something-learned/Algorithms and Data-Structures/Competitive-programming-library/CP/codefights/CodeLeader.cpp
<gh_stars>1-10 //solution by albinutte std::map<std::pair<std::vector<int>, int>, double> M; double solve(std::vector<int> V, int idx, int n, int forbidden) { using namespace std; if (idx == n) { int mmax = 0, cnt = 0; for (int i=0; i<V.size(); i++) if (V[i] > mmax) { mmax = V[i]; cnt = 1; } else if (V[i] == mmax) cnt ++; return cnt; } sort(V.begin(), V.end()); if (M.find(pair<vector<int>, int>(V, forbidden)) != M.end()) return M[pair<vector<int>, int>(V, forbidden)]; double res = 0.0; int first = 1; for (int i=0; i<V.size(); i++) { if (V[i] != forbidden || !first) { V[i] ++; res += solve(V, idx+1, n, V[i]); V[i] --; } else first = 0; } vector<int> W = V; W.push_back(1); res += (n - V.size()) * solve(W, idx+1, n, 1); res /= n-1; return M[pair<vector<int>, int>(V, forbidden)] = res; } std::string CodeLeader(int N) { using namespace std; vector<int> V; V.push_back(1); double res = solve(V, 1, N, 1); cout << res << endl; return to_string(res); }
afeng11/tomato-arm
release/src-rt-6.x.4708/router/samba-3.5.8/source4/utils/net/net.c
<filename>release/src-rt-6.x.4708/router/samba-3.5.8/source4/utils/net/net.c<gh_stars>1-10 /* Samba Unix/Linux SMB client library Distributed SMB/CIFS Server Management Utility Copyright (C) 2001 <NAME> (<EMAIL>) Copyright (C) 2001 <NAME> (<EMAIL>) Copyright (C) 2001 <NAME> (<EMAIL>) Copyright (C) 2001 <NAME> (<EMAIL>) Copyright (C) 2004 <NAME> (<EMAIL>) Largely rewritten by metze in August 2004 Originally written by Steve and Jim. Largely rewritten by tridge in November 2001. Reworked again by abartlet in December 2001 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/>. */ /*****************************************************/ /* */ /* Distributed SMB/CIFS Server Management Utility */ /* */ /* The intent was to make the syntax similar */ /* to the NET utility (first developed in DOS */ /* with additional interesting & useful functions */ /* added in later SMB server network operating */ /* systems). */ /* */ /*****************************************************/ #include "includes.h" #include "utils/net/net.h" #include "lib/cmdline/popt_common.h" #include "lib/ldb/include/ldb.h" #include "librpc/rpc/dcerpc.h" #include "param/param.h" #include "lib/events/events.h" #include "auth/credentials/credentials.h" /* run a function from a function table. If not found then call the specified usage function */ int net_run_function(struct net_context *ctx, int argc, const char **argv, const struct net_functable *functable, int (*usage_fn)(struct net_context *ctx, int argc, const char **argv)) { int i; if (argc == 0) { return usage_fn(ctx, argc, argv); } else if (argc == 1 && strequal(argv[0], "help")) { return net_help(ctx, functable); } for (i=0; functable[i].name; i++) { if (strcasecmp_m(argv[0], functable[i].name) == 0) return functable[i].fn(ctx, argc-1, argv+1); } d_printf("No command: %s\n", argv[0]); return usage_fn(ctx, argc, argv); } /* run a usage function from a function table. If not found then fail */ int net_run_usage(struct net_context *ctx, int argc, const char **argv, const struct net_functable *functable) { int i; for (i=0; functable[i].name; i++) { if (strcasecmp_m(argv[0], functable[i].name) == 0) if (functable[i].usage) { return functable[i].usage(ctx, argc-1, argv+1); } } d_printf("No usage information for command: %s\n", argv[0]); return 1; } /* main function table */ static const struct net_functable net_functable[] = { {"password", "<PASSWORD>", net_password, net_password_usage}, {"time", "get remote server's time\n", net_time, net_time_usage}, {"join", "join a domain\n", net_join, net_join_usage}, {"samdump", "dump the sam of a domain\n", net_samdump, net_samdump_usage}, {"export", "dump the sam of this domain\n", net_export, net_export_usage}, {"vampire", "join and syncronise an AD domain onto the local server\n", net_vampire, net_vampire_usage}, {"samsync", "synchronise into the local ldb the sam of an NT4 domain\n", net_samsync_ldb, net_samsync_ldb_usage}, {"user", "manage user accounts\n", net_user, net_user_usage}, {"machinepw", "Get a machine password out of our SAM\n", net_machinepw, net_machinepw_usage}, {NULL, NULL, NULL, NULL} }; int net_help(struct net_context *ctx, const struct net_functable *ftable) { int i = 0; const char *name = ftable[i].name; const char *desc = ftable[i].desc; d_printf("Available commands:\n"); while (name && desc) { d_printf("\t%s\t\t%s", name, desc); name = ftable[++i].name; desc = ftable[i].desc; } return 0; } static int net_usage(struct net_context *ctx, int argc, const char **argv) { d_printf("Usage:\n"); d_printf("net <command> [options]\n"); return 0; } /**************************************************************************** main program ****************************************************************************/ static int binary_net(int argc, const char **argv) { int opt,i; int rc; int argc_new; const char **argv_new; struct tevent_context *ev; struct net_context *ctx = NULL; poptContext pc; struct poptOption long_options[] = { POPT_AUTOHELP POPT_COMMON_SAMBA POPT_COMMON_CONNECTION POPT_COMMON_CREDENTIALS POPT_COMMON_VERSION { NULL } }; setlinebuf(stdout); pc = poptGetContext("net", argc, (const char **) argv, long_options, POPT_CONTEXT_KEEP_FIRST); while((opt = poptGetNextOpt(pc)) != -1) { switch (opt) { default: d_printf("Invalid option %s: %s\n", poptBadOption(pc, 0), poptStrerror(opt)); net_usage(ctx, argc, argv); exit(1); } } argv_new = (const char **)poptGetArgs(pc); argc_new = argc; for (i=0; i<argc; i++) { if (argv_new[i] == NULL) { argc_new = i; break; } } if (argc_new < 2) { return net_usage(ctx, argc, argv); } dcerpc_init(cmdline_lp_ctx); ev = s4_event_context_init(NULL); if (!ev) { d_printf("Failed to create an event context\n"); exit(1); } ctx = talloc(ev, struct net_context); if (!ctx) { d_printf("Failed to talloc a net_context\n"); exit(1); } ZERO_STRUCTP(ctx); ctx->lp_ctx = cmdline_lp_ctx; ctx->credentials = cmdline_credentials; ctx->event_ctx = ev; rc = net_run_function(ctx, argc_new-1, argv_new+1, net_functable, net_usage); if (rc != 0) { DEBUG(0,("return code = %d\n", rc)); } talloc_free(ev); return rc; } int main(int argc, const char **argv) { return binary_net(argc, argv); }
Davdegreat/metasploit-framework
spec/lib/rex/proto/sms/model/smtp_spec.rb
# -*- coding: binary -*- require 'spec_helper' require 'rex/proto/sms/model' RSpec.describe Rex::Proto::Sms::Model::Smtp do let(:address) { 'example.com' } let(:port) { 25 } let(:username) { 'username' } let(:password) { 'password' } let(:login_type) { :login } let(:from) { 'from' } let(:helo_domain) { 'example.com'} subject do Rex::Proto::Sms::Model::Smtp.new( address: address, port: port, username: username, password: password, login_type: login_type, from: from, helo_domain: helo_domain ) end describe '#initialize' do it 'sets address' do expect(subject.address).to eq(address) end it 'sets port' do expect(subject.port).to eq(port) end it 'sets username' do expect(subject.username).to eq(username) end it 'sets password' do expect(subject.password).to eq(password) end it 'sets login_type' do expect(subject.login_type).to eq(login_type) end it 'sets from' do expect(subject.from).to eq(from) end it 'sets helo domain' do expect(subject.helo_domain).to eq(helo_domain) end end end
magistermaks/mod-stylishoccult
src/main/java/net/darktree/stylishoccult/network/Packet.java
<gh_stars>0 package net.darktree.stylishoccult.network; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.network.PacketContext; import net.minecraft.network.PacketByteBuf; import net.minecraft.util.Identifier; public abstract class Packet { protected final Identifier identifier; public Packet( Identifier identifier ) { this.identifier = identifier; } @Environment(EnvType.CLIENT) public void client() { } public void read(PacketContext context, PacketByteBuf buffer ) { } }
jalbam/CrossBrowdy
crossbrowdy.com/_html/_doc/examples/EN/advanced/tower_defense_game_files/Input.js
<gh_stars>10-100 var Input = {}; //Class to manage input. //It will store the column and row where the mouse is over: Input.mouseData = { column: -1, row: -1 }; //Initializes the class: Input.init = function() { //Sets the mouse events: CB_Mouse.onMove ( function() { if (!Game.data.gameStarted) { return; } //If the game did not start yet, just exits. //Updates the row and column where the mouse is over: Input.mouseData = Game.Levels.getSymbolPositionFromCoordinates(CB_Mouse.getX(), CB_Mouse.getY()); if (Input.mouseData.column === -1 || Input.mouseData.row === -1) { return; } //Sets the corresponding mouse cursor: if (Game.Levels.getSymbolTypeFromMap(Input.mouseData.column, Input.mouseData.row) === Game.Levels.SYMBOL_TYPES.SOIL_UNWALKABLE_BUILDABLE) { CB_Mouse.setCSS("pointer"); } else { CB_Mouse.setCSS(); } } ); CB_Mouse.onClick ( function() { if (!Game.data.gameStarted) { return; } //If the game did not start yet, just exits. //TODO: do not perform the action if the touch event was processed already. //Updates the row and column where the mouse is over: Input.mouseData = Game.Levels.getSymbolPositionFromCoordinates(CB_Mouse.getX(), CB_Mouse.getY()); if (Input.mouseData.column === -1 || Input.mouseData.row === -1) { return; } //If we are clicking on an unwalkable and buildable area: if (Game.Levels.getSymbolTypeFromMap(Input.mouseData.column, Input.mouseData.row) === Game.Levels.SYMBOL_TYPES.SOIL_UNWALKABLE_BUILDABLE) { //TODO: call onBuildableTouched() alert("Clicked buildable soil"); } //...otherwise, if we are clicking on a tower: else if (Game.Levels.getSymbolTypeFromMap(Input.mouseData.column, Input.mouseData.row, true, "").substring(0, 6) === "TOWER_") { //TODO. alert("Clicked tower"); } } ); //Sets the touch events: //TODO: only onTouchStart event is needed. //TODO: do not perform the action if the mouse event was processed already. } //Input management (some controllers can also fire keyboard events): Input._inputProcessedLastTime = 0; Input._ignoreInputMs = 150; //Number of milliseconds that the input will be ignored after the player has been moved (to avoid moving or processing the input too fast). Input.manage = function(action) { //If not enough time has been elapsed since the last movement, exits (to avoid moving or processing the input too fast): if (CB_Device.getTiming() < Input._inputProcessedLastTime + Input._ignoreInputMs) { return; } //If the game has not started: if (!Game.data.gameStarted) { //If return, space or a button (button 1, 2 or 3) or axis from any gamepad is pressed, starts the game: if (CB_Keyboard.isKeyDown(CB_Keyboard.keys.ENTER) || CB_Keyboard.isKeyDown(CB_Keyboard.keys.SPACEBAR) || CB_Controllers.isButtonDown([1, 2, 3]) || CB_Controllers.getAxesDown().length > 0 || CB_Controllers.getAxesDown("", -1).length > 0) { if (!Game.data.musicEnabled || Game.data.musicLoaded && Game.data.musicChecked) { Game.start(CB_GEM.graphicSpritesSceneObject); } else if (Game.data.musicLoaded) { Sound.Music.check(); } else { Sound.Music.prepare(); } Input._inputProcessedLastTime = CB_Device.getTiming(); //As we have processed the input, updates the time with the new one (to avoid moving or processing the input too fast). return; } } //...otherwise, if the game has started, manages the input to move the player (if possible): else { var actionPerformed = false; //After pressing the ESC key or a specific gamepad button, ends the game: if (action === "ABORT" || CB_Keyboard.isKeyDown(CB_Keyboard.keys.ESC) || CB_Controllers.isButtonDown(9)) { Game.end("Game aborted"); actionPerformed = true; } //...otherwise, if we want to go to the previous level, goes there: else if (action === "PREVIOUS_LEVEL" || typeof(action) === "undefined" && CB_Keyboard.isKeyDown([CB_Keyboard.keys.O]) || CB_Controllers.isButtonDown(4) || CB_Controllers.isButtonDown(7)) { Game.Levels.loadPrevious(); actionPerformed = true; } //...otherwise, if we want to go to the next level, goes there: else if (action === "NEXT_LEVEL" || typeof(action) === "undefined" && CB_Keyboard.isKeyDown([CB_Keyboard.keys.P]) || CB_Controllers.isButtonDown(5) || CB_Controllers.isButtonDown(6)) { Game.Levels.loadNext(); //It will not cycle (when reaches last level, will not go to the first one). actionPerformed = true; } //...otherwise, if we want to restart the level, restarts it: else if (action === "RESTART" || typeof(action) === "undefined" && CB_Keyboard.isKeyDown([CB_Keyboard.keys.R, CB_Keyboard.keys.F9]) || CB_Controllers.isButtonDown(3)) { Game.Levels.restart(); actionPerformed = true; } //...otherwise, if we want to toggle full screen, we try it: //NOTE: some browsers will fail to enable full screen mode if it is not requested through a user-driven event (as "onClick", "onTouchStart", etc.). else if (action === "FULL_SCREEN_TOGGLE" || typeof(action) === "undefined" && CB_Keyboard.isKeyDown([CB_Keyboard.keys.F]) || CB_Controllers.isButtonDown(8)) { Visual.fullScreenToggle(); actionPerformed = true; } //If an action has performed already, just exits: if (actionPerformed) { Input._inputProcessedLastTime = CB_Device.getTiming(); //As we have processed the input, updates the time with the new one (to avoid moving or processing the input too fast). return; } //TODO. //var mapCurrent = Game.data.levelMap; } }
proteye/aero-frontend-testapp
src/components/elements/logo/index.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import themes from '@utils/themes'; import './style.less'; class Logo extends Component { static propTypes = { to: PropTypes.string, title: PropTypes.string, theme: PropTypes.oneOfType([PropTypes.string, PropTypes.array]), }; static defaultProps = { to: '/', title: '', theme: '', }; render() { const { to, title } = this.props; return ( <Link className={themes('Logo', this.props.theme)} to={to} title={title}> AERO FRONTEND </Link> ); } } export default Logo;
palanga/utils
examples/src/main/scala/examples/GraphqlExample.scala
<reponame>palanga/utils<filename>examples/src/main/scala/examples/GraphqlExample.scala<gh_stars>0 package examples import caliban.GraphQL.graphQL import caliban.schema.GenericSchema import caliban.{ GraphQL, RootResolver } import palanga.aconcagua import zio.stream.ZStream import zio.{ ExitCode, Task, URIO, ZIO } object GraphqlExample extends zio.App { case class Painter(paintings: Set[Painting], name: Name) type Name = String type Painting = String case class Queries( painter: PainterArgs => ZIO[Any, Throwable, Painter], painters: ZStream[Any, Throwable, Painter], ) case class PainterArgs(name: Name) object painters { def read(name: Name): Task[Painter] = ZIO effect data(name) def readAll: ZStream[Any, Nothing, Painter] = ZStream fromIterable data.values private val data = List( Painter(Set("<NAME>"), "<NAME>") ).map(p => p.name -> p).toMap } private val queries = Queries( painters read _.name, painters.readAll, ) object ExampleApi extends GenericSchema[Any] { val api: GraphQL[Any] = graphQL( RootResolver( queries ) ) } override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] = aconcagua.graphql .app(ExampleApi.api) .withDefaultMetrics .instrumented .run .exitCode }
Devan-Kerman/FluidVolume
src/main/java/io/github/fablabsmc/fablabs/api/fluidvolume/v1/properties/potions/CustomPotionEffectsFluidProperty.java
<filename>src/main/java/io/github/fablabsmc/fablabs/api/fluidvolume/v1/properties/potions/CustomPotionEffectsFluidProperty.java package io.github.fablabsmc.fablabs.api.fluidvolume.v1.properties.potions; import io.github.fablabsmc.fablabs.api.fluidvolume.v1.math.Fraction; import io.github.fablabsmc.fablabs.api.fluidvolume.v1.properties.FluidProperty; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntSet; import net.minecraft.fluid.Fluid; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.Tag; public class CustomPotionEffectsFluidProperty implements FluidProperty<ListTag> { @Override public ListTag merge(Fluid fluid, Fraction amountA, Fraction amountB, ListTag aData, ListTag bData) { ListTag tags = aData.copy(); for (Tag tag : aData) { tags.add(tag.copy()); } return tags; } @Override public boolean areCompatible(Fluid fluid, ListTag aData, ListTag bData) { IntSet set = new IntOpenHashSet(); for (Tag tag : aData) { CompoundTag effect = (CompoundTag) tag; set.add(effect.getInt("Id")); } for (Tag tag : bData) { CompoundTag effect = (CompoundTag) tag; if (set.contains(effect.getInt("Id"))) { return false; } } return true; } }
janesser/axon-percona-demo
src/test/java/org/axonframework/queryhandling/benchmark/AxonServerQueryBusBenchmark.java
<reponame>janesser/axon-percona-demo package org.axonframework.queryhandling.benchmark; import demo.DemoApp; import org.axonframework.axonserver.connector.query.AxonServerQueryBus; import org.axonframework.queryhandling.config.DistributedQueryBusAutoConfiguration; import org.axonframework.springboot.autoconfig.AxonAutoConfiguration; import org.axonframework.springboot.autoconfig.AxonServerAutoConfiguration; import org.junit.Ignore; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; /** * FIXME updates Flux doesn't get unblocked more than once. * * @see AxonServerQueryBus */ @Ignore @SpringBootTest(classes = { AxonServerAutoConfiguration.class, AxonAutoConfiguration.class, DemoApp.class }) @EnableAutoConfiguration(exclude = DistributedQueryBusAutoConfiguration.class) @ActiveProfiles({"spring-test-hsqldb"}) @DirtiesContext public class AxonServerQueryBusBenchmark extends AbstractQueryBusBenchmark { @Autowired public void setAxonServerQueryGateway(AxonServerQueryBus queryBus) { super.setQueryBus(queryBus); } }
KAtana-Karlsruhe/AADC_2015_KAtana
src/adtfUser/katana_mission_control/tools/demoDataGenerators/DemoPatchGenerator.cpp
<filename>src/adtfUser/katana_mission_control/tools/demoDataGenerators/DemoPatchGenerator.cpp<gh_stars>0 /** * Katana Demo Patch Filter. * $Author: philipp $ * */ #include "stdafx.h" #include "math.h" #include <fstream> #include "DemoPatchGenerator.h" /// Create filter for random number generator ADTF_FILTER_PLUGIN("KATANA Demo Patch Generator Filter", OID_ADTF_DEMO_PATCH_GENERATOR_FILTER, cDemoPatchFilter) cDemoPatchFilter::cDemoPatchFilter(const tChar* __info) : adtf::cTimeTriggeredFilter(__info) { m_numberOfPatches = -1; m_cycle = 0; m_points = nullptr; m_types = nullptr; m_thetas = nullptr; m_upper_left = katana::Point(23000, 5000); m_down_right = katana::Point(4000, -5000); m_enable_field_of_view = true; SetPropertyInt("Interval", 500000); //500ms = 2Hz SetPropertyBool("Enable field of view", m_enable_field_of_view); SetPropertyStr("Configuration File For Patches",""); SetPropertyBool("Configuration File For Patches" NSSUBPROP_FILENAME, tTrue); SetPropertyStr("Configuration File For Patches" NSSUBPROP_FILENAME NSSUBSUBPROP_EXTENSIONFILTER, "CSV Files (*.csv)"); } cDemoPatchFilter::~cDemoPatchFilter() { } tResult cDemoPatchFilter::initializePatchArray() { cFilename fileConfig = GetPropertyStr("Configuration File For Patches"); if (fileConfig.IsEmpty()) { LOG_ERROR("DemoPatchGenerator: Configured configuration file not found"); RETURN_ERROR(ERR_INVALID_FILE); } ADTF_GET_CONFIG_FILENAME(fileConfig); fileConfig = fileConfig.CreateAbsolutePath("."); if (cFileSystem::Exists(fileConfig)) { calculateNumberOfPatches(fileConfig); std::ifstream infile(fileConfig); tInt32 x,y, type; tFloat32 theta; tInt32 count = 0; m_points = new katana::Point [m_numberOfPatches]; m_thetas = new tFloat32[m_numberOfPatches]; m_types = new tInt32[m_numberOfPatches]; while (infile >> x >> y >> theta >> type && count < m_numberOfPatches) { m_points[count] = katana::Point(x,y); m_thetas[count] = theta; m_types[count] = type; LOG_INFO(adtf_util::cString::Format("DemoPatchGenerator: initialized Patch no.: %d x %d y %d theta %f type %d",count,x,y,theta,type)); count++; } } else { LOG_ERROR(adtf_util::cString::Format("Patch configuration file not found.")); RETURN_ERROR(ERR_INVALID_FILE); } RETURN_NOERROR; } tResult cDemoPatchFilter::calculateNumberOfPatches(cFilename fileConfig) { std::ifstream file(fileConfig); tInt32 counter = 0; tInt32 x,y, type; tFloat32 theta; while (file >> x >> y >> theta >> type) { counter++; } m_numberOfPatches = counter; RETURN_NOERROR; } tResult cDemoPatchFilter::Init(tInitStage eStage, __exception) { RETURN_IF_FAILED(cTimeTriggeredFilter::Init(eStage, __exception_ptr)); if (eStage == StageFirst) { CreateOutputPins(__exception_ptr); } else if (eStage == StageNormal) { tInt nGenerateRate = GetPropertyInt("Interval"); m_numberDataValues = GetPropertyInt("Numer Data Values"); m_enable_field_of_view = GetPropertyBool("Enable field of view"); RETURN_IF_FAILED(initializePatchArray()); RETURN_IF_FAILED(SetInterval(nGenerateRate)); } else if (eStage == StageGraphReady){ } RETURN_NOERROR; } tResult cDemoPatchFilter::Shutdown(tInitStage eStage, __exception) { if (eStage == StageGraphReady) { } else if (eStage == StageNormal) { if(m_points != nullptr){ delete[] m_points; } m_points = nullptr; if(m_thetas != nullptr) { delete[] m_thetas; } m_thetas = nullptr; if(m_types != nullptr) { delete[] m_types; } m_types = nullptr; } else if (eStage == StageFirst) { } return cTimeTriggeredFilter::Shutdown(eStage, __exception_ptr); } tResult cDemoPatchFilter::CreateOutputPins(__exception) { // patch output RETURN_IF_FAILED(m_oPinOutput.Create("demo_patches", new adtf::cMediaType(MEDIA_TYPE_STRUCTURED_DATA, MEDIA_SUBTYPE_STRUCT_STRUCTURED), static_cast<IPinEventSink*> (this))); RETURN_IF_FAILED(RegisterPin(&m_oPinOutput)); // create pose input pin without media description RETURN_IF_FAILED(m_ipin_pose.Create("pose_buffer" , new adtf::cMediaType(MEDIA_TYPE_STRUCTURED_DATA, MEDIA_SUBTYPE_STRUCT_STRUCTURED), static_cast<IPinEventSink*> (this))); RETURN_IF_FAILED(RegisterPin(&m_ipin_pose)); /* // get pose media type for the pose output pin strDescSignalValue = pDescManager->GetMediaDescription("tPose"); RETURN_IF_POINTER_NULL(strDescSignalValue); cObjectPtr<IMediaType> pTypePoseValueOutput = new cMediaType(0, 0, 0, "tPose", strDescSignalValue, IMediaDescription::MDF_DDL_DEFAULT_VERSION); RETURN_IF_FAILED(pTypePoseValueOutput->GetInterface(IID_ADTF_MEDIA_TYPE_DESCRIPTION, (tVoid**)&m_pCoderDescSignalOutputPose)); // create and register the output pin RETURN_IF_FAILED(m_opin_pose.Create("pose", pTypePoseValueOutput, this)); RETURN_IF_FAILED(RegisterPin(&m_opin_pose)); */ RETURN_NOERROR; } tResult cDemoPatchFilter::Cycle(__exception) { if(m_numberOfPatches == -1) { std::cout << "Points not correctly initialized"; RETURN_ERROR(ERR_FILE_NOT_FOUND); } // if(m_cycle % 2 == 0) { // Create Mediasample std::vector<u_int32_t> patches; // choose patches in field of view if (m_enable_field_of_view) { for (int32_t i = 0; i < m_numberOfPatches; i++) { katana::Point veh_coord = m_pose.transformToVehicle(katana::Point(m_points[i].x(), m_points[i].y())); if(veh_coord.getX() < m_down_right.getX() || veh_coord.getX() > m_upper_left.getX() || veh_coord.getY() < m_down_right.getY() || veh_coord.getY() > m_upper_left.getY()) { continue; } // patch pose with index i is in field of view: patches.push_back(i); } } else { patches.push_back(m_cycle % m_numberOfPatches); patches.push_back((m_cycle+1) % m_numberOfPatches); patches.push_back((m_cycle+2) % m_numberOfPatches); patches.push_back((m_cycle+3) % m_numberOfPatches); m_cycle += 3; } // array for sending katana::sPatch s[patches.size()]; for (size_t i = 0; i < patches.size(); i++) { u_int32_t num = patches[i]; s[i].sp.x = m_points[num].x(); s[i].sp.y = m_points[num].y(); s[i].sp.theta = m_thetas[num]; // leave ids out so mc can insert "virtual" patches for junctions s[i].id = num * 5; s[i].patch_type = m_types[num]; } // alloc media sample and send // transmit number of patches and patches themselves const std::size_t number_size = sizeof(u_int8_t); u_int8_t number_of_patches = patches.size() < 256 ? (u_int8_t)patches.size() : 255; const std::size_t patchsize = patches.size() * sizeof(katana::sPatch); cObjectPtr<IMediaSample> pMediaSample; RETURN_IF_FAILED(AllocMediaSample((tVoid**)&pMediaSample)); RETURN_IF_FAILED(pMediaSample->AllocBuffer(patchsize + number_size)); RETURN_IF_FAILED(pMediaSample->CopyBufferFrom(&number_of_patches, number_size, 0, 0)); RETURN_IF_FAILED(pMediaSample->CopyBufferFrom(s, patchsize, 0, number_size)); RETURN_IF_FAILED(pMediaSample->SetTime(_clock->GetStreamTime())); m_oPinOutput.Transmit(pMediaSample); m_cycle++; RETURN_NOERROR; } tResult cDemoPatchFilter::OnPinEvent(IPin* pSource, tInt nEventCode, tInt nParam1, tInt nParam2, IMediaSample* pMediaSample) { // first check what kind of event it is if (nEventCode == IPinEventSink::PE_MediaSampleReceived) { // so we received a media sample, so this pointer better be valid. RETURN_IF_POINTER_NULL(pMediaSample); // by comparing it to our member pin variable we can find out which pin received // the sample if (pSource == &m_ipin_pose) { katana::sPose sp; pMediaSample->CopyBufferTo(&sp, sizeof(katana::sPose), 0, 0); m_pose.setX(sp.x); m_pose.setY(sp.y); m_pose.setTheta(sp.theta); } } RETURN_NOERROR; }
forkkit/webiny-js
packages/app-forms/src/editor/plugins/triggers/redirect.js
<filename>packages/app-forms/src/editor/plugins/triggers/redirect.js import React from "react"; import { Grid, Cell } from "@webiny/ui/Grid"; import { Input } from "@webiny/ui/Input"; import { ReactComponent as LinkIcon } from "./icons/round-link-24px.svg"; import { ButtonPrimary } from "@webiny/ui/Button"; import { get } from "lodash"; import { i18n } from "@webiny/app/i18n"; import { Alert } from "@webiny/ui/Alert"; const t = i18n.namespace("FormsApp.Editor.RedirectTriggerSettings"); export default { type: "form-editor-trigger", name: "form-editor-trigger-redirect", trigger: { id: "redirect", title: "Redirect", description: "Send a user to a specific URL.", icon: <LinkIcon />, renderSettings({ Bind, submit, form }) { const hasSuccessMessage = get(form, "settings.successMessage.values.length") > 0; return ( <Grid> <Cell span={12}> {hasSuccessMessage && ( <Alert type="warning" title="Success message set"> {t`This form has a success message set. Note that it will not be visible if a redirect is set.`} </Alert> )} <Bind name={"url"}> <Input label={t`Redirect URL`} /> </Bind> </Cell> <Cell> <ButtonPrimary onClick={submit}>{t`Save`}</ButtonPrimary> </Cell> </Grid> ); } } };
addstone/unrealengine3
Development/External/wxWindows_2.4.0/src/msw/tbarmsw.cpp
<filename>Development/External/wxWindows_2.4.0/src/msw/tbarmsw.cpp ///////////////////////////////////////////////////////////////////////////// // Name: tbarmsw.cpp // Purpose: wxToolBar // Author: <NAME> // Modified by: 13.12.99 by VZ during toolbar classes reorganization // Created: 04/01/98 // RCS-ID: $Id: tbarmsw.cpp,v 1.23 2002/03/25 23:14:33 VZ Exp $ // Copyright: (c) <NAME> and <NAME> // Licence: wxWindows license ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- #ifdef __GNUG__ #pragma implementation "tbarmsw.h" #endif // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif #if wxUSE_TOOLBAR && defined(__WIN16__) #if !defined(__WIN32__) && !wxUSE_IMAGE_LOADING_IN_MSW #error wxToolBar needs wxUSE_IMAGE_LOADING_IN_MSW under Win16 #endif #if !defined(__GNUWIN32__) && !defined(__SALFORDC__) #include "malloc.h" #endif #if !defined(__MWERKS__) && !defined(__SALFORDC__) #include <memory.h> #endif #include <stdlib.h> #include "wx/msw/tbarmsw.h" #include "wx/event.h" #include "wx/app.h" #include "wx/bitmap.h" #include "wx/msw/private.h" #include "wx/msw/dib.h" // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- #define DEFAULTBITMAPX 16 #define DEFAULTBITMAPY 15 #define DEFAULTBUTTONX 24 #define DEFAULTBUTTONY 22 #define DEFAULTBARHEIGHT 27 // // States (not all of them currently used) // #define wxTBSTATE_CHECKED 0x01 // radio button is checked #define wxTBSTATE_PRESSED 0x02 // button is being depressed (any style) #define wxTBSTATE_ENABLED 0x04 // button is enabled #define wxTBSTATE_HIDDEN 0x08 // button is hidden #define wxTBSTATE_INDETERMINATE 0x10 // button is indeterminate // ---------------------------------------------------------------------------- // private classes // ---------------------------------------------------------------------------- class WXDLLEXPORT wxToolBarTool : public wxToolBarToolBase { public: wxToolBarTool(wxToolBar *tbar, int id, const wxBitmap& bmpNormal, const wxBitmap& bmpDisabled, bool toggle, wxObject *clientData, const wxString& shortHelp, const wxString& longHelp) : wxToolBarToolBase(tbar, id, bmpNormal, bmpDisabled, toggle, clientData, shortHelp, longHelp) { } wxToolBarTool(wxToolBar *tbar, wxControl *control) : wxToolBarToolBase(tbar, control) { } void SetSize(const wxSize& size) { m_width = size.x; m_height = size.y; } long GetWidth() const { return m_width; } long GetHeight() const { return m_height; } wxCoord m_x; wxCoord m_y; wxCoord m_width; wxCoord m_height; }; // ---------------------------------------------------------------------------- // wxWin macros // ---------------------------------------------------------------------------- #if !USE_SHARED_LIBRARY IMPLEMENT_DYNAMIC_CLASS(wxToolBar, wxToolBarBase) BEGIN_EVENT_TABLE(wxToolBar, wxToolBarBase) EVT_PAINT(wxToolBar::OnPaint) EVT_MOUSE_EVENTS(wxToolBar::OnMouseEvent) END_EVENT_TABLE() #endif // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // wxToolBarTool // ---------------------------------------------------------------------------- wxToolBarToolBase *wxToolBar::CreateTool(int id, const wxString& label, const wxBitmap& bmpNormal, const wxBitmap& bmpDisabled, wxItemKind kind, wxObject *clientData, const wxString& shortHelp, const wxString& longHelp) { return new wxToolBarTool(this, id, label, bmpNormal, bmpDisabled, kind, clientData, shortHelp, longHelp); } wxToolBarToolBase *wxToolBar::CreateTool(wxControl *control) { return new wxToolBarTool(this, control); } // ---------------------------------------------------------------------------- // wxToolBar // ---------------------------------------------------------------------------- void wxToolBar::Init() { m_hbrDither = 0; m_rgbFace = 0; m_rgbShadow = 0; m_rgbHilight = 0; m_rgbFrame = 0; m_hdcMono = 0; m_hbmMono = 0; m_hbmDefault = 0; m_defaultWidth = DEFAULTBITMAPX; m_defaultHeight = DEFAULTBITMAPY; m_xPos = m_yPos = -1; m_maxWidth = m_maxHeight = 0; m_pressedTool = m_currentTool = -1; m_toolPacking = 1; m_toolSeparation = 5; } bool wxToolBar::Create(wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) { if ( !wxWindow::Create(parent, id, pos, size, style, name) ) return FALSE; if ( style & wxTB_HORIZONTAL ) { m_lastX = 3; m_lastY = 7; } else { m_lastX = 7; m_lastY = 3; } // Set it to grey SetBackgroundColour(wxColour(192, 192, 192)); InitGlobalObjects(); return TRUE; } wxToolBar::~wxToolBar() { FreeGlobalObjects(); } void wxToolBar::SetToolBitmapSize(const wxSize& size) { m_defaultWidth = size.x; m_defaultHeight = size.y; FreeGlobalObjects(); InitGlobalObjects(); } // The button size is bigger than the bitmap size wxSize wxToolBar::GetToolSize() const { return wxSize(m_defaultWidth + 8, m_defaultHeight + 7); } wxToolBarToolBase *wxToolBar::FindToolForPosition(wxCoord x, wxCoord y) const { wxToolBarToolsList::Node *node = m_tools.GetFirst(); while (node) { wxToolBarTool *tool = (wxToolBarTool *)node->GetData(); if ((x >= tool->m_x) && (y >= tool->m_y) && (x <= (tool->m_x + tool->GetWidth())) && (y <= (tool->m_y + tool->GetHeight()))) { return tool; } node = node->GetNext(); } return (wxToolBarToolBase *)NULL; } wxToolBarToolBase *wxToolBar::AddTool(int id, const wxBitmap& bitmap, const wxBitmap& pushedBitmap, bool toggle, wxCoord xPos, wxCoord yPos, wxObject *clientData, const wxString& helpString1, const wxString& helpString2) { // rememeber the position for DoInsertTool() m_xPos = xPos; m_yPos = yPos; return wxToolBarBase::AddTool(id, bitmap, pushedBitmap, toggle, xPos, yPos, clientData, helpString1, helpString2); } void wxToolBar::OnPaint(wxPaintEvent& event) { wxPaintDC dc(this); static int wxOnPaintCount = 0; // Prevent reentry of OnPaint which would cause // wxMemoryDC errors. if (wxOnPaintCount > 0) return; wxOnPaintCount++; wxToolBarToolsList::Node *node = m_tools.GetFirst(); while (node) { wxToolBarToolBase *tool = node->GetData(); if ( tool->GetStyle()!= wxTOOL_STYLE_BUTTON ) { int state = tool->IsEnabled() ? wxTBSTATE_ENABLED : 0; if ( tool->IsToggled() ) state |= wxTBSTATE_CHECKED; DrawTool(dc, tool, state); } node = node->GetNext(); } wxOnPaintCount--; } // If a Button is disabled, then NO function (besides leaving // or entering) should be carried out. Therefore the additions // of 'enabled' testing (<NAME>). void wxToolBar::OnMouseEvent(wxMouseEvent& event) { static wxToolBarToolBase *eventCurrentTool = NULL; wxClientDC dc(this); if (event.Leaving()) { m_currentTool = -1; if (eventCurrentTool && eventCurrentTool->IsEnabled()) { ::ReleaseCapture(); int state = wxTBSTATE_ENABLED; if (eventCurrentTool->IsToggled()) state |= wxTBSTATE_CHECKED; DrawTool(dc, eventCurrentTool, state); eventCurrentTool = NULL; } OnMouseEnter(-1); return; } wxCoord x, y; event.GetPosition(&x, &y); wxToolBarToolBase *tool = FindToolForPosition(x, y); if (!tool) { if (eventCurrentTool && eventCurrentTool->IsEnabled()) { ::ReleaseCapture(); int state = wxTBSTATE_ENABLED; if (eventCurrentTool->IsToggled()) state |= wxTBSTATE_CHECKED; DrawTool(dc, eventCurrentTool, state); eventCurrentTool = NULL; } if (m_currentTool > -1) { m_currentTool = -1; OnMouseEnter(-1); } return; } if (!event.Dragging() && !event.IsButton()) { if (tool->GetId() != m_currentTool) { OnMouseEnter(m_currentTool = tool->GetId()); return; } } if (event.Dragging() && tool->IsEnabled()) { if (eventCurrentTool) { // Might have dragged outside tool if (eventCurrentTool != tool) { int state = wxTBSTATE_ENABLED; if (tool->IsToggled()) state |= wxTBSTATE_CHECKED; DrawTool(dc, tool, state); eventCurrentTool = NULL; return; } } else { if (tool && event.LeftIsDown() && tool->IsEnabled()) { eventCurrentTool = tool; ::SetCapture((HWND) GetHWND()); int state = wxTBSTATE_ENABLED|wxTBSTATE_PRESSED; if (tool->IsToggled()) state |= wxTBSTATE_CHECKED; DrawTool(dc, tool, state); } } } if (event.LeftDown() && tool->IsEnabled()) { eventCurrentTool = tool; ::SetCapture((HWND) GetHWND()); int state = wxTBSTATE_ENABLED|wxTBSTATE_PRESSED; if (tool->IsToggled()) state |= wxTBSTATE_CHECKED; DrawTool(dc, tool, state); } else if (event.LeftUp() && tool->IsEnabled()) { if (eventCurrentTool) ::ReleaseCapture(); if (eventCurrentTool == tool) { if (tool->CanBeToggled()) { tool->Toggle(); if (!OnLeftClick(tool->GetId(), tool->IsToggled())) { tool->Toggle(); } int state = wxTBSTATE_ENABLED; if (tool->IsToggled()) state |= wxTBSTATE_CHECKED; DrawTool(dc, tool, state); } else { int state = wxTBSTATE_ENABLED; if (tool->IsToggled()) state |= wxTBSTATE_CHECKED; DrawTool(dc, tool, state); OnLeftClick(tool->GetId(), tool->IsToggled()); } } eventCurrentTool = NULL; } else if (event.RightDown() && tool->IsEnabled()) { OnRightClick(tool->GetId(), x, y); } } void wxToolBar::DoEnableTool(wxToolBarToolBase *tool, bool WXUNUSED(enable)) { DoRedrawTool(tool); } void wxToolBar::DoToggleTool(wxToolBarToolBase *tool, bool WXUNUSED(toggle)) { DoRedrawTool(tool); } void wxToolBar::DoSetToggle(wxToolBarToolBase * WXUNUSED(tool), bool WXUNUSED(toggle)) { // nothing to do } void wxToolBar::DoRedrawTool(wxToolBarToolBase *tool) { wxClientDC dc(this); DrawTool(dc, tool); } void wxToolBar::DrawTool(wxDC& dc, wxToolBarToolBase *toolBase, int state) { wxToolBarTool *tool = (wxToolBarTool *)toolBase; DrawButton(dc.GetHDC(), tool->m_x, tool->m_y, tool->GetWidth(), tool->GetHeight(), tool, state); } void wxToolBar::DrawTool(wxDC& dc, wxToolBarToolBase *tool) { int state = 0; if (tool->IsEnabled()) state |= wxTBSTATE_ENABLED; if (tool->IsToggled()) state |= wxTBSTATE_CHECKED; // how can i access the PRESSED state??? DrawTool(dc, tool, state); } bool wxToolBar::DoDeleteTool(size_t WXUNUSED(pos), wxToolBarToolBase *tool) { // VZ: didn't test whether it works, but why not... tool->Detach(); Refresh(); return TRUE; } bool wxToolBar::DoInsertTool(size_t pos, wxToolBarToolBase *toolBase) { wxToolBarTool *tool = (wxToolBarTool *)toolBase; wxCHECK_MSG( !tool->IsControl(), FALSE, _T("generic wxToolBar doesn't support controls") ); // TODO: use the mapping code from wxToolBar95 to get it right in this class #if !defined(__WIN32__) && !defined(__WIN386__) wxBitmap bmpDisabled; if (tool->CanBeToggled()) { HBITMAP hbmp = CreateMappedBitmap((WXHINSTANCE)wxGetInstance(), GetHbitmapOf(tool->GetBitmap1())); wxBitmap bmp; bmp.SetHBITMAP((WXHBITMAP)hbmp); tool->SetBitmap2(bmp); } #endif tool->m_x = m_xPos; if ( tool->m_x == -1 ) tool->m_x = m_xMargin; tool->m_y = m_yPos; if ( tool->m_y == -1 ) tool->m_y = m_yMargin; tool->SetSize(GetToolSize()); if ( tool->IsButton() ) { // Calculate reasonable max size in case Layout() not called if ((tool->m_x + tool->GetBitmap1().GetWidth() + m_xMargin) > m_maxWidth) m_maxWidth = (tool->m_x + tool->GetWidth() + m_xMargin); if ((tool->m_y + tool->GetBitmap1().GetHeight() + m_yMargin) > m_maxHeight) m_maxHeight = (tool->m_y + tool->GetHeight() + m_yMargin); } return TRUE; } bool wxToolBar::Realize() { m_currentRowsOrColumns = 0; m_lastX = m_xMargin; m_lastY = m_yMargin; int maxToolWidth = 0; int maxToolHeight = 0; m_maxWidth = 0; m_maxHeight = 0; // Find the maximum tool width and height wxToolBarToolsList::Node *node = m_tools.GetFirst(); while (node) { wxToolBarTool *tool = (wxToolBarTool *)node->GetData(); if (tool->GetWidth() > maxToolWidth) maxToolWidth = tool->GetWidth(); if (tool->GetHeight() > maxToolHeight) maxToolHeight = tool->GetHeight(); node = node->GetNext(); } int separatorSize = m_toolSeparation; node = m_tools.GetFirst(); while (node) { wxToolBarTool *tool = (wxToolBarTool *)node->GetData(); if (tool->GetStyle() == wxTOOL_STYLE_SEPARATOR) { if ( GetWindowStyleFlag() & wxTB_HORIZONTAL ) { if (m_currentRowsOrColumns >= m_maxCols) m_lastY += separatorSize; else m_lastX += separatorSize; } else { if (m_currentRowsOrColumns >= m_maxRows) m_lastX += separatorSize; else m_lastY += separatorSize; } } else if (tool->GetStyle() == wxTOOL_STYLE_BUTTON) { if ( GetWindowStyleFlag() & wxTB_HORIZONTAL ) { if (m_currentRowsOrColumns >= m_maxCols) { m_currentRowsOrColumns = 0; m_lastX = m_xMargin; m_lastY += maxToolHeight + m_toolPacking; } tool->m_x = (long) (m_lastX + (maxToolWidth - tool->GetWidth())/2.0); tool->m_y = (long) (m_lastY + (maxToolHeight - tool->GetHeight())/2.0); m_lastX += maxToolWidth + m_toolPacking; } else { if (m_currentRowsOrColumns >= m_maxRows) { m_currentRowsOrColumns = 0; m_lastX += (maxToolWidth + m_toolPacking); m_lastY = m_yMargin; } tool->m_x = (long) (m_lastX + (maxToolWidth - tool->GetWidth())/2.0); tool->m_y = (long) (m_lastY + (maxToolHeight - tool->GetHeight())/2.0); m_lastY += maxToolHeight + m_toolPacking; } m_currentRowsOrColumns ++; } if (m_lastX > m_maxWidth) m_maxWidth = m_lastX; if (m_lastY > m_maxHeight) m_maxHeight = m_lastY; node = node->GetNext(); } if ( GetWindowStyleFlag() & wxTB_HORIZONTAL ) { m_maxWidth += maxToolWidth; m_maxHeight += maxToolHeight; } else { m_maxWidth += maxToolWidth; m_maxHeight += maxToolHeight; } m_maxWidth += m_xMargin; m_maxHeight += m_yMargin; SetSize(m_maxWidth, m_maxHeight); return TRUE; } bool wxToolBar::InitGlobalObjects() { GetSysColors(); if (!CreateDitherBrush()) return FALSE; m_hdcMono = (WXHDC) CreateCompatibleDC(NULL); if (!m_hdcMono) return FALSE; m_hbmMono = (WXHBITMAP) CreateBitmap((int)GetToolSize().x, (int)GetToolSize().y, 1, 1, NULL); if (!m_hbmMono) return FALSE; m_hbmDefault = (WXHBITMAP) SelectObject((HDC) m_hdcMono, (HBITMAP) m_hbmMono); return TRUE; } void wxToolBar::FreeGlobalObjects() { FreeDitherBrush(); if (m_hdcMono) { if (m_hbmDefault) { SelectObject((HDC) m_hdcMono, (HBITMAP) m_hbmDefault); m_hbmDefault = 0; } DeleteDC((HDC) m_hdcMono); // toast the DCs } m_hdcMono = 0; if (m_hbmMono) DeleteObject((HBITMAP) m_hbmMono); m_hbmMono = 0; } // ---------------------------------------------------------------------------- // drawing routines // ---------------------------------------------------------------------------- void wxToolBar::PatB(WXHDC hdc,int x,int y,int dx,int dy, long rgb) { RECT rc; rc.left = x; rc.top = y; rc.right = x + dx; rc.bottom = y + dy; SetBkColor((HDC) hdc,rgb); ExtTextOut((HDC) hdc,0,0,ETO_OPAQUE,&rc,NULL,0,NULL); } // create a mono bitmap mask: // 1's where color == COLOR_BTNFACE || COLOR_HILIGHT // 0's everywhere else void wxToolBar::CreateMask(WXHDC hdc, int xoffset, int yoffset, int dx, int dy) { HDC globalDC = ::GetDC(NULL); HDC hdcGlyphs = CreateCompatibleDC((HDC) globalDC); ReleaseDC(NULL, (HDC) globalDC); // krj - create a new bitmap and copy the image from hdc. //HBITMAP bitmapOld = SelectObject(hdcGlyphs, hBitmap); HBITMAP hBitmap = CreateCompatibleBitmap((HDC) hdc, dx, dy); HBITMAP bitmapOld = (HBITMAP) SelectObject(hdcGlyphs, hBitmap); BitBlt(hdcGlyphs, 0,0, dx, dy, (HDC) hdc, 0, 0, SRCCOPY); // initalize whole area with 1's PatBlt((HDC) m_hdcMono, 0, 0, dx, dy, WHITENESS); // create mask based on color bitmap // convert this to 1's SetBkColor(hdcGlyphs, m_rgbFace); BitBlt((HDC) m_hdcMono, xoffset, yoffset, (int)GetToolBitmapSize().x, (int)GetToolBitmapSize().y, hdcGlyphs, 0, 0, SRCCOPY); // convert this to 1's SetBkColor(hdcGlyphs, m_rgbHilight); // OR in the new 1's BitBlt((HDC) m_hdcMono, xoffset, yoffset, (int)GetToolBitmapSize().x, (int)GetToolBitmapSize().y, hdcGlyphs, 0, 0, SRCPAINT); SelectObject(hdcGlyphs, bitmapOld); DeleteObject(hBitmap); DeleteDC(hdcGlyphs); } void wxToolBar::DrawBlankButton(WXHDC hdc, int x, int y, int dx, int dy, int state) { // face color PatB(hdc, x, y, dx, dy, m_rgbFace); if (state & wxTBSTATE_PRESSED) { PatB(hdc, x + 1, y, dx - 2, 1, m_rgbFrame); PatB(hdc, x + 1, y + dy - 1, dx - 2, 1, m_rgbFrame); PatB(hdc, x, y + 1, 1, dy - 2, m_rgbFrame); PatB(hdc, x + dx - 1, y +1, 1, dy - 2, m_rgbFrame); PatB(hdc, x + 1, y + 1, 1, dy-2, m_rgbShadow); PatB(hdc, x + 1, y + 1, dx-2, 1, m_rgbShadow); } else { PatB(hdc, x + 1, y, dx - 2, 1, m_rgbFrame); PatB(hdc, x + 1, y + dy - 1, dx - 2, 1, m_rgbFrame); PatB(hdc, x, y + 1, 1, dy - 2, m_rgbFrame); PatB(hdc, x + dx - 1, y + 1, 1, dy - 2, m_rgbFrame); dx -= 2; dy -= 2; PatB(hdc, x + 1, y + 1, 1, dy - 1, m_rgbHilight); PatB(hdc, x + 1, y + 1, dx - 1, 1, m_rgbHilight); PatB(hdc, x + dx, y + 1, 1, dy, m_rgbShadow); PatB(hdc, x + 1, y + dy, dx, 1, m_rgbShadow); PatB(hdc, x + dx - 1, y + 2, 1, dy - 2, m_rgbShadow); PatB(hdc, x + 2, y + dy - 1, dx - 2, 1, m_rgbShadow); } } void wxToolBar::DrawButton(WXHDC hdc, int x, int y, int dx, int dy, wxToolBarToolBase *toolBase, int state) { wxToolBarTool *tool = (wxToolBarTool *)toolBase; int yOffset; HBRUSH hbrOld, hbr; BOOL bMaskCreated = FALSE; int xButton = 0; // assume button is down int dxFace, dyFace; int xCenterOffset; dxFace = dx; dyFace = dy; // HBITMAP hBitmap = (HBITMAP) tool->m_bitmap1.GetHBITMAP(); HDC globalDC = ::GetDC(NULL); HDC hdcGlyphs = CreateCompatibleDC(globalDC); ReleaseDC(NULL, globalDC); // get the proper button look - up or down. if (!(state & (wxTBSTATE_PRESSED | wxTBSTATE_CHECKED))) { xButton = dx; // use 'up' version of button dxFace -= 2; dyFace -= 2; // extents to ignore button highlight } DrawBlankButton(hdc, x, y, dx, dy, state); // move coordinates inside border and away from upper left highlight. // the extents change accordingly. x += 2; y += 2; dxFace -= 3; dyFace -= 3; // Using bmpDisabled can cause problems (don't know why!) #if !defined(__WIN32__) && !defined(__WIN386__) HBITMAP bitmapOld; if (tool->GetBitmap2().Ok()) bitmapOld = GetHbitmapOf(tool->GetBitmap2()); else bitmapOld = GetHbitmapOf(tool->GetBitmap1()); #else HBITMAP bitmapOld = GetHbitmapOf(tool->GetBitmap1()); #endif bitmapOld = (HBITMAP)SelectObject(hdcGlyphs, bitmapOld); // calculate offset of face from (x,y). y is always from the top, // so the offset is easy. x needs to be centered in face. yOffset = 1; xCenterOffset = (dxFace - (int)GetToolBitmapSize().x)/2; if (state & (wxTBSTATE_PRESSED | wxTBSTATE_CHECKED)) { // pressed state moves down and to the right // (x moves automatically as face size grows) yOffset++; } // now put on the face if (state & wxTBSTATE_ENABLED) { // regular version BitBlt((HDC) hdc, x+xCenterOffset, y + yOffset, (int)GetToolBitmapSize().x, (int)GetToolBitmapSize().y, hdcGlyphs, 0, 0, SRCCOPY); } else { // disabled version (or indeterminate) bMaskCreated = TRUE; CreateMask((WXHDC) hdcGlyphs, xCenterOffset, yOffset, dxFace, dyFace); // CreateMask(hBitmap, xCenterOffset, yOffset, dxFace, dyFace); SetTextColor((HDC) hdc, 0L); // 0's in mono -> 0 (for ROP) SetBkColor((HDC) hdc, 0x00FFFFFF); // 1's in mono -> 1 // draw glyph's white understrike if (!(state & wxTBSTATE_INDETERMINATE)) { hbr = CreateSolidBrush(m_rgbHilight); if (hbr) { hbrOld = (HBRUSH) SelectObject((HDC) hdc, hbr); if (hbrOld) { // draw hilight color where we have 0's in the mask BitBlt((HDC) hdc, x + 1, y + 1, dxFace, dyFace, (HDC) m_hdcMono, 0, 0, 0x00B8074A); SelectObject((HDC) hdc, hbrOld); } DeleteObject(hbr); } } // gray out glyph hbr = CreateSolidBrush(m_rgbShadow); if (hbr) { hbrOld = (HBRUSH) SelectObject((HDC) hdc, hbr); if (hbrOld) { // draw the shadow color where we have 0's in the mask BitBlt((HDC) hdc, x, y, dxFace, dyFace, (HDC) m_hdcMono, 0, 0, 0x00B8074A); SelectObject((HDC) hdc, hbrOld); } DeleteObject(hbr); } if (state & wxTBSTATE_CHECKED) { BitBlt((HDC) m_hdcMono, 1, 1, dxFace - 1, dyFace - 1, (HDC) m_hdcMono, 0, 0, SRCAND); } } if (state & (wxTBSTATE_CHECKED | wxTBSTATE_INDETERMINATE)) { hbrOld = (HBRUSH) SelectObject((HDC) hdc, (HBRUSH) m_hbrDither); if (hbrOld) { if (!bMaskCreated) CreateMask((WXHDC) hdcGlyphs, xCenterOffset, yOffset, dxFace, dyFace); // CreateMask(hBitmap, xCenterOffset, yOffset, dxFace, dyFace); SetTextColor((HDC) hdc, 0L); // 0 -> 0 SetBkColor((HDC) hdc, 0x00FFFFFF); // 1 -> 1 // only draw the dither brush where the mask is 1's BitBlt((HDC) hdc, x, y, dxFace, dyFace, (HDC) m_hdcMono, 0, 0, 0x00E20746); SelectObject((HDC) hdc, hbrOld); } } SelectObject(hdcGlyphs, bitmapOld); DeleteDC(hdcGlyphs); } // ---------------------------------------------------------------------------- // drawing helpers // ---------------------------------------------------------------------------- void wxToolBar::GetSysColors() { static COLORREF rgbSaveFace = 0xffffffffL, rgbSaveShadow = 0xffffffffL, rgbSaveHilight = 0xffffffffL, rgbSaveFrame = 0xffffffffL; // For now, override these because the colour replacement isn't working, // and we get inconsistent colours. Assume all buttons are grey for the moment. // m_rgbFace = GetSysColor(COLOR_BTNFACE); m_rgbFace = RGB(192,192,192); // m_rgbShadow = GetSysColor(COLOR_BTNSHADOW); m_rgbShadow = RGB(128,128,128); // m_rgbHilight = GetSysColor(COLOR_BTNHIGHLIGHT); m_rgbHilight = RGB(255, 255, 255); m_rgbFrame = GetSysColor(COLOR_WINDOWFRAME); if (rgbSaveFace!=m_rgbFace || rgbSaveShadow!=m_rgbShadow || rgbSaveHilight!=m_rgbHilight || rgbSaveFrame!=m_rgbFrame) { rgbSaveFace = m_rgbFace; rgbSaveShadow = m_rgbShadow; rgbSaveHilight = m_rgbHilight; rgbSaveFrame = m_rgbFrame; // Update the brush for pushed-in buttons CreateDitherBrush(); } } WXHBITMAP wxToolBar::CreateDitherBitmap() { BITMAPINFO* pbmi; HBITMAP hbm; HDC hdc; int i; long patGray[8]; DWORD rgb; pbmi = (BITMAPINFO *)malloc(sizeof(BITMAPINFOHEADER) + 16*sizeof(RGBQUAD)); memset(pbmi, 0, (sizeof(BITMAPINFOHEADER) + 16*sizeof(RGBQUAD))); pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); pbmi->bmiHeader.biWidth = 8; pbmi->bmiHeader.biHeight = 8; pbmi->bmiHeader.biPlanes = 1; pbmi->bmiHeader.biBitCount = 1; pbmi->bmiHeader.biCompression = BI_RGB; // rgb = GetSysColor(COLOR_BTNFACE); rgb = RGB(192,192,192); pbmi->bmiColors[0].rgbBlue = GetBValue(rgb); pbmi->bmiColors[0].rgbGreen = GetGValue(rgb); pbmi->bmiColors[0].rgbRed = GetRValue(rgb); pbmi->bmiColors[0].rgbReserved = 0; // rgb = GetSysColor(COLOR_BTNHIGHLIGHT); rgb = RGB(255, 255, 255); pbmi->bmiColors[1].rgbBlue = GetBValue(rgb); pbmi->bmiColors[1].rgbGreen = GetGValue(rgb); pbmi->bmiColors[1].rgbRed = GetRValue(rgb); pbmi->bmiColors[1].rgbReserved = 0; /* initialize the brushes */ for (i = 0; i < 8; i++) if (i & 1) patGray[i] = 0xAAAA5555L; // 0x11114444L; // lighter gray else patGray[i] = 0x5555AAAAL; // 0x11114444L; // lighter gray hdc = ::GetDC(NULL); hbm = CreateDIBitmap(hdc, &pbmi->bmiHeader, CBM_INIT, patGray, pbmi, DIB_RGB_COLORS); ReleaseDC(NULL, hdc); free(pbmi); return (WXHBITMAP)hbm; } bool wxToolBar::CreateDitherBrush() { HBITMAP hbmGray; HBRUSH hbrSave; if (m_hbrDither) return TRUE; hbmGray = (HBITMAP) CreateDitherBitmap(); if (hbmGray) { hbrSave = (HBRUSH) m_hbrDither; m_hbrDither = (WXHBRUSH) CreatePatternBrush(hbmGray); DeleteObject(hbmGray); if (m_hbrDither) { if (hbrSave) { DeleteObject(hbrSave); } return TRUE; } else { m_hbrDither = (WXHBRUSH) hbrSave; } } return FALSE; } bool wxToolBar::FreeDitherBrush(void) { if (m_hbrDither) DeleteObject((HBRUSH) m_hbrDither); m_hbrDither = 0; return TRUE; } typedef struct tagCOLORMAP2 { COLORREF bgrfrom; COLORREF bgrto; COLORREF sysColor; } COLORMAP2; // these are the default colors used to map the dib colors // to the current system colors #define BGR_BUTTONTEXT (RGB(000,000,000)) // black #define BGR_BUTTONSHADOW (RGB(128,128,128)) // dark grey #define BGR_BUTTONFACE (RGB(192,192,192)) // bright grey #define BGR_BUTTONHILIGHT (RGB(255,255,255)) // white #define BGR_BACKGROUNDSEL (RGB(255,000,000)) // blue #define BGR_BACKGROUND (RGB(255,000,255)) // magenta #define FlipColor(rgb) (RGB(GetBValue(rgb), GetGValue(rgb), GetRValue(rgb))) WXHBITMAP wxToolBar::CreateMappedBitmap(WXHINSTANCE WXUNUSED(hInstance), void *info) { LPBITMAPINFOHEADER lpBitmapInfo = (LPBITMAPINFOHEADER)info; HDC hdc, hdcMem = NULL; DWORD FAR *p; LPSTR lpBits; HBITMAP hbm = NULL, hbmOld; int numcolors, i; int wid, hgt; static COLORMAP2 ColorMap[] = { {BGR_BUTTONTEXT, BGR_BUTTONTEXT, COLOR_BTNTEXT}, // black {BGR_BUTTONSHADOW, BGR_BUTTONSHADOW, COLOR_BTNSHADOW}, // dark grey {BGR_BUTTONFACE, BGR_BUTTONFACE, COLOR_BTNFACE}, // bright grey {BGR_BUTTONHILIGHT, BGR_BUTTONHILIGHT, COLOR_BTNHIGHLIGHT},// white {BGR_BACKGROUNDSEL, BGR_BACKGROUNDSEL, COLOR_HIGHLIGHT}, // blue {BGR_BACKGROUND, BGR_BACKGROUND, COLOR_WINDOW} // magenta }; #define NUM_MAPS (sizeof(ColorMap)/sizeof(COLORMAP2)) if (!lpBitmapInfo) return 0; // // So what are the new colors anyway ? // for (i=0; i < (int) NUM_MAPS; i++) { ColorMap[i].bgrto = (long unsigned int) FlipColor(GetSysColor((int)ColorMap[i].sysColor)); } p = (DWORD FAR *)(((LPSTR)lpBitmapInfo) + lpBitmapInfo->biSize); /* Replace button-face and button-shadow colors with the current values */ numcolors = 16; while (numcolors-- > 0) { for (i = 0; i < (int) NUM_MAPS; i++) { if (*p == ColorMap[i].bgrfrom) { *p = ColorMap[i].bgrto; break; } } p++; } /* First skip over the header structure */ lpBits = (LPSTR)(lpBitmapInfo + 1); /* Skip the color table entries, if any */ lpBits += (1 << (lpBitmapInfo->biBitCount)) * sizeof(RGBQUAD); /* Create a color bitmap compatible with the display device */ i = wid = (int)lpBitmapInfo->biWidth; hgt = (int)lpBitmapInfo->biHeight; hdc = ::GetDC(NULL); hdcMem = CreateCompatibleDC(hdc); if (hdcMem) { // hbm = CreateDiscardableBitmap(hdc, i, hgt); hbm = CreateCompatibleBitmap(hdc, i, hgt); if (hbm) { hbmOld = (HBITMAP) SelectObject(hdcMem, hbm); // set the main image StretchDIBits(hdcMem, 0, 0, wid, hgt, 0, 0, wid, hgt, lpBits, (LPBITMAPINFO)lpBitmapInfo, DIB_RGB_COLORS, SRCCOPY); SelectObject(hdcMem, hbmOld); } DeleteObject(hdcMem); } ReleaseDC(NULL, hdc); return (WXHBITMAP) hbm; } WXHBITMAP wxToolBar::CreateMappedBitmap(WXHINSTANCE hInstance, WXHBITMAP hBitmap) { HANDLE hDIB = wxBitmapToDIB((HBITMAP) hBitmap, 0); if (hDIB) { #ifdef __WINDOWS_386__ LPBITMAPINFOHEADER lpbmInfoHdr = (LPBITMAPINFOHEADER)MK_FP32(GlobalLock(hDIB)); #else LPBITMAPINFOHEADER lpbmInfoHdr = (LPBITMAPINFOHEADER)GlobalLock(hDIB); #endif HBITMAP newBitmap = (HBITMAP) CreateMappedBitmap((WXHINSTANCE) wxGetInstance(), lpbmInfoHdr); GlobalUnlock(hDIB); GlobalFree(hDIB); return (WXHBITMAP) newBitmap; } return 0; } #endif
nakedible/vpnease-l2tp
openswan/openswan-2.4.0rc4.quilt/linux/include/openswan/ipsec_errs.h
<filename>openswan/openswan-2.4.0rc4.quilt/linux/include/openswan/ipsec_errs.h /* * @(#) definition of ipsec_errs structure * * Copyright (C) 2001 <NAME> <<EMAIL>> * and <NAME> <<EMAIL>> * * 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. See <http://www.fsf.org/copyleft/gpl.txt>. * * 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. * * RCSID $Id: ipsec_errs.h,v 1.4 2004/04/05 19:55:05 mcr Exp $ * */ /* * This file describes the errors/statistics that FreeSWAN collects. * */ struct ipsec_errs { __u32 ips_alg_errs; /* number of algorithm errors */ __u32 ips_auth_errs; /* # of authentication errors */ __u32 ips_encsize_errs; /* # of encryption size errors*/ __u32 ips_encpad_errs; /* # of encryption pad errors*/ __u32 ips_replaywin_errs; /* # of pkt sequence errors */ }; /* * $Log: ipsec_errs.h,v $ * Revision 1.4 2004/04/05 19:55:05 mcr * Moved from linux/include/freeswan/ipsec_errs.h,v * * Revision 1.3 2002/04/24 07:36:46 mcr * Moved from ./klips/net/ipsec/ipsec_errs.h,v * * Revision 1.2 2001/11/26 09:16:13 rgb * Merge MCR's ipsec_sa, eroute, proc and struct lifetime changes. * * Revision 1.1.2.1 2001/09/25 02:25:57 mcr * lifetime structure created and common functions created. * * * Local variables: * c-file-style: "linux" * End: * */
krattai/AEBL
blades/icecast2/win32/resource.h
<filename>blades/icecast2/win32/resource.h //{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by Icecast2win.rc // #define IDM_ABOUTBOX 0x0010 #define IDD_ABOUTBOX 100 #define IDS_ABOUTBOX 101 #define IDD_ICECAST2WIN_DIALOG 102 #define IDR_MAINFRAME 128 #define IDR_MENU1 132 #define IDB_BITMAP1 134 #define IDB_BITMAP2 135 #define IDI_R 141 #define IDI_G 142 #define IDI_ICON1 142 #define IDD_SERVERSTATUS 144 #define IDD_SSTATUS 145 #define IDD_CONFIGDIALOG 146 #define IDD_STATSDIALOG 147 #define IDB_BITMAP3 149 #define IDB_BITMAP4 150 #define IDB_BITMAP5 151 #define IDB_BITMAP6 152 #define IDR_MENU2 153 #define IDR_MENU3 154 #define IDC_CURSOR1 155 #define IDC_CURSOR2 156 #define IDB_BITMAP7 159 #define IDR_TRAY 160 #define IDR_MENU4 161 #define IDB_BITMAP8 163 #define IDB_BITMAP9 164 #define IDC_MAINTAB 1000 #define IDC_ERROR_EDIT 1003 #define IDC_ACCESS_EDIT 1004 #define IDC_CONFIG_EDIT 1006 #define IDC_SERVERSTATUS 1008 #define IDC_SOURCES_CONNECTED 1009 #define IDC_NUMBER_CLIENTS 1010 #define IDC_GROUP1 1011 #define IDC_STATS_EDIT 1012 #define IDC_CONFIG 1020 #define IDC_STATSLIST 1021 #define IDC_SOURCELIST 1022 #define IDC_START 1023 #define IDC_AUTOSTART 1024 #define IDC_FILLER1 1025 #define IDC_FILLER2 1026 #define IDC_STATIC_SS 1029 #define IDC_GLOBALSTAT_LIST 1030 #define IDC_STATIC_GS 1031 #define IDC_STATIC_SLS 1032 #define IDC_RUNNINGFOR 1033 #define IDC_STATIC_RUN 1034 #define IDC_STATICBLACK 1035 #define IDC_HIDESYSTRAY 1036 #define ID_FILE_STARTSERVER 32771 #define ID_FILE_EXIT 32772 #define ID_FILE_STOPSERVER 32774 #define ID_FILE 32775 #define ID_POPUP_ADDTOGLOBALSTATLIST 32776 #define ID__DELETEFROMGLOBALSTATS 32777 #define ID__MAKETHISSTATTHEWINDOWTITLE 32779 #define ID_BLANK_RESTORE 32780 #define ID_ABOUT_HELP 32781 #define ID_FILE_EDITCONFIGURATION 32782 #define ID_ABOUT_CREDITS 32784 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 165 #define _APS_NEXT_COMMAND_VALUE 32785 #define _APS_NEXT_CONTROL_VALUE 1037 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
yuan50697105/my-admin-test
admin-demo-spring-boot-gradle/shower-commons-db-mybatis-mapper-with-sqlhelper/src/main/java/com/example/commons/db/mybatis/mapper/base/sqlhelper/module/mapper/GoodsInfoMapper.java
<reponame>yuan50697105/my-admin-test package com.example.commons.db.mybatis.mapper.base.sqlhelper.module.mapper; import com.example.commons.db.mybatis.mapper.base.sqlhelper.module.pojo.GoodsInfo; import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @Mapper public interface GoodsInfoMapper extends tk.mybatis.mapper.common.Mapper<GoodsInfo> { int updateBatch(List<GoodsInfo> list); int updateBatchSelective(List<GoodsInfo> list); int batchInsert(@Param("list") List<GoodsInfo> list); }
AlbandeCrevoisier/ldd-athens
linux-socfpga/drivers/gpu/drm/nouveau/nvkm/engine/disp/nv50.h
<filename>linux-socfpga/drivers/gpu/drm/nouveau/nvkm/engine/disp/nv50.h #ifndef __NV50_DISP_H__ #define __NV50_DISP_H__ #define nv50_disp(p) container_of((p), struct nv50_disp, base) #include "priv.h" struct nvkm_output; struct nvkm_output_dp; #define NV50_DISP_MTHD_ struct nvkm_object *object, \ struct nv50_disp *disp, void *data, u32 size #define NV50_DISP_MTHD_V0 NV50_DISP_MTHD_, int head #define NV50_DISP_MTHD_V1 NV50_DISP_MTHD_, int head, struct nvkm_output *outp struct nv50_disp { const struct nv50_disp_func *func; struct nvkm_disp base; struct work_struct supervisor; u32 super; struct nvkm_event uevent; struct { u32 lvdsconf; } sor; struct { u8 type[3]; } pior; struct nv50_disp_chan *chan[17]; }; int nv50_disp_root_scanoutpos(NV50_DISP_MTHD_V0); int gf119_disp_root_scanoutpos(NV50_DISP_MTHD_V0); int nv50_dac_power(NV50_DISP_MTHD_V1); int nv50_dac_sense(NV50_DISP_MTHD_V1); int gt215_hda_eld(NV50_DISP_MTHD_V1); int gf119_hda_eld(NV50_DISP_MTHD_V1); int g84_hdmi_ctrl(NV50_DISP_MTHD_V1); int gt215_hdmi_ctrl(NV50_DISP_MTHD_V1); int gf119_hdmi_ctrl(NV50_DISP_MTHD_V1); int gk104_hdmi_ctrl(NV50_DISP_MTHD_V1); int nv50_sor_power(NV50_DISP_MTHD_V1); int nv50_pior_power(NV50_DISP_MTHD_V1); int nv50_disp_new_(const struct nv50_disp_func *, struct nvkm_device *, int index, int heads, struct nvkm_disp **); int gf119_disp_new_(const struct nv50_disp_func *, struct nvkm_device *, int index, struct nvkm_disp **); struct nv50_disp_func_outp { int (* crt)(struct nvkm_disp *, int index, struct dcb_output *, struct nvkm_output **); int (* tv)(struct nvkm_disp *, int index, struct dcb_output *, struct nvkm_output **); int (*tmds)(struct nvkm_disp *, int index, struct dcb_output *, struct nvkm_output **); int (*lvds)(struct nvkm_disp *, int index, struct dcb_output *, struct nvkm_output **); int (* dp)(struct nvkm_disp *, int index, struct dcb_output *, struct nvkm_output **); }; struct nv50_disp_func { void (*intr)(struct nv50_disp *); const struct nvkm_event_func *uevent; void (*super)(struct work_struct *); const struct nvkm_disp_oclass *root; struct { void (*vblank_init)(struct nv50_disp *, int head); void (*vblank_fini)(struct nv50_disp *, int head); int (*scanoutpos)(NV50_DISP_MTHD_V0); } head; struct { const struct nv50_disp_func_outp internal; const struct nv50_disp_func_outp external; } outp; struct { int nr; int (*power)(NV50_DISP_MTHD_V1); int (*sense)(NV50_DISP_MTHD_V1); } dac; struct { int nr; int (*power)(NV50_DISP_MTHD_V1); int (*hda_eld)(NV50_DISP_MTHD_V1); int (*hdmi)(NV50_DISP_MTHD_V1); void (*magic)(struct nvkm_output *); } sor; struct { int nr; int (*power)(NV50_DISP_MTHD_V1); } pior; }; void nv50_disp_vblank_init(struct nv50_disp *, int); void nv50_disp_vblank_fini(struct nv50_disp *, int); void nv50_disp_intr(struct nv50_disp *); void nv50_disp_intr_supervisor(struct work_struct *); void gf119_disp_vblank_init(struct nv50_disp *, int); void gf119_disp_vblank_fini(struct nv50_disp *, int); void gf119_disp_intr(struct nv50_disp *); void gf119_disp_intr_supervisor(struct work_struct *); #endif
hu1991die/spring-boot-learing
Chapter09/src/main/java/com/feizi/RedisObjectSerializer.java
<filename>Chapter09/src/main/java/com/feizi/RedisObjectSerializer.java /* * Copyright (c) 2014 <EMAIL>. All Rights Reserved. */ package com.feizi; import org.springframework.core.convert.converter.Converter; import org.springframework.core.serializer.support.DeserializingConverter; import org.springframework.core.serializer.support.SerializingConverter; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.SerializationException; /** * @Desc 实现对象的序列化接口,对传入的对象进行序列化和反序列化 * @Author feizi * @Date 2016/10/20 14:00 * @Package_name com.feizi.domain */ public class RedisObjectSerializer implements RedisSerializer<Object> { //序列化对象 private Converter<Object, byte[]> serializer = new SerializingConverter(); //反序列化对象 private Converter<byte[], Object> deserializer = new DeserializingConverter(); static final byte[] EMPTY_ARRAY = new byte[0]; /** * @Desc 序列化操作 * @Author feizi * @Date 2016/10/20 14:06 * @param * @return */ @Override public byte[] serialize(Object obj) throws SerializationException { if(null == obj){ return EMPTY_ARRAY; } try { return serializer.convert(obj); } catch (Exception e) { return EMPTY_ARRAY; } } /** * @Desc 反序列化操作 * @Author feizi * @Date 2016/10/20 14:06 * @param * @return */ @Override public Object deserialize(byte[] bytes) throws SerializationException { if(isEmpty(bytes)){ return null; } try { return deserializer.convert(bytes); } catch (Exception e) { throw new SerializationException("Can not deserializer.", e); } } /** * @Desc 判空方法 * @Author feizi * @Date 2016/10/20 14:11 * @param * @return */ private boolean isEmpty(byte[] data){ return (null == data || data.length == 0); } }
CEPoole/awrs
test/controllers/SubscriptionControllerTest.scala
/* * Copyright 2021 HM Revenue & Customs * * 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 controllers import audit.TestAudit import metrics.AwrsMetrics import models._ import org.mockito.ArgumentMatchers.any import org.mockito.Mockito._ import org.scalatest.Matchers.convertToAnyShouldWrapper import org.scalatest.{MustMatchers, WordSpecLike} import play.api.libs.json.{JsValue, Json} import play.api.mvc.ControllerComponents import play.api.test.Helpers._ import play.api.test.{FakeHeaders, FakeRequest} import services.{EtmpLookupService, EtmpRegimeService, EtmpStatusService, SubscriptionService} import uk.gov.hmrc.http.HttpResponse import uk.gov.hmrc.play.audit.http.connector.AuditConnector import uk.gov.hmrc.play.audit.model.Audit import uk.gov.hmrc.play.bootstrap.config.ServicesConfig import utils.AwrsTestJson.testRefNo import utils.BaseSpec import scala.concurrent.Future class SubscriptionControllerTest extends BaseSpec with MustMatchers with WordSpecLike { val mockSubcriptionService: SubscriptionService = mock[SubscriptionService] val mockEtmpLookupService: EtmpLookupService = mock[EtmpLookupService] val mockEtmpStatusService: EtmpStatusService = mock[EtmpStatusService] val mockAuditConnector: AuditConnector = mock[AuditConnector] val mockEtmpRegimeService: EtmpRegimeService = mock[EtmpRegimeService] val awrsMetrics: AwrsMetrics = app.injector.instanceOf[AwrsMetrics] val cc: ControllerComponents = app.injector.instanceOf[ControllerComponents] val servicesConfig: ServicesConfig = app.injector.instanceOf[ServicesConfig] val utr = "testUtr" val lookupSuccess: JsValue = Json.parse( """{"reason": "All ok"}""") val lookupFailure: JsValue = Json.parse( """{"reason": "Resource not found"}""") val statusFailure: JsValue = Json.parse( """{"reason": "Resource not found"}""") val badRequestJson: JsValue = Json.parse("""{"Reason" : "Bad Request"}""") val serviceUnavailable: JsValue = Json.parse("""{"Reason" : "Service unavailable"}""") val serverError: JsValue = Json.parse("""{"Reason" : "Internal server error"}""") object TestSubscriptionController extends SubscriptionController( mockAuditConnector, awrsMetrics, mockSubcriptionService, mockEtmpLookupService, mockEtmpStatusService, mockEtmpRegimeService, cc, "awrs" ) { override val appName: String = "awrs" override val audit: Audit = new TestAudit(mockAuditConnector) override val metrics: AwrsMetrics = awrsMetrics override val regimeService: EtmpRegimeService = mockEtmpRegimeService override val auditConnector: AuditConnector = mockAuditConnector } "SubscriptionController" must { "subscribe" must { val successResponse = Json.parse( s"""{"processingDate":"2015-12-17T09:30:47Z","etmpFormBundleNumber":"123456789012345","awrsRegistrationNumber": "$testRefNo"}""") val registerSuccessResponse = HttpResponse(OK, successResponse, Map.empty[String, Seq[String]]) val matchFailure = Json.parse( """{"Reason": "Resource not found"}""") val matchFailureResponse = HttpResponse(NOT_FOUND, matchFailure, Map.empty[String, Seq[String]]) "respond with OK" in { when(mockSubcriptionService.subscribe(any(), any(), any(), any(), any())(any())).thenReturn(Future.successful(registerSuccessResponse)) val result = TestSubscriptionController.subscribe().apply(FakeRequest().withJsonBody(api4FrontendLTDJson)) contentType(result).get shouldBe "text/plain" status(result) shouldBe OK } "return Businessdetails for successful register" in { when(mockSubcriptionService.subscribe(any(), any(), any(), any(), any())(any())).thenReturn(Future.successful(registerSuccessResponse)) val result = TestSubscriptionController.subscribe().apply(FakeRequest().withJsonBody(api4FrontendLTDJson)) contentAsJson(result) shouldBe successResponse } "for an unsuccessful match return Not found" in { when(mockSubcriptionService.subscribe(any(), any(), any(), any(), any())(any())).thenReturn(Future.successful(matchFailureResponse)) val result = TestSubscriptionController.subscribe().apply(FakeRequest().withJsonBody(api4FrontendLTDJson)) status(result) shouldBe NOT_FOUND contentAsJson(result) shouldBe matchFailureResponse.json } "for a bad request, return BadRequest" in { when(mockSubcriptionService.subscribe(any(), any(), any(), any(), any())(any())).thenReturn(Future.successful(HttpResponse(BAD_REQUEST, badRequestJson, Map.empty[String, Seq[String]]))) when(mockEtmpRegimeService.checkETMPApi(any(), any())(any(), any())).thenReturn(Future.successful(None)) val result = TestSubscriptionController.subscribe()(FakeRequest().withJsonBody(api4FrontendLTDJson)) status(result) shouldBe BAD_REQUEST contentAsJson(result) shouldBe badRequestJson } "for a bad request, return ACCEPTED when checkETMPApi returns etmpRegistrationDetails" in { val etmpRegistrationDetails = EtmpRegistrationDetails( Some("ACME Trading"), "1", "XE0001234567890", Some(false),"XAAW00000123456", Some("AARN1234567"), None, None) when(mockSubcriptionService.subscribe(any(), any(), any(), any(), any())(any())) .thenReturn(Future.successful(HttpResponse(BAD_REQUEST, badRequestJson, Map.empty[String, Seq[String]]))) when(mockEtmpRegimeService.checkETMPApi( any(), any())(any(), any())) .thenReturn(Future.successful(Some(etmpRegistrationDetails))) val result = TestSubscriptionController.subscribe()(FakeRequest().withJsonBody(api4FrontendLTDJson)) status(result) shouldBe ACCEPTED } "for service unavailable, return service unavailable" in { when(mockSubcriptionService.subscribe(any(), any(), any(), any(), any())(any())).thenReturn(Future.successful(HttpResponse(SERVICE_UNAVAILABLE, serviceUnavailable, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.subscribe().apply(FakeRequest().withJsonBody(api4FrontendLTDJson)) status(result) shouldBe SERVICE_UNAVAILABLE contentAsJson(result) shouldBe serviceUnavailable } "internal server error, return internal server error" in { when(mockSubcriptionService.subscribe(any(), any(), any(), any(), any())(any())).thenReturn(Future.successful(HttpResponse(INTERNAL_SERVER_ERROR, serverError, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.subscribe().apply(FakeRequest().withJsonBody(api4FrontendLTDJson)) status(result) shouldBe INTERNAL_SERVER_ERROR contentAsJson(result) shouldBe serverError } } "Subscription Controller " must { "lookup submitted application from HODS when passed a valid awrs reference" in { when(mockEtmpLookupService.lookupApplication(any())(any())).thenReturn(Future.successful(HttpResponse(OK, api4EtmpLTDJson, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.lookupApplication(testRefNo).apply(FakeRequest()) status(result) shouldBe OK } "return BAD REQUEST error from HODS when passed an invalid awrs reference" in { when(mockEtmpLookupService.lookupApplication(any())(any())).thenReturn(Future.successful(HttpResponse(BAD_REQUEST, lookupFailure, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.lookupApplication("AAW00000123456").apply(FakeRequest()) status(result) shouldBe BAD_REQUEST } "return NOT FOUND error from HODS when passed an invalid awrs reference" in { when(mockEtmpLookupService.lookupApplication(any())(any())).thenReturn(Future.successful(HttpResponse(NOT_FOUND, lookupFailure, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.lookupApplication("AAW00000123456").apply(FakeRequest()) status(result) shouldBe NOT_FOUND } "return SERVICE UNAVAILABLE error from HODS when passed an invalid awrs reference" in { when(mockEtmpLookupService.lookupApplication(any())(any())).thenReturn(Future.successful(HttpResponse(SERVICE_UNAVAILABLE, lookupFailure, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.lookupApplication("AAW00000123456").apply(FakeRequest()) status(result) shouldBe SERVICE_UNAVAILABLE } "return INTERNAL SERVER ERROR error from HODS when passed an invalid awrs reference" in { when(mockEtmpLookupService.lookupApplication(any())(any())).thenReturn(Future.successful(HttpResponse(INTERNAL_SERVER_ERROR, lookupFailure, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.lookupApplication("AAW00000123456").apply(FakeRequest()) status(result) shouldBe INTERNAL_SERVER_ERROR } } "For API6, Subscription Controller " must { val updateSuccessResponse = Json.parse( """{"processingDate":"2015-12-17T09:30:47Z","etmpFormBundleNumber":"123456789012345"}""") "respond with OK" in { when(mockSubcriptionService.updateSubscription(any(), any())(any())).thenReturn(Future.successful(HttpResponse(OK, updateSuccessResponse, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.updateSubscription("").apply(FakeRequest().withJsonBody(api6FrontendLTDJson)) status(result) shouldBe OK contentAsJson(result) shouldBe updateSuccessResponse } "respond with BAD REQUEST" in { when(mockSubcriptionService.updateSubscription(any(), any())(any())).thenReturn(Future.successful(HttpResponse(BAD_REQUEST, badRequestJson, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.updateSubscription("").apply(FakeRequest().withJsonBody(api6FrontendLTDJson)) status(result) shouldBe BAD_REQUEST } "return NOT FOUND error from HODS when passed an invalid awrs reference" in { when(mockSubcriptionService.updateSubscription(any(), any())(any())).thenReturn(Future.successful(HttpResponse(NOT_FOUND, serviceUnavailable, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.updateSubscription("").apply(FakeRequest().withJsonBody(api6FrontendLTDJson)) status(result) shouldBe NOT_FOUND } "return SERVICE UNAVAILABLE error from HODS when passed an invalid awrs reference" in { when(mockSubcriptionService.updateSubscription(any(), any())(any())).thenReturn(Future.successful(HttpResponse(SERVICE_UNAVAILABLE, serviceUnavailable, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.updateSubscription("").apply(FakeRequest().withJsonBody(api6FrontendLTDJson)) status(result) shouldBe SERVICE_UNAVAILABLE } "return INTERNAL SERVER ERROR error from HODS when passed an invalid awrs reference" in { when(mockSubcriptionService.updateSubscription(any(), any())(any())).thenReturn(Future.successful(HttpResponse(INTERNAL_SERVER_ERROR, serverError, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.updateSubscription("").apply(FakeRequest().withJsonBody(api6FrontendLTDJson)) status(result) shouldBe INTERNAL_SERVER_ERROR } } "For API3, Subscription Controller " must { val updateSuccessResponse = Json.parse( """{"processingDate":"2015-12-17T09:30:47Z"}""") val fakeRequest = FakeRequest(method = "POST", uri = "", headers = FakeHeaders(Seq("Content-type" -> "application/json")), body = api3FrontendJson) "respond with OK" in { when(mockSubcriptionService.updateGrpRepRegistrationDetails(any(), any())(any())).thenReturn(Future.successful(HttpResponse(OK, updateSuccessResponse, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.updateGrpRegistrationDetails("", "").apply(fakeRequest) status(result) shouldBe OK contentAsJson(result) shouldBe updateSuccessResponse } "respond with BAD REQUEST" in { when(mockSubcriptionService.updateGrpRepRegistrationDetails(any(), any())(any())).thenReturn(Future.successful(HttpResponse(BAD_REQUEST, badRequestJson, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.updateGrpRegistrationDetails("", "").apply(fakeRequest) status(result) shouldBe BAD_REQUEST } "return NOT FOUND error from HODS when passed an invalid awrs reference" in { when(mockSubcriptionService.updateGrpRepRegistrationDetails(any(), any())(any())).thenReturn(Future.successful(HttpResponse(NOT_FOUND, serviceUnavailable, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.updateGrpRegistrationDetails("", "").apply(fakeRequest) status(result) shouldBe NOT_FOUND } "return SERVICE UNAVAILABLE error from HODS when passed an invalid awrs reference" in { when(mockSubcriptionService.updateGrpRepRegistrationDetails(any(), any())(any())).thenReturn(Future.successful(HttpResponse(SERVICE_UNAVAILABLE, serviceUnavailable, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.updateGrpRegistrationDetails("", "").apply(fakeRequest) status(result) shouldBe SERVICE_UNAVAILABLE } "return INTERNAL SERVER ERROR error from HODS when passed an invalid awrs reference" in { when(mockSubcriptionService.updateGrpRepRegistrationDetails(any(), any())(any())).thenReturn(Future.successful(HttpResponse(INTERNAL_SERVER_ERROR, serverError, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.updateGrpRegistrationDetails("", "").apply(fakeRequest) status(result) shouldBe INTERNAL_SERVER_ERROR } } "For API 9, Subscription Controller " must { "check submitted application status from HODS when passed a valid awrs reference" in { def checkStatus(json: JsValue, expected: FormBundleStatus): Unit = { when(mockEtmpStatusService.checkStatus(any())(any())).thenReturn(Future.successful(HttpResponse(OK, json, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.checkStatus(testRefNo).apply(FakeRequest()) status(result) shouldBe OK await(result) val r = contentAsString(result) val subscriptionStatusType = SubscriptionStatusType.reader.reads(Json.parse(r)) subscriptionStatusType.isSuccess shouldBe true subscriptionStatusType.get.formBundleStatus shouldBe expected } checkStatus(api9SuccessfulResponseJson, Pending) checkStatus(api9SuccessfulResponseUsingCodeJson, Pending) checkStatus(api9SuccessfulResponseWithMismatchCasesJson, Pending) checkStatus(api9SuccessfulDeRegResponseJson, DeRegistered) } "return BAD REQUEST error from HODS when passed an invalid awrs reference" in { when(mockEtmpStatusService.checkStatus(any())(any())).thenReturn(Future.successful(HttpResponse(BAD_REQUEST, statusFailure, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.checkStatus("AAW00000123456").apply(FakeRequest()) status(result) shouldBe BAD_REQUEST } "return NOT FOUND error from HODS when passed an invalid awrs reference" in { when(mockEtmpStatusService.checkStatus(any())(any())).thenReturn(Future.successful(HttpResponse(NOT_FOUND, statusFailure, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.checkStatus("AAW00000123456").apply(FakeRequest()) status(result) shouldBe NOT_FOUND } "return SERVICE UNAVAILABLE error from HODS when passed an invalid awrs reference" in { when(mockEtmpStatusService.checkStatus(any())(any())).thenReturn(Future.successful(HttpResponse(SERVICE_UNAVAILABLE, statusFailure, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.checkStatus("AAW00000123456").apply(FakeRequest()) status(result) shouldBe SERVICE_UNAVAILABLE } "return INTERNAL SERVER ERROR error from HODS when passed an invalid awrs reference" in { when(mockEtmpStatusService.checkStatus(any())(any())).thenReturn(Future.successful(HttpResponse(INTERNAL_SERVER_ERROR, statusFailure, Map.empty[String, Seq[String]]))) val result = TestSubscriptionController.checkStatus("AAW00000123456").apply(FakeRequest()) status(result) shouldBe INTERNAL_SERVER_ERROR } } } }
fortinet-solutions-cse/ansible_fgt_modules
v6.0.5/vpn_ssl_web/test_fortios_vpn_ssl_web_portal.py
# Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 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 Ansible. If not, see <https://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest from mock import ANY from ansible.module_utils.network.fortios.fortios import FortiOSHandler try: from ansible.modules.network.fortios import fortios_vpn_ssl_web_portal except ImportError: pytest.skip("Could not load required modules for testing", allow_module_level=True) @pytest.fixture(autouse=True) def connection_mock(mocker): connection_class_mock = mocker.patch('ansible.modules.network.fortios.fortios_vpn_ssl_web_portal.Connection') return connection_class_mock fos_instance = FortiOSHandler(connection_mock) def test_vpn_ssl_web_portal_creation(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'vpn_ssl_web_portal': { 'allow_user_access': 'web', 'auto_connect': 'enable', 'custom_lang': 'test_value_5', 'customize_forticlient_download_url': 'enable', 'display_bookmark': 'enable', 'display_connection_tools': 'enable', 'display_history': 'enable', 'display_status': 'enable', 'dns_server1': 'test_value_11', 'dns_server2': 'test_value_12', 'dns_suffix': 'test_value_13', 'exclusive_routing': 'enable', 'forticlient_download': 'enable', 'forticlient_download_method': 'direct', 'heading': 'test_value_17', 'hide_sso_credential': 'enable', 'host_check': 'none', 'host_check_interval': '20', 'ip_mode': 'range', 'ipv6_dns_server1': 'test_value_22', 'ipv6_dns_server2': 'test_value_23', 'ipv6_exclusive_routing': 'enable', 'ipv6_service_restriction': 'enable', 'ipv6_split_tunneling': 'enable', 'ipv6_tunnel_mode': 'enable', 'ipv6_wins_server1': 'test_value_28', 'ipv6_wins_server2': 'test_value_29', 'keep_alive': 'enable', 'limit_user_logins': 'enable', 'mac_addr_action': 'allow', 'mac_addr_check': 'enable', 'macos_forticlient_download_url': 'test_value_34', 'name': 'default_name_35', 'os_check': 'enable', 'redir_url': 'test_value_37', 'save_password': '<PASSWORD>', 'service_restriction': 'enable', 'skip_check_for_unsupported_browser': 'enable', 'skip_check_for_unsupported_os': 'enable', 'smb_ntlmv1_auth': 'enable', 'smbv1': 'enable', 'split_tunneling': 'enable', 'theme': 'blue', 'tunnel_mode': 'enable', 'user_bookmark': 'enable', 'user_group_bookmark': 'enable', 'web_mode': 'enable', 'windows_forticlient_download_url': 'test_value_50', 'wins_server1': 'test_value_51', 'wins_server2': 'test_value_52' }, 'vdom': 'root'} is_error, changed, response = fortios_vpn_ssl_web_portal.fortios_vpn_ssl_web(input_data, fos_instance) expected_data = { 'allow-user-access': 'web', 'auto-connect': 'enable', 'custom-lang': 'test_value_5', 'customize-forticlient-download-url': 'enable', 'display-bookmark': 'enable', 'display-connection-tools': 'enable', 'display-history': 'enable', 'display-status': 'enable', 'dns-server1': 'test_value_11', 'dns-server2': 'test_value_12', 'dns-suffix': 'test_value_13', 'exclusive-routing': 'enable', 'forticlient-download': 'enable', 'forticlient-download-method': 'direct', 'heading': 'test_value_17', 'hide-sso-credential': 'enable', 'host-check': 'none', 'host-check-interval': '20', 'ip-mode': 'range', 'ipv6-dns-server1': 'test_value_22', 'ipv6-dns-server2': 'test_value_23', 'ipv6-exclusive-routing': 'enable', 'ipv6-service-restriction': 'enable', 'ipv6-split-tunneling': 'enable', 'ipv6-tunnel-mode': 'enable', 'ipv6-wins-server1': 'test_value_28', 'ipv6-wins-server2': 'test_value_29', 'keep-alive': 'enable', 'limit-user-logins': 'enable', 'mac-addr-action': 'allow', 'mac-addr-check': 'enable', 'macos-forticlient-download-url': 'test_value_34', 'name': 'default_name_35', 'os-check': 'enable', 'redir-url': 'test_value_37', 'save-password': '<PASSWORD>', 'service-restriction': 'enable', 'skip-check-for-unsupported-browser': 'enable', 'skip-check-for-unsupported-os': 'enable', 'smb-ntlmv1-auth': 'enable', 'smbv1': 'enable', 'split-tunneling': 'enable', 'theme': 'blue', 'tunnel-mode': 'enable', 'user-bookmark': 'enable', 'user-group-bookmark': 'enable', 'web-mode': 'enable', 'windows-forticlient-download-url': 'test_value_50', 'wins-server1': 'test_value_51', 'wins-server2': 'test_value_52' } set_method_mock.assert_called_with('vpn.ssl.web', 'portal', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200 def test_vpn_ssl_web_portal_creation_fails(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'error', 'http_method': 'POST', 'http_status': 500} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'vpn_ssl_web_portal': { 'allow_user_access': 'web', 'auto_connect': 'enable', 'custom_lang': 'test_value_5', 'customize_forticlient_download_url': 'enable', 'display_bookmark': 'enable', 'display_connection_tools': 'enable', 'display_history': 'enable', 'display_status': 'enable', 'dns_server1': 'test_value_11', 'dns_server2': 'test_value_12', 'dns_suffix': 'test_value_13', 'exclusive_routing': 'enable', 'forticlient_download': 'enable', 'forticlient_download_method': 'direct', 'heading': 'test_value_17', 'hide_sso_credential': 'enable', 'host_check': 'none', 'host_check_interval': '20', 'ip_mode': 'range', 'ipv6_dns_server1': 'test_value_22', 'ipv6_dns_server2': 'test_value_23', 'ipv6_exclusive_routing': 'enable', 'ipv6_service_restriction': 'enable', 'ipv6_split_tunneling': 'enable', 'ipv6_tunnel_mode': 'enable', 'ipv6_wins_server1': 'test_value_28', 'ipv6_wins_server2': 'test_value_29', 'keep_alive': 'enable', 'limit_user_logins': 'enable', 'mac_addr_action': 'allow', 'mac_addr_check': 'enable', 'macos_forticlient_download_url': 'test_value_34', 'name': 'default_name_35', 'os_check': 'enable', 'redir_url': 'test_value_37', 'save_password': '<PASSWORD>', 'service_restriction': 'enable', 'skip_check_for_unsupported_browser': 'enable', 'skip_check_for_unsupported_os': 'enable', 'smb_ntlmv1_auth': 'enable', 'smbv1': 'enable', 'split_tunneling': 'enable', 'theme': 'blue', 'tunnel_mode': 'enable', 'user_bookmark': 'enable', 'user_group_bookmark': 'enable', 'web_mode': 'enable', 'windows_forticlient_download_url': 'test_value_50', 'wins_server1': 'test_value_51', 'wins_server2': 'test_value_52' }, 'vdom': 'root'} is_error, changed, response = fortios_vpn_ssl_web_portal.fortios_vpn_ssl_web(input_data, fos_instance) expected_data = { 'allow-user-access': 'web', 'auto-connect': 'enable', 'custom-lang': 'test_value_5', 'customize-forticlient-download-url': 'enable', 'display-bookmark': 'enable', 'display-connection-tools': 'enable', 'display-history': 'enable', 'display-status': 'enable', 'dns-server1': 'test_value_11', 'dns-server2': 'test_value_12', 'dns-suffix': 'test_value_13', 'exclusive-routing': 'enable', 'forticlient-download': 'enable', 'forticlient-download-method': 'direct', 'heading': 'test_value_17', 'hide-sso-credential': 'enable', 'host-check': 'none', 'host-check-interval': '20', 'ip-mode': 'range', 'ipv6-dns-server1': 'test_value_22', 'ipv6-dns-server2': 'test_value_23', 'ipv6-exclusive-routing': 'enable', 'ipv6-service-restriction': 'enable', 'ipv6-split-tunneling': 'enable', 'ipv6-tunnel-mode': 'enable', 'ipv6-wins-server1': 'test_value_28', 'ipv6-wins-server2': 'test_value_29', 'keep-alive': 'enable', 'limit-user-logins': 'enable', 'mac-addr-action': 'allow', 'mac-addr-check': 'enable', 'macos-forticlient-download-url': 'test_value_34', 'name': 'default_name_35', 'os-check': 'enable', 'redir-url': 'test_value_37', 'save-password': '<PASSWORD>', 'service-restriction': 'enable', 'skip-check-for-unsupported-browser': 'enable', 'skip-check-for-unsupported-os': 'enable', 'smb-ntlmv1-auth': 'enable', 'smbv1': 'enable', 'split-tunneling': 'enable', 'theme': 'blue', 'tunnel-mode': 'enable', 'user-bookmark': 'enable', 'user-group-bookmark': 'enable', 'web-mode': 'enable', 'windows-forticlient-download-url': 'test_value_50', 'wins-server1': 'test_value_51', 'wins-server2': 'test_value_52' } set_method_mock.assert_called_with('vpn.ssl.web', 'portal', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 500 def test_vpn_ssl_web_portal_removal(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') delete_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} delete_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.delete', return_value=delete_method_result) input_data = { 'username': 'admin', 'state': 'absent', 'vpn_ssl_web_portal': { 'allow_user_access': 'web', 'auto_connect': 'enable', 'custom_lang': 'test_value_5', 'customize_forticlient_download_url': 'enable', 'display_bookmark': 'enable', 'display_connection_tools': 'enable', 'display_history': 'enable', 'display_status': 'enable', 'dns_server1': 'test_value_11', 'dns_server2': 'test_value_12', 'dns_suffix': 'test_value_13', 'exclusive_routing': 'enable', 'forticlient_download': 'enable', 'forticlient_download_method': 'direct', 'heading': 'test_value_17', 'hide_sso_credential': 'enable', 'host_check': 'none', 'host_check_interval': '20', 'ip_mode': 'range', 'ipv6_dns_server1': 'test_value_22', 'ipv6_dns_server2': 'test_value_23', 'ipv6_exclusive_routing': 'enable', 'ipv6_service_restriction': 'enable', 'ipv6_split_tunneling': 'enable', 'ipv6_tunnel_mode': 'enable', 'ipv6_wins_server1': 'test_value_28', 'ipv6_wins_server2': 'test_value_29', 'keep_alive': 'enable', 'limit_user_logins': 'enable', 'mac_addr_action': 'allow', 'mac_addr_check': 'enable', 'macos_forticlient_download_url': 'test_value_34', 'name': 'default_name_35', 'os_check': 'enable', 'redir_url': 'test_value_37', 'save_password': '<PASSWORD>', 'service_restriction': 'enable', 'skip_check_for_unsupported_browser': 'enable', 'skip_check_for_unsupported_os': 'enable', 'smb_ntlmv1_auth': 'enable', 'smbv1': 'enable', 'split_tunneling': 'enable', 'theme': 'blue', 'tunnel_mode': 'enable', 'user_bookmark': 'enable', 'user_group_bookmark': 'enable', 'web_mode': 'enable', 'windows_forticlient_download_url': 'test_value_50', 'wins_server1': 'test_value_51', 'wins_server2': 'test_value_52' }, 'vdom': 'root'} is_error, changed, response = fortios_vpn_ssl_web_portal.fortios_vpn_ssl_web(input_data, fos_instance) delete_method_mock.assert_called_with('vpn.ssl.web', 'portal', mkey=ANY, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200 def test_vpn_ssl_web_portal_deletion_fails(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') delete_method_result = {'status': 'error', 'http_method': 'POST', 'http_status': 500} delete_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.delete', return_value=delete_method_result) input_data = { 'username': 'admin', 'state': 'absent', 'vpn_ssl_web_portal': { 'allow_user_access': 'web', 'auto_connect': 'enable', 'custom_lang': 'test_value_5', 'customize_forticlient_download_url': 'enable', 'display_bookmark': 'enable', 'display_connection_tools': 'enable', 'display_history': 'enable', 'display_status': 'enable', 'dns_server1': 'test_value_11', 'dns_server2': 'test_value_12', 'dns_suffix': 'test_value_13', 'exclusive_routing': 'enable', 'forticlient_download': 'enable', 'forticlient_download_method': 'direct', 'heading': 'test_value_17', 'hide_sso_credential': 'enable', 'host_check': 'none', 'host_check_interval': '20', 'ip_mode': 'range', 'ipv6_dns_server1': 'test_value_22', 'ipv6_dns_server2': 'test_value_23', 'ipv6_exclusive_routing': 'enable', 'ipv6_service_restriction': 'enable', 'ipv6_split_tunneling': 'enable', 'ipv6_tunnel_mode': 'enable', 'ipv6_wins_server1': 'test_value_28', 'ipv6_wins_server2': 'test_value_29', 'keep_alive': 'enable', 'limit_user_logins': 'enable', 'mac_addr_action': 'allow', 'mac_addr_check': 'enable', 'macos_forticlient_download_url': 'test_value_34', 'name': 'default_name_35', 'os_check': 'enable', 'redir_url': 'test_value_37', 'save_password': '<PASSWORD>', 'service_restriction': 'enable', 'skip_check_for_unsupported_browser': 'enable', 'skip_check_for_unsupported_os': 'enable', 'smb_ntlmv1_auth': 'enable', 'smbv1': 'enable', 'split_tunneling': 'enable', 'theme': 'blue', 'tunnel_mode': 'enable', 'user_bookmark': 'enable', 'user_group_bookmark': 'enable', 'web_mode': 'enable', 'windows_forticlient_download_url': 'test_value_50', 'wins_server1': 'test_value_51', 'wins_server2': 'test_value_52' }, 'vdom': 'root'} is_error, changed, response = fortios_vpn_ssl_web_portal.fortios_vpn_ssl_web(input_data, fos_instance) delete_method_mock.assert_called_with('vpn.ssl.web', 'portal', mkey=ANY, vdom='root') schema_method_mock.assert_not_called() assert is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 500 def test_vpn_ssl_web_portal_idempotent(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'error', 'http_method': 'DELETE', 'http_status': 404} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'vpn_ssl_web_portal': { 'allow_user_access': 'web', 'auto_connect': 'enable', 'custom_lang': 'test_value_5', 'customize_forticlient_download_url': 'enable', 'display_bookmark': 'enable', 'display_connection_tools': 'enable', 'display_history': 'enable', 'display_status': 'enable', 'dns_server1': 'test_value_11', 'dns_server2': 'test_value_12', 'dns_suffix': 'test_value_13', 'exclusive_routing': 'enable', 'forticlient_download': 'enable', 'forticlient_download_method': 'direct', 'heading': 'test_value_17', 'hide_sso_credential': 'enable', 'host_check': 'none', 'host_check_interval': '20', 'ip_mode': 'range', 'ipv6_dns_server1': 'test_value_22', 'ipv6_dns_server2': 'test_value_23', 'ipv6_exclusive_routing': 'enable', 'ipv6_service_restriction': 'enable', 'ipv6_split_tunneling': 'enable', 'ipv6_tunnel_mode': 'enable', 'ipv6_wins_server1': 'test_value_28', 'ipv6_wins_server2': 'test_value_29', 'keep_alive': 'enable', 'limit_user_logins': 'enable', 'mac_addr_action': 'allow', 'mac_addr_check': 'enable', 'macos_forticlient_download_url': 'test_value_34', 'name': 'default_name_35', 'os_check': 'enable', 'redir_url': 'test_value_37', 'save_password': '<PASSWORD>', 'service_restriction': 'enable', 'skip_check_for_unsupported_browser': 'enable', 'skip_check_for_unsupported_os': 'enable', 'smb_ntlmv1_auth': 'enable', 'smbv1': 'enable', 'split_tunneling': 'enable', 'theme': 'blue', 'tunnel_mode': 'enable', 'user_bookmark': 'enable', 'user_group_bookmark': 'enable', 'web_mode': 'enable', 'windows_forticlient_download_url': 'test_value_50', 'wins_server1': 'test_value_51', 'wins_server2': 'test_value_52' }, 'vdom': 'root'} is_error, changed, response = fortios_vpn_ssl_web_portal.fortios_vpn_ssl_web(input_data, fos_instance) expected_data = { 'allow-user-access': 'web', 'auto-connect': 'enable', 'custom-lang': 'test_value_5', 'customize-forticlient-download-url': 'enable', 'display-bookmark': 'enable', 'display-connection-tools': 'enable', 'display-history': 'enable', 'display-status': 'enable', 'dns-server1': 'test_value_11', 'dns-server2': 'test_value_12', 'dns-suffix': 'test_value_13', 'exclusive-routing': 'enable', 'forticlient-download': 'enable', 'forticlient-download-method': 'direct', 'heading': 'test_value_17', 'hide-sso-credential': 'enable', 'host-check': 'none', 'host-check-interval': '20', 'ip-mode': 'range', 'ipv6-dns-server1': 'test_value_22', 'ipv6-dns-server2': 'test_value_23', 'ipv6-exclusive-routing': 'enable', 'ipv6-service-restriction': 'enable', 'ipv6-split-tunneling': 'enable', 'ipv6-tunnel-mode': 'enable', 'ipv6-wins-server1': 'test_value_28', 'ipv6-wins-server2': 'test_value_29', 'keep-alive': 'enable', 'limit-user-logins': 'enable', 'mac-addr-action': 'allow', 'mac-addr-check': 'enable', 'macos-forticlient-download-url': 'test_value_34', 'name': 'default_name_35', 'os-check': 'enable', 'redir-url': 'test_value_37', 'save-password': '<PASSWORD>', 'service-restriction': 'enable', 'skip-check-for-unsupported-browser': 'enable', 'skip-check-for-unsupported-os': 'enable', 'smb-ntlmv1-auth': 'enable', 'smbv1': 'enable', 'split-tunneling': 'enable', 'theme': 'blue', 'tunnel-mode': 'enable', 'user-bookmark': 'enable', 'user-group-bookmark': 'enable', 'web-mode': 'enable', 'windows-forticlient-download-url': 'test_value_50', 'wins-server1': 'test_value_51', 'wins-server2': 'test_value_52' } set_method_mock.assert_called_with('vpn.ssl.web', 'portal', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 404 def test_vpn_ssl_web_portal_filter_foreign_attributes(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'vpn_ssl_web_portal': { 'random_attribute_not_valid': 'tag', 'allow_user_access': 'web', 'auto_connect': 'enable', 'custom_lang': 'test_value_5', 'customize_forticlient_download_url': 'enable', 'display_bookmark': 'enable', 'display_connection_tools': 'enable', 'display_history': 'enable', 'display_status': 'enable', 'dns_server1': 'test_value_11', 'dns_server2': 'test_value_12', 'dns_suffix': 'test_value_13', 'exclusive_routing': 'enable', 'forticlient_download': 'enable', 'forticlient_download_method': 'direct', 'heading': 'test_value_17', 'hide_sso_credential': 'enable', 'host_check': 'none', 'host_check_interval': '20', 'ip_mode': 'range', 'ipv6_dns_server1': 'test_value_22', 'ipv6_dns_server2': 'test_value_23', 'ipv6_exclusive_routing': 'enable', 'ipv6_service_restriction': 'enable', 'ipv6_split_tunneling': 'enable', 'ipv6_tunnel_mode': 'enable', 'ipv6_wins_server1': 'test_value_28', 'ipv6_wins_server2': 'test_value_29', 'keep_alive': 'enable', 'limit_user_logins': 'enable', 'mac_addr_action': 'allow', 'mac_addr_check': 'enable', 'macos_forticlient_download_url': 'test_value_34', 'name': 'default_name_35', 'os_check': 'enable', 'redir_url': 'test_value_37', 'save_password': '<PASSWORD>', 'service_restriction': 'enable', 'skip_check_for_unsupported_browser': 'enable', 'skip_check_for_unsupported_os': 'enable', 'smb_ntlmv1_auth': 'enable', 'smbv1': 'enable', 'split_tunneling': 'enable', 'theme': 'blue', 'tunnel_mode': 'enable', 'user_bookmark': 'enable', 'user_group_bookmark': 'enable', 'web_mode': 'enable', 'windows_forticlient_download_url': 'test_value_50', 'wins_server1': 'test_value_51', 'wins_server2': 'test_value_52' }, 'vdom': 'root'} is_error, changed, response = fortios_vpn_ssl_web_portal.fortios_vpn_ssl_web(input_data, fos_instance) expected_data = { 'allow-user-access': 'web', 'auto-connect': 'enable', 'custom-lang': 'test_value_5', 'customize-forticlient-download-url': 'enable', 'display-bookmark': 'enable', 'display-connection-tools': 'enable', 'display-history': 'enable', 'display-status': 'enable', 'dns-server1': 'test_value_11', 'dns-server2': 'test_value_12', 'dns-suffix': 'test_value_13', 'exclusive-routing': 'enable', 'forticlient-download': 'enable', 'forticlient-download-method': 'direct', 'heading': 'test_value_17', 'hide-sso-credential': 'enable', 'host-check': 'none', 'host-check-interval': '20', 'ip-mode': 'range', 'ipv6-dns-server1': 'test_value_22', 'ipv6-dns-server2': 'test_value_23', 'ipv6-exclusive-routing': 'enable', 'ipv6-service-restriction': 'enable', 'ipv6-split-tunneling': 'enable', 'ipv6-tunnel-mode': 'enable', 'ipv6-wins-server1': 'test_value_28', 'ipv6-wins-server2': 'test_value_29', 'keep-alive': 'enable', 'limit-user-logins': 'enable', 'mac-addr-action': 'allow', 'mac-addr-check': 'enable', 'macos-forticlient-download-url': 'test_value_34', 'name': 'default_name_35', 'os-check': 'enable', 'redir-url': 'test_value_37', 'save-password': '<PASSWORD>', 'service-restriction': 'enable', 'skip-check-for-unsupported-browser': 'enable', 'skip-check-for-unsupported-os': 'enable', 'smb-ntlmv1-auth': 'enable', 'smbv1': 'enable', 'split-tunneling': 'enable', 'theme': 'blue', 'tunnel-mode': 'enable', 'user-bookmark': 'enable', 'user-group-bookmark': 'enable', 'web-mode': 'enable', 'windows-forticlient-download-url': 'test_value_50', 'wins-server1': 'test_value_51', 'wins-server2': 'test_value_52' } set_method_mock.assert_called_with('vpn.ssl.web', 'portal', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200
takanori-ugai/smile
nlp/src/main/java/smile/nlp/relevance/BM25.java
<gh_stars>0 /* * Copyright (c) 2010-2021 <NAME>. All rights reserved. * * Smile 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. * * Smile 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 Smile. If not, see <https://www.gnu.org/licenses/>. */ package smile.nlp.relevance; import smile.nlp.Corpus; import smile.nlp.TextTerms; /** * The BM25 weighting scheme, often called Okapi weighting, after the system in * which it was first implemented, was developed as a way of building a * probabilistic model sensitive to term frequency and document length while * not introducing too many additional parameters into the model. It is not * a single function, but actually a whole family of scoring functions, with * slightly different components and parameters. * <p> * At the extreme values of the coefficient b, BM25 turns into ranking functions * known as BM11 (for b = 1) and BM15 (for b = 0). BM25F is a modification of * BM25 in which the document is considered to be composed from several fields * (such as headlines, main text, anchor text) with possibly different degrees * of importance. * <p> * BM25 and its newer variants represent state-of-the-art TF-IDF-like retrieval * functions used in document retrieval, such as web search. * * @see TFIDF * * @author <NAME> */ public class BM25 implements RelevanceRanker { /** * Free parameter, usually chosen as k1 = 2.0. */ private final double k1; /** * Free parameter, usually chosen as b = 0.75. */ private final double b; /** * The control parameter in BM25+. The standard BM25 in which the * component of term frequency normalization by document length * is not properly lower-bounded; as a result of this deficiency, * long documents which do match the query term can often be scored * unfairly by BM25 as having a similar relevance to shorter * documents that do not contain the query term at all. */ private final double delta; /** * Default constructor with k1 = 1.2, b = 0.75, delta = 1.0. */ public BM25() { this(1.2, 0.75, 1.0); } /** * Constructor. * * @param k1 is a positive tuning parameter that calibrates * the document term frequency scaling. A k1 value of 0 * corresponds to a binary model (no term frequency), * and a large value corresponds to using raw term frequency. * * @param b b is another tuning parameter ({@code 0 <= b <= 1}) which * determines the scaling by document length: b = 1 corresponds * to fully scaling the term weight by the document length, * while b = 0 corresponds to no length normalization. * * @param delta the control parameter in BM25+. The standard BM25 in * which the component of term frequency normalization * by document length is not properly lower-bounded; * as a result of this deficiency, long documents which * do match the query term can often be scored unfairly * by BM25 as having a similar relevance to shorter * documents that do not contain the query term at all. */ public BM25(double k1, double b, double delta) { if (k1 < 0) { throw new IllegalArgumentException("Negative k1 = " + k1); } if (b < 0 || b > 1) { throw new IllegalArgumentException("Invalid b = " + b); } if (delta < 0) { throw new IllegalArgumentException("Invalid delta = " + delta); } this.k1 = k1; this.b = b; this.delta = delta; } /** * Returns the relevance score between a term and a document based on a corpus. * @param termFreq the term frequency in the text body. * @param docSize the text length. * @param avgDocSize the average text length in the corpus. * @param titleTermFreq the term frequency in the title. * @param titleSize the title length. * @param avgTitleSize the average title length in the corpus. * @param anchorTermFreq the term frequency in the anchor. * @param anchorSize the anchor length. * @param avgAnchorSize the average anchor length in the corpus. * @param N the number of documents in the corpus. * @param n the number of documents containing the given term in the corpus; * @return the relevance score. */ public double score(int termFreq, int docSize, double avgDocSize, int titleTermFreq, int titleSize, double avgTitleSize, int anchorTermFreq, int anchorSize, double avgAnchorSize, long N, long n) { if (termFreq <= 0) return 0.0; // BM25F parameters final double kf = 4.9; // k1 in BM25F final double bTitle = 0.6; final double bBody = 0.5; final double bAnchor = 0.6; final double wTitle = 13.5; final double wBody = 1.0; final double wAnchor = 11.5; double tf = wBody * termFreq / (1.0 + bBody * (docSize / avgDocSize - 1.0)); if (titleTermFreq > 0) { tf += wTitle * titleTermFreq / (1.0 + bTitle * (titleSize / avgTitleSize - 1.0)); } if (anchorTermFreq > 0) { tf += wAnchor * anchorTermFreq / (1.0 + bAnchor * (anchorSize / avgAnchorSize - 1.0)); } tf = tf / (kf + tf); double idf = Math.log((N - n + 0.5) / (n + 0.5) + 1); return (tf + delta) * idf; } /** * Returns the relevance score between a term and a document based on a corpus. * @param freq the normalized term frequency of searching term in the document to rank. * @param N the number of documents in the corpus. * @param n the number of documents containing the given term in the corpus; * @return the relevance score. */ public double score(double freq, long N, long n) { if (freq <= 0) return 0.0; double tf = (k1 + 1) * freq / (freq + k1); double idf = Math.log((N - n + 0.5) / (n + 0.5) + 1); return (tf + delta) * idf; } /** * Returns the relevance score between a term and a document based on a corpus. * @param freq the frequency of searching term in the document to rank. * @param docSize the size of document to rank. * @param avgDocSize the average size of documents in the corpus. * @param N the number of documents in the corpus. * @param n the number of documents containing the given term in the corpus; * @return the relevance score. */ public double score(double freq, int docSize, double avgDocSize, long N, long n) { if (freq <= 0) return 0.0; double tf = freq * (k1 + 1) / (freq + k1 * (1 - b + b * docSize / avgDocSize)); double idf = Math.log((N - n + 0.5) / (n + 0.5) + 1); return (tf + delta) * idf; } @Override public double rank(Corpus corpus, TextTerms doc, String term, int tf, int n) { if (tf <= 0) return 0.0; int N = corpus.ndoc(); int docSize = doc.size(); int avgDocSize = corpus.avgDocSize(); return score(tf, docSize, avgDocSize, N, n); } @Override public double rank(Corpus corpus, TextTerms doc, String[] terms, int[] tf, int n) { int N = corpus.ndoc(); int docSize = doc.size(); int avgDocSize = corpus.avgDocSize(); double r = 0.0; for (int i = 0; i < terms.length; i++) { r += score(tf[i], docSize, avgDocSize, N, n); } return r; } }
amirgreenheart/DataSubmissionServiceAPI
spec/models/export/framework_suppliers_lots/extract_spec.rb
<gh_stars>1-10 require 'rails_helper' RSpec.describe Export::FrameworkSuppliersLots::Extract do describe '#all_relevant' do let(:all_relevant) { Export::FrameworkSuppliersLots::Extract.all_relevant(framework) } context 'with suppliers that have both active and inactive lots on a framework' do let!(:framework) do create(:framework, name: 'G-Cloud 42', short_name: 'RM5678.42') end let!(:active_supplier) do create(:supplier, name: 'Active Technologies', salesforce_id: 'ACT123') do |supplier| create(:agreement, supplier: supplier, framework: framework, active: true) do |agreement| create(:agreement_framework_lot, agreement: agreement, framework_lot: lot_1a) create(:agreement_framework_lot, agreement: agreement, framework_lot: lot_2b) end end end let!(:inactive_supplier) do create(:supplier, name: 'Inactive Ltd', salesforce_id: 'INACT456') do |supplier| create(:agreement, supplier: supplier, framework: framework, active: false) do |agreement| create(:agreement_framework_lot, agreement: agreement, framework_lot: lot_3) end end end let!(:supplier_not_on_lots) do create(:supplier, name: 'Forget Me Lots Ltd', salesforce_id: 'NOT000') do |supplier| create(:agreement, supplier: supplier, framework: framework, active: false) end end let!(:lot_1a) { create(:framework_lot, framework: framework, number: '1a') } let!(:lot_2b) { create(:framework_lot, framework: framework, number: '2b') } let!(:lot_3) { create(:framework_lot, framework: framework, number: '3') } let!(:other_framework) do create(:framework, name: 'Other Framework') do |framework| create(:agreement, supplier: active_supplier, framework: framework) end end it 'includes all suppliers and their lots for a given framework' do expect(all_relevant.size).to eql(3) end describe '#_framework_reference as a projection on the AgreementFrameworkLot model' do it 'is included in every result' do all_relevant.map(&:_framework_reference).each do |relevant| expect(relevant).to eql framework.short_name end end end describe '#_framework_name as a projection on the AgreementFrameworkLot model' do it 'is included in every result' do all_relevant.map(&:_framework_name).each do |relevant| expect(relevant).to eql framework.name end end end describe '#_supplier_name as a projection on the AgreementFrameworkLot model' do it 'contains the suppliers the correct number of times' do extracted_supplier_names = all_relevant.map(&:_supplier_name) expect(extracted_supplier_names).to match_array( [ active_supplier.name, active_supplier.name, inactive_supplier.name ] ) end end describe '#_supplier_salesforce_id as a projection on the AgreementFrameworkLot model' do it 'contains the suppliers the correct number of times' do extracted_supplier_salesforce_ids = all_relevant.map(&:_supplier_salesforce_id) expect(extracted_supplier_salesforce_ids).to match_array( [ active_supplier.salesforce_id, active_supplier.salesforce_id, inactive_supplier.salesforce_id ] ) end end describe '#_supplier_active as a projection on the AgreementFrameworkLot model' do it 'contains the suppliers on one or more lots' do extracted_supplier_statuses = all_relevant.map(&:_supplier_active) expect(extracted_supplier_statuses).to match_array( [ true, true, false ] ) end end describe '#_lot_number as a projection on the AgreementFrameworkLot model' do it 'contains the lot numbers of frameworks the suppliers belongs to' do extracted_lot_numbers = all_relevant.map(&:_lot_number) expect(extracted_lot_numbers).to match_array( [ '1a', '2b', '3' ] ) end end it 'excludes frameworks that were not requested' do expect(all_relevant.map(&:_framework_name)).not_to include 'Other Framework' end it 'excludes suppliers not on any lots' do expect(all_relevant.map(&:_supplier_name)).not_to include 'Forget Me Lots Ltd' end end end end
jonathas/libatsc3
src/atsc3_alp_parser.h
/* * atsc3_alp_parser.h * * Created on: May 1, 2019 * Author: jjustman */ #ifndef ATSC3_ALP_PARSER_H_ #define ATSC3_ALP_PARSER_H_ #include "atsc3_utils.h" #include "atsc3_logging_externs.h" #include "atsc3_alp_types.h" #include "atsc3_stltp_types.h" #if defined (__cplusplus) extern "C" { #endif void atsc3_alp_parse_stltp_baseband_packet(atsc3_stltp_baseband_packet_t* atsc3_stltp_baseband_packet); #if defined (__cplusplus) } #endif #define __ALP_PARSER_ERROR(...) printf("%s:%d:ERROR: ",__FILE__,__LINE__); printf(__VA_ARGS__); printf("%s%s","\r","\n") #define __ALP_PARSER_WARN(...) printf("%s:%d:WARN : ",__FILE__,__LINE__); printf(__VA_ARGS__); printf("%s%s","\r","\n") #define __ALP_PARSER_INFO(...) if(_ALP_PARSER_INFO_ENABLED) { printf("%s:%d:INFO:%.4f: ",__FILE__,__LINE__, gt()); printf(__VA_ARGS__); printf("%s%s","\r","\n"); } #define __ALP_PARSER_DEBUG(...) if(_ALP_PARSER_DEBUG_ENABLED) { printf("%s:%d:DEBUG: ",__FILE__,__LINE__); printf(__VA_ARGS__); printf("%s%s","\r","\n"); } #endif /* ATSC3_ALP_PARSER_H_ */
anmolnar/cloudbreak
core/src/main/java/com/sequenceiq/cloudbreak/service/StackUnderOperationService.java
package com.sequenceiq.cloudbreak.service; import org.springframework.stereotype.Service; @Service public class StackUnderOperationService { private static final ThreadLocal<Boolean> ON_LOCAL = new ThreadLocal<>(); private static final ThreadLocal<Long> STACK_ID_LOCAL = new ThreadLocal<>(); public void on() { ON_LOCAL.set(Boolean.TRUE); } public void off() { STACK_ID_LOCAL.remove(); ON_LOCAL.remove(); } public void set(Long stackId) { if (Boolean.TRUE.equals(ON_LOCAL.get())) { STACK_ID_LOCAL.set(stackId); } else { ON_LOCAL.remove(); } } public Long get() { Long stackId = STACK_ID_LOCAL.get(); if (stackId == null) { STACK_ID_LOCAL.remove(); } return stackId; } }
jkganzan13/tekken-ss
app/constants/routes.js
<filename>app/constants/routes.js export default [ { to: '/', name: 'Home' }, { to: '/combos', name: 'Combos' }, { to: '/moves', name: 'Move List' }, ];
likloadm/cross_platform_crypto
LibsodiumSignatureDetachedString/LibsodiumSignatureDetachedStringNodeJs.js
var tweetnacl = require('tweetnacl'); // https://www.npmjs.com/package/tweetnacl // https://github.com/dchest/tweetnacl-js tweetnacl.util = require('tweetnacl-util'); // https://github.com/dchest/tweetnacl-util-js#documentation console.log('Libsodium detached signature string'); var dataToSign = 'The quick brown fox jumps over the lazy dog'; console.log ('plaintext: ' + dataToSign); // usually we would load the private and public key from a file or keystore // here we use hardcoded keys for demonstration - don't do this in real programs console.log ('\n* * * sign the plaintext with the ED25519 private key * * *'); var privateKey = loadEd25519PrivateKey(); var signatureBase64 = libsodiumSignDetachedToBase64(privateKey, dataToSign); console.log ('signature (Base64): ' + signatureBase64); console.log ('signature (Base64): ' + 'x41mufah/9VO347W+nPXu5FYeSJOI894YClbbTiX0pwRrvfAPMymxEvyMMsDFMI0R0sulCnuCRSgN0WOKnZBDg=='); console.log ('\n* * * verify the signature against the plaintext with the ED25519 public key * * *'); var publicKey = loadEd25519PublicKey(); var signatureVerified = libsodiumVerifyDetachedFromBase64(publicKey, dataToSign, signatureBase64); console.log ('signature (Base64): ' + signatureBase64); console.log ('signature (Base64) verified: ' + signatureVerified); function libsodiumSignDetachedToBase64(privateKey, data){ var plaintext = tweetnacl.util.decodeUTF8(data); return base64Encoding(tweetnacl.sign.detached(plaintext, privateKey)); } function libsodiumVerifyDetachedFromBase64(publicKey, data, signatureBase64){ var plaintext = tweetnacl.util.decodeUTF8(data); return tweetnacl.sign.detached.verify(plaintext, base64Decoding(signatureBase64), publicKey) } function loadEd25519PrivateKey() { // this is a sample key - don't worry ! return base64Decoding("<KEY>); } function loadEd25519PublicKey() { // this is a sample key - don't worry ! return base64Decoding("<KEY> } function base64Encoding(input) { return tweetnacl.util.encodeBase64(input); } function base64Decoding(input) { return tweetnacl.util.decodeBase64(input); }
jsango2/kolega-dental
src/components/RadnoVrijeme/styles.js
import styled from "styled-components" import mjesto from "../../../content/assets/Mapview.png" export const WrapRadnoVrijeme = styled.div` position: relative; width: 100%; height: 1215px; /* padding-top: 60px; */ @media screen and (max-width: 768px) { height: auto; } ` export const WrapTimetable = styled.div` position: absolute; top: 40px; left: -31px; width: 481px; height: 650px; background: #32bde3; border-radius: 38px; display: flex; z-index: 5; flex-direction: column; justify-content: center; align-items: center; -webkit-box-shadow: -2px 18px 24px 5px rgba(6, 25, 31, 0.24); box-shadow: -2px 18px 24px 5px rgba(6, 25, 31, 0.24); padding-left: 32px; transition: all 1s ease-in-out; transform: ${props => (props.inView ? `translate(0%)` : `translate(-40%)`)}; opacity: ${props => (props.inView ? `1` : `0`)}; @media screen and (max-width: 1000px) { width: 400px; } @media screen and (max-width: 768px) { width: 80%; min-width: 350px; position: relative; top: auto; left: auto; padding-left: 0; margin: 0 auto 130px auto; } @media screen and (max-width: 440px) { width: 100%; min-width: 350px; position: relative; top: auto; left: auto; padding-left: 0; margin: 0 auto 0 auto; border-radius: 0; } ` export const Title = styled.h2` font-family: Avenir Next; font-style: normal; font-weight: bold; font-size: 40px; line-height: 120%; /* identical to box height, or 48px */ text-align: center; margin-bottom: 60px; /* SUNRISE / White */ color: #ffffff; @media screen and (max-width: 460px) { font-size: 34px; } ` export const Satnica = styled.div` @media screen and (max-width: 768px) { /* order: 1; margin-bottom: 1rem; */ } ` export const DnevniRaspored = styled.div` display: flex; justify-content: space-between; align-items: center; width: 337px; margin-bottom: 25px; @media screen and (max-width: 768px) { width: 300px; } ` export const WrapDanCrta = styled.div` display: flex; justify-content: space-between; align-items: center; width: 167px; @media screen and (max-width: 768px) { width: 153px; } ` export const Dan = styled.div` font-family: Work Sans; font-style: normal; font-weight: normal; font-size: 18px; line-height: 140%; /* or 25px */ /* white */ color: #fcfefe; @media screen and (max-width: 768px) { /* order: 1; margin-bottom: 1rem; */ } ` export const Crta = styled.div` width: 20px; height: 2px; background-color: white; @media screen and (max-width: 768px) { /* order: 1; margin-bottom: 1rem; */ } ` export const WrapMap = styled.div` position: absolute; z-index: 1; top: 226px; left: 27%; width: 944px; height: 523px; border-radius: 20px; overflow: hidden; -webkit-box-shadow: -2px 18px 24px 5px rgba(6, 25, 31, 0.24); box-shadow: -2px 18px 24px 5px rgba(6, 25, 31, 0.24); transition: all 1.6s ease-in-out; transform: ${props => (props.inView ? `translate(0%)` : `translate(40%)`)}; opacity: ${props => (props.inView ? `1` : `0`)}; @media screen and (max-width: 768px) { position: relative; top: auto; left: auto; width: 100%; height: 83vw; border-radius: 0; } @media screen and (max-width: 440px) { transform: none; opacity: 1; } ` export const Sat = styled.div` font-family: Work Sans; font-style: normal; font-weight: normal; font-size: 18px; line-height: 140%; /* or 25px */ /* white */ color: #fcfefe; @media screen and (max-width: 768px) { /* order: 1; margin-bottom: 1rem; */ } ` export const WrapLogo = styled.div` position: absolute; right: 0; top: 20px; @media screen and (max-width: 768px) { /* order: 1; margin-bottom: 1rem; */ } ` export const WrapTockice = styled.div` position: absolute; left: 35%; top: 20px; @media screen and (max-width: 768px) { /* order: 1; margin-bottom: 1rem; */ } ` export const WrapSitneTockice = styled.div` position: absolute; left: 5%; bottom: 300px; @media screen and (max-width: 768px) { /* order: 1; margin-bottom: 1rem; */ } ` export const Lokacija = styled.div` width: 85%; height: 396px; position: absolute; z-index: 5; bottom: 70px; left: 40%; overflow: hidden; border-radius: 20px; transform: translate(-25%); background-image: url(${mjesto}); background-position: center; background-repeat: no-repeat; background-size: cover; -webkit-box-shadow: -2px 18px 24px 5px rgba(6, 25, 31, 0.24); box-shadow: -2px 18px 24px 5px rgba(6, 25, 31, 0.24); /* transition: all 1s ease-in-out 1s; transform: ${props => props.inView ? `translate(-20%, 0%)` : `translate(-20%,30%)`}; opacity: ${props => (props.inView ? `1` : `0`)}; */ @media screen and (max-width: 768px) { position: relative; top: auto; width: 100%; height: 70vw; bottom: auto; left: 0; transform: translate(0%); border-radius: 0; } ` export const Adresa = styled.p` position: absolute; bottom: 30px; right: 45px; font-family: Avenir Next; font-style: normal; font-weight: 500; font-size: 18px; line-height: 120%; /* identical to box height, or 22px */ text-align: right; /* SUNRISE / White */ color: #ffffff; @media screen and (max-width: 768px) { /* order: 1; margin-bottom: 1rem; */ } ` export const Button = styled.a` width: 252px; height: 38px; background: #32bde3; /* SUNRISE/Coral */ position: absolute; border: 3px solid #32bde3; box-sizing: border-box; border-radius: 15px; bottom: 46px; left: 42px; font-family: Avenir Next; font-style: normal; font-weight: 500; font-size: 18px; line-height: 120%; color: #ffffff; display: flex; align-items: center; justify-content: space-around; cursor: pointer; text-decoration: none; &:hover { background: #416ca5; border: 4px solid #416ca5; box-sizing: border-box; border-radius: 15px; color: white; } @media screen and (max-width: 768px) { /* order: 1; margin-bottom: 1rem; */ } ` export const ButtonDirection = styled.a` position: relative; z-index: 10; display: flex; flex-direction: row; align-items: center; padding: 14px 32px; max-height: 53px; border: none; background-color: ${props => props.bgColor}; color: ${props => props.color}; width: ${props => props.width}; justify-content: center; box-shadow: 0px 14px 23px rgba(28, 37, 44, 0.08); border-radius: 30px; /* Buttons */ font-family: Avenir Next; font-style: normal; font-weight: bold; font-size: 21px; line-height: 120%; /* or 25px */ z-index: 2; text-align: left; cursor: pointer; /* SUNRISE / White */ transition: all 0.5s ease-in-out; text-decoration: none; color: ${props => props.color}; &:hover a { color: inherit; } &:hover { box-shadow: 3px 3px 15px 0px #2088b3; border-radius: 30px; } @media screen and (max-width: 440px) { font-size: 18px; } @media screen and (max-width: 1000px) { /* z-index: 0; */ } `
ScalablyTyped/SlinkyTyped
m/maxim_mazurok__gapi_dot_client_dot_cloudscheduler/src/main/scala/typingsSlinky/maximMazurokGapiClientCloudscheduler/gapi/client/cloudscheduler/Job.scala
<filename>m/maxim_mazurok__gapi_dot_client_dot_cloudscheduler/src/main/scala/typingsSlinky/maximMazurokGapiClientCloudscheduler/gapi/client/cloudscheduler/Job.scala<gh_stars>10-100 package typingsSlinky.maximMazurokGapiClientCloudscheduler.gapi.client.cloudscheduler import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait Job extends StObject { /** App Engine HTTP target. */ var appEngineHttpTarget: js.UndefOr[AppEngineHttpTarget] = js.native /** * The deadline for job attempts. If the request handler does not respond by this deadline then the request is cancelled and the attempt is marked as a `DEADLINE_EXCEEDED` failure. The * failed attempt can be viewed in execution logs. Cloud Scheduler will retry the job according to the RetryConfig. The allowed duration for this deadline is: * For HTTP targets, * between 15 seconds and 30 minutes. * For App Engine HTTP targets, between 15 seconds and 24 hours. */ var attemptDeadline: js.UndefOr[String] = js.native /** Optionally caller-specified in CreateJob or UpdateJob. A human-readable description for the job. This string must not contain more than 500 characters. */ var description: js.UndefOr[String] = js.native /** HTTP target. */ var httpTarget: js.UndefOr[HttpTarget] = js.native /** Output only. The time the last job attempt started. */ var lastAttemptTime: js.UndefOr[String] = js.native /** * Optionally caller-specified in CreateJob, after which it becomes output only. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * `PROJECT_ID` can * contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), or periods (.). For more information, see [Identifying * projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the job's location. The list of * available locations can be obtained by calling ListLocations. For more information, see https://cloud.google.com/about/locations/. * `JOB_ID` can contain only letters ([A-Za-z]), * numbers ([0-9]), hyphens (-), or underscores (_). The maximum length is 500 characters. */ var name: js.UndefOr[String] = js.native /** Pub/Sub target. */ var pubsubTarget: js.UndefOr[PubsubTarget] = js.native /** Settings that determine the retry behavior. */ var retryConfig: js.UndefOr[RetryConfig] = js.native /** * Required, except when used with UpdateJob. Describes the schedule on which the job will be executed. The schedule can be either of the following types: * * [Crontab](http://en.wikipedia.org/wiki/Cron#Overview) * English-like [schedule](https://cloud.google.com/scheduler/docs/configuring/cron-job-schedules) As a general rule, execution * `n + 1` of a job will not begin until execution `n` has finished. Cloud Scheduler will never allow two simultaneously outstanding executions. For example, this implies that if the * `n+1`th execution is scheduled to run at 16:00 but the `n`th execution takes until 16:15, the `n+1`th execution will not start until `16:15`. A scheduled start time will be delayed * if the previous execution has not ended when its scheduled time occurs. If retry_count > 0 and a job attempt fails, the job will be tried a total of retry_count times, with * exponential backoff, until the next scheduled start time. */ var schedule: js.UndefOr[String] = js.native /** Output only. The next time the job is scheduled. Note that this may be a retry of a previously failed attempt or the next execution time according to the schedule. */ var scheduleTime: js.UndefOr[String] = js.native /** Output only. State of the job. */ var state: js.UndefOr[String] = js.native /** Output only. The response from the target for the last attempted execution. */ var status: js.UndefOr[Status] = js.native /** * Specifies the time zone to be used in interpreting schedule. The value of this field must be a time zone name from the [tz database](http://en.wikipedia.org/wiki/Tz_database). Note * that some time zones include a provision for daylight savings time. The rules for daylight saving time are determined by the chosen tz. For UTC use the string "utc". If a time zone * is not specified, the default will be in UTC (also known as GMT). */ var timeZone: js.UndefOr[String] = js.native /** Output only. The creation time of the job. */ var userUpdateTime: js.UndefOr[String] = js.native } object Job { @scala.inline def apply(): Job = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[Job] } @scala.inline implicit class JobMutableBuilder[Self <: Job] (val x: Self) extends AnyVal { @scala.inline def setAppEngineHttpTarget(value: AppEngineHttpTarget): Self = StObject.set(x, "appEngineHttpTarget", value.asInstanceOf[js.Any]) @scala.inline def setAppEngineHttpTargetUndefined: Self = StObject.set(x, "appEngineHttpTarget", js.undefined) @scala.inline def setAttemptDeadline(value: String): Self = StObject.set(x, "attemptDeadline", value.asInstanceOf[js.Any]) @scala.inline def setAttemptDeadlineUndefined: Self = StObject.set(x, "attemptDeadline", js.undefined) @scala.inline def setDescription(value: String): Self = StObject.set(x, "description", value.asInstanceOf[js.Any]) @scala.inline def setDescriptionUndefined: Self = StObject.set(x, "description", js.undefined) @scala.inline def setHttpTarget(value: HttpTarget): Self = StObject.set(x, "httpTarget", value.asInstanceOf[js.Any]) @scala.inline def setHttpTargetUndefined: Self = StObject.set(x, "httpTarget", js.undefined) @scala.inline def setLastAttemptTime(value: String): Self = StObject.set(x, "lastAttemptTime", value.asInstanceOf[js.Any]) @scala.inline def setLastAttemptTimeUndefined: Self = StObject.set(x, "lastAttemptTime", js.undefined) @scala.inline def setName(value: String): Self = StObject.set(x, "name", value.asInstanceOf[js.Any]) @scala.inline def setNameUndefined: Self = StObject.set(x, "name", js.undefined) @scala.inline def setPubsubTarget(value: PubsubTarget): Self = StObject.set(x, "pubsubTarget", value.asInstanceOf[js.Any]) @scala.inline def setPubsubTargetUndefined: Self = StObject.set(x, "pubsubTarget", js.undefined) @scala.inline def setRetryConfig(value: RetryConfig): Self = StObject.set(x, "retryConfig", value.asInstanceOf[js.Any]) @scala.inline def setRetryConfigUndefined: Self = StObject.set(x, "retryConfig", js.undefined) @scala.inline def setSchedule(value: String): Self = StObject.set(x, "schedule", value.asInstanceOf[js.Any]) @scala.inline def setScheduleTime(value: String): Self = StObject.set(x, "scheduleTime", value.asInstanceOf[js.Any]) @scala.inline def setScheduleTimeUndefined: Self = StObject.set(x, "scheduleTime", js.undefined) @scala.inline def setScheduleUndefined: Self = StObject.set(x, "schedule", js.undefined) @scala.inline def setState(value: String): Self = StObject.set(x, "state", value.asInstanceOf[js.Any]) @scala.inline def setStateUndefined: Self = StObject.set(x, "state", js.undefined) @scala.inline def setStatus(value: Status): Self = StObject.set(x, "status", value.asInstanceOf[js.Any]) @scala.inline def setStatusUndefined: Self = StObject.set(x, "status", js.undefined) @scala.inline def setTimeZone(value: String): Self = StObject.set(x, "timeZone", value.asInstanceOf[js.Any]) @scala.inline def setTimeZoneUndefined: Self = StObject.set(x, "timeZone", js.undefined) @scala.inline def setUserUpdateTime(value: String): Self = StObject.set(x, "userUpdateTime", value.asInstanceOf[js.Any]) @scala.inline def setUserUpdateTimeUndefined: Self = StObject.set(x, "userUpdateTime", js.undefined) } }
aifargonos2/elk-reasoner
elk-owl-parent/elk-owl-model/src/main/java/org/semanticweb/elk/owl/visitors/ElkObjectPropertyAxiomVisitor.java
<gh_stars>10-100 /* * #%L * elk-reasoner * * $Id: ElkObjectPropertyAxiomVisitor.java 297 2011-08-10 14:42:57Z <EMAIL> $ * $HeadURL: https://elk-reasoner.googlecode.com/svn/trunk/elk-reasoner/src/main/java/org/semanticweb/elk/syntax/ElkObjectPropertyAxiomVisitor.java $ * %% * Copyright (C) 2011 Oxford University Computing Laboratory * %% * 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. * #L% */ /** * @author <NAME>, Apr 8, 2011 */ package org.semanticweb.elk.owl.visitors; import org.semanticweb.elk.owl.interfaces.ElkObjectPropertyAxiom; /** * Visitor pattern interface for instances of {@link ElkObjectPropertyAxiom}. * * @author <NAME> * @author <NAME> * * @param <O> * the type of the output of this visitor */ public interface ElkObjectPropertyAxiomVisitor<O> extends ElkAsymmetricObjectPropertyAxiomVisitor<O>, ElkDisjointObjectPropertiesAxiomVisitor<O>, ElkEquivalentObjectPropertiesAxiomVisitor<O>, ElkFunctionalObjectPropertyAxiomVisitor<O>, ElkInverseFunctionalObjectPropertyAxiomVisitor<O>, ElkInverseObjectPropertiesAxiomVisitor<O>, ElkIrreflexiveObjectPropertyAxiomVisitor<O>, ElkObjectPropertyDomainAxiomVisitor<O>, ElkObjectPropertyRangeAxiomVisitor<O>, ElkReflexiveObjectPropertyAxiomVisitor<O>, ElkSubObjectPropertyOfAxiomVisitor<O>, ElkSymmetricObjectPropertyAxiomVisitor<O>, ElkTransitiveObjectPropertyAxiomVisitor<O> { // combined visitor }
jadedsurfer/creativechallenge
server/server.js
<reponame>jadedsurfer/creativechallenge var loopback = require('loopback'); var boot = require('loopback-boot'); var app = module.exports = loopback(); app.start = function appStart() { // start the web server return app.listen(function appListen() { app.emit('started'); console.log('Web server listening at: %s', app.get('host')); }); }; // Bootstrap the application, configure models, datasources and middleware. // Sub-apps like REST API are mounted via boot scripts. boot(app, __dirname, function startApp(err, sys){ if (err) { console.error(err); process.exit(1); } app.start(); });
sosu-rochelt/com.rochelt.www
src/components/molecules/InfoGraphicSlider/InfoGraphicSlider.js
import React from 'react'; import PropTypes from 'prop-types'; // import Link from "gatsby-link"import Waypoint from 'react-waypoint'; import Markdown from 'react-remarkable'; import Slick from 'react-slick'; import Measure from 'react-measure'; import { Link } from 'react-router'; import cx from 'classnames'; import Image from '../../atoms/Image'; import styles from './InfoGraphicSlider.scss'; /** * General component description in JSDoc format. Markdown is *supported*. */ /** * @param {string} * @param {string} * @param {...[type]} * @return {node} */ class InfoGraphicSlider extends React.Component { constructor(props) { super(props); this.state = { activeIndex: 0, dimensions: { width: -1, height: -1 } }; } infoContainer(index, infoItems, background) { if (index !== null) { const info = infoItems[index]; let wrappedInfo = ( <div className={cx({ info: true })} style={{}} > <div className="info-image" style={{ backgroundImage: `url(${info.image})` }} > <Image src={background} variant={[]} /> </div> <div className="info-text"> <Markdown options={{ breaks: true }}>{info.copy}</Markdown> </div> </div> ); return wrappedInfo; } } render() { var settings = { arrows: false, dots: false, infinite: true, draggable: false, speed: 0, fade: true, autoplay: false, autoplaySpeed: 5000, adaptiveHeight: false, slickGoTo: 1, beforeChange: (prevIndex, nextIndex) => { this.setState({ activeIndex: nextIndex }); } }; return ( <div className={cx({ infoGraphicSlider: true })} > <div style={{}} className="infoGraphicSlider-wrapper"> <Slick ref="slider" className={cx({ slider: true })} {...settings} > {this.props.items.map((item, index) => { return ( <div key={`infoGraphicSlider-${index}`}> {this.infoContainer( index, this.props.items, this.props.background )} </div> ); })} </Slick> <div className={cx({ infoGraphicSlider_dots: true })} style={{ top: this.state.dimensions.height }} > {this.props.items.map((item, index) => ( <div key={`infoGraphicSlider_dot-${index}`} className={cx({ infoGraphicSlider_dot: true, 'infoGraphicSlider_dot--active': this.state.activeIndex === index })} onClick={e => { this.refs.slider.innerSlider.slickGoTo(index); }} /> ))} </div> <div className="infoGraphicSlider_background"> <Measure bounds onResize={contentRect => { this.setState({ dimensions: contentRect.bounds }); }} > {({ measureRef }) => ( <div ref={measureRef}> <Image src={this.props.background} variant={[]} /> </div> )} </Measure> </div> </div> </div> ); } } InfoGraphicSlider.propTypes = { background: PropTypes.string, overlay: PropTypes.string }; InfoGraphicSlider.defaultProps = {}; export default InfoGraphicSlider;
navidkhoshavi/marss.cacheLineData
qemu/hw/pcnet.h
#define PCNET_IOPORT_SIZE 0x20 #define PCNET_PNPMMIO_SIZE 0x20 #define PCNET_LOOPTEST_CRC 1 #define PCNET_LOOPTEST_NOCRC 2 typedef struct PCNetState_st PCNetState; struct PCNetState_st { NICState *nic; NICConf conf; QEMUTimer *poll_timer; int rap, isr, lnkst; uint32_t rdra, tdra; uint8_t prom[16]; uint16_t csr[128]; uint16_t bcr[32]; uint64_t timer; int mmio_index, xmit_pos; uint8_t buffer[4096]; int tx_busy; qemu_irq irq; void (*phys_mem_read)(void *dma_opaque, target_phys_addr_t addr, uint8_t *buf, int len, int do_bswap); void (*phys_mem_write)(void *dma_opaque, target_phys_addr_t addr, uint8_t *buf, int len, int do_bswap); void *dma_opaque; int looptest; }; void pcnet_h_reset(void *opaque); void pcnet_ioport_writew(void *opaque, uint32_t addr, uint32_t val); uint32_t pcnet_ioport_readw(void *opaque, uint32_t addr); void pcnet_ioport_writel(void *opaque, uint32_t addr, uint32_t val); uint32_t pcnet_ioport_readl(void *opaque, uint32_t addr); uint32_t pcnet_bcr_readw(PCNetState *s, uint32_t rap); int pcnet_can_receive(VLANClientState *nc); ssize_t pcnet_receive(VLANClientState *nc, const uint8_t *buf, size_t size_); void pcnet_common_cleanup(PCNetState *d); int pcnet_common_init(DeviceState *dev, PCNetState *s, NetClientInfo *info); extern const VMStateDescription vmstate_pcnet;
reactivators-studio-playground/CarteJaune
reducers/__test__/vaccinations.js
<filename>reducers/__test__/vaccinations.js import { OrderedMap } from 'immutable'; import { expect } from 'chai'; import reducer from '../vaccinations'; import { ADD_VACCINATION, FETCH_VACCINATIONS_SUCCESS, } from '../../constants/actions'; describe('vaccinations', () => { it('returns an initial state', () => { const nextState = reducer(undefined, { type: 'SOMETHING', }); expect(nextState).to.deep.equal(OrderedMap()); }); it('sets the current vaccination id on ADD_VACCINATION', () => { const nextState = reducer(undefined, { type: ADD_VACCINATION, vaccineId: 222, vaccinationDate: 444, }); expect(nextState.first().get('id')).to.equal(222); expect(nextState.first().get('date')).to.equal(444); }); it('sets the state to the vavvinations from the FETCH_VACCINATIONS_SUCCESS action', () => { const nextState = reducer(4444, { type: FETCH_VACCINATIONS_SUCCESS, vaccinations: OrderedMap({ id: 1, date: 3 }), }); const expected = OrderedMap({ id: 1, date: 3 }); expect(nextState).to.deep.equal(expected); }); });
onap/policy-models
models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/CdsSimulator.java
<reponame>onap/policy-models /*- * ============LICENSE_START======================================================= * Copyright (C) 2020 Nordix Foundation. * Modifications Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ package org.onap.policy.simulators; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.util.JsonFormat; import io.grpc.Server; import io.grpc.netty.NettyServerBuilder; import io.grpc.stub.StreamObserver; import java.io.IOException; import java.net.InetSocketAddress; import java.time.Instant; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import lombok.Getter; import org.apache.commons.lang3.StringUtils; import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType; import org.onap.ccsdk.cds.controllerblueprints.common.api.Status; import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase; import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput; import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput; import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput.Builder; import org.onap.policy.common.utils.resources.ResourceUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CdsSimulator implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(CdsSimulator.class); @Getter private final int port; private final Server server; private final String resourceLocation; private AtomicInteger countOfEvents = new AtomicInteger(1); /** * Constructs the object, but does not start it. * * @param host host name of the server * @param port port of the server */ public CdsSimulator(String host, int port) { this(host, port, "org/onap/policy/simulators/cds/", 0, 0); } /** * Constructs the object, but does not start it. * * @param host host name of the server * @param port port of the server * @param countOfSuccesfulEvents number of successive successful events * @param requestedResponseDelayMs time for the request to be processed */ public CdsSimulator(String host, int port, String resourceLocation, int countOfSuccesfulEvents, long requestedResponseDelayMs) { this.port = port; this.resourceLocation = resourceLocation; BluePrintProcessingServiceImplBase testCdsBlueprintServerImpl = new BluePrintProcessingServiceImplBase() { @Override public StreamObserver<ExecutionServiceInput> process( final StreamObserver<ExecutionServiceOutput> responseObserver) { return new StreamObserver<ExecutionServiceInput>() { @Override public void onNext(final ExecutionServiceInput executionServiceInput) { LOGGER.info("Received request input to CDS: {}", executionServiceInput); try { var builder = getResponse(executionServiceInput, countOfSuccesfulEvents); TimeUnit.MILLISECONDS.sleep(requestedResponseDelayMs); responseObserver.onNext(builder.build()); } catch (InvalidProtocolBufferException e) { throw new SimulatorRuntimeException("Cannot convert ExecutionServiceOutput output", e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new SimulatorRuntimeException("Execution Interrupted", e); } } @Override public void onError(final Throwable throwable) { responseObserver.onError(throwable); } @Override public void onCompleted() { responseObserver.onCompleted(); } }; } }; server = NettyServerBuilder.forAddress(new InetSocketAddress(host, port)).addService(testCdsBlueprintServerImpl) .build(); } /** * Start the server. * * @throws IOException IO exception. */ public void start() throws IOException { server.start(); // The grpc server uses daemon threads by default. Hence the application will exit as soon the main thread // completes. So, wrap the server in a non-daemon thread and call awaitTermination to keep the thread alive // until the server is terminated. new Thread(this).start(); } /** * Stop the server. */ public void stop() { server.shutdown(); } /** * Constructs the ResponseString on the basis of request. * * @param executionServiceInput service input * @param countOfSuccesfulEvents number of successive successful events * @return builder for ExecutionServiceOutput response * @throws InvalidProtocolBufferException when response string cannot be converted */ public Builder getResponse(ExecutionServiceInput executionServiceInput, int countOfSuccesfulEvents) throws InvalidProtocolBufferException { var resourceName = "DefaultResponseEvent"; if (!StringUtils.isBlank(executionServiceInput.getActionIdentifiers().getActionName())) { var actionIdentifiers = executionServiceInput.getActionIdentifiers(); resourceName = actionIdentifiers.getBlueprintName() + "-" + actionIdentifiers.getActionName(); } if (countOfSuccesfulEvents > 0 && countOfEvents.getAndIncrement() % countOfSuccesfulEvents == 0) { // generating the failure response resourceName = resourceName + "-error.json"; } else { resourceName = resourceName + ".json"; } LOGGER.info("Fetching response from {}", resourceName); var responseString = ResourceUtils.getResourceAsString(resourceLocation + resourceName); var builder = ExecutionServiceOutput.newBuilder(); if (null == responseString) { LOGGER.info("Expected response file {} not found in {}", resourceName, resourceLocation); var actionIdentifiers = executionServiceInput.getActionIdentifiers(); builder.setCommonHeader(executionServiceInput.getCommonHeader()); builder.setActionIdentifiers(actionIdentifiers); builder.setPayload(executionServiceInput.getPayload()); builder.setStatus(Status.newBuilder().setCode(500).setMessage("failure") .setErrorMessage("failed to get get cba file name(" + actionIdentifiers.getBlueprintName() + "), version(" + actionIdentifiers.getBlueprintVersion() + ") from db : file check failed.") .setEventType(EventType.EVENT_COMPONENT_FAILURE).setTimestamp(Instant.now().toString())); } else { LOGGER.debug("Returning response from CDS Simulator: {}", responseString); JsonFormat.parser().ignoringUnknownFields().merge(responseString, builder); } return builder; } @Override public void run() { try { server.awaitTermination(); } catch (InterruptedException e) { LOGGER.info("gRPC server is terminated"); Thread.currentThread().interrupt(); } } }
bdunne/catalog-api
lib/tasks/list_rbac.rake
require 'rake' namespace :catalog do namespace :rbac do namespace :list do options = {} options[:user_file] = ENV['USER_FILE'] options[:debug] = ENV['DEBUG'] desc "List groups for a tenant" task :groups => :environment do raise "Please provide a user credential yaml file" unless ENV['USER_FILE'] RBAC::Tools::Group.new(options).process end desc "List roles for a tenant" task :roles => :environment do raise "Please provide a user credential yaml file" unless ENV['USER_FILE'] RBAC::Tools::Role.new(options).process end desc "List policies for a tenant" task :policies => :environment do raise "Please provide a user credential yaml file" unless ENV['USER_FILE'] RBAC::Tools::Policy.new(options).process end end end end
Gohan/aws-sdk-cpp
aws-cpp-sdk-cloudfront/include/aws/cloudfront/model/ViewerCertificate.h
<filename>aws-cpp-sdk-cloudfront/include/aws/cloudfront/model/ViewerCertificate.h /* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/cloudfront/CloudFront_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/cloudfront/model/SSLSupportMethod.h> #include <aws/cloudfront/model/MinimumProtocolVersion.h> #include <utility> namespace Aws { namespace Utils { namespace Xml { class XmlNode; } // namespace Xml } // namespace Utils namespace CloudFront { namespace Model { /** * <p>A complex type that specifies the following:</p> <ul> <li> <p>Whether you * want viewers to use HTTP or HTTPS to request your objects.</p> </li> <li> <p>If * you want viewers to use HTTPS, whether you're using an alternate domain name * such as <code>example.com</code> or the CloudFront domain name for your * distribution, such as <code>d111111abcdef8.cloudfront.net</code>.</p> </li> <li> * <p>If you're using an alternate domain name, whether AWS Certificate Manager * (ACM) provided the certificate, or you purchased a certificate from a * third-party certificate authority and imported it into ACM or uploaded it to the * IAM certificate store.</p> </li> </ul> <p>You must specify only one of the * following values: </p> <ul> <li> <p> <a>ViewerCertificate$ACMCertificateArn</a> * </p> </li> <li> <p> <a>ViewerCertificate$IAMCertificateId</a> </p> </li> <li> * <p> <a>ViewerCertificate$CloudFrontDefaultCertificate</a> </p> </li> </ul> * <p>Don't specify <code>false</code> for * <code>CloudFrontDefaultCertificate</code>.</p> <p> <b>If you want viewers to use * HTTP instead of HTTPS to request your objects</b>: Specify the following * value:</p> <p> * <code>&lt;CloudFrontDefaultCertificate&gt;true&lt;CloudFrontDefaultCertificate&gt;</code> * </p> <p>In addition, specify <code>allow-all</code> for * <code>ViewerProtocolPolicy</code> for all of your cache behaviors.</p> <p> <b>If * you want viewers to use HTTPS to request your objects</b>: Choose the type of * certificate that you want to use based on whether you're using an alternate * domain name for your objects or the CloudFront domain name:</p> <ul> <li> <p> * <b>If you're using an alternate domain name, such as example.com</b>: Specify * one of the following values, depending on whether ACM provided your certificate * or you purchased your certificate from third-party certificate authority:</p> * <ul> <li> <p> <code>&lt;ACMCertificateArn&gt;<i>ARN for ACM SSL/TLS * certificate</i>&lt;ACMCertificateArn&gt;</code> where <code> <i>ARN for ACM * SSL/TLS certificate</i> </code> is the ARN for the ACM SSL/TLS certificate that * you want to use for this distribution.</p> </li> <li> <p> * <code>&lt;IAMCertificateId&gt;<i>IAM certificate * ID</i>&lt;IAMCertificateId&gt;</code> where <code> <i>IAM certificate ID</i> * </code> is the ID that IAM returned when you added the certificate to the IAM * certificate store.</p> </li> </ul> <p>If you specify * <code>ACMCertificateArn</code> or <code>IAMCertificateId</code>, you must also * specify a value for <code>SSLSupportMethod</code>.</p> <p>If you choose to use * an ACM certificate or a certificate in the IAM certificate store, we recommend * that you use only an alternate domain name in your object URLs * (<code>https://example.com/logo.jpg</code>). If you use the domain name that is * associated with your CloudFront distribution (such as * <code>https://d111111abcdef8.cloudfront.net/logo.jpg</code>) and the viewer * supports <code>SNI</code>, then CloudFront behaves normally. However, if the * browser does not support SNI, the user's experience depends on the value that * you choose for <code>SSLSupportMethod</code>:</p> <ul> <li> <p> * <code>vip</code>: The viewer displays a warning because there is a mismatch * between the CloudFront domain name and the domain name in your SSL/TLS * certificate.</p> </li> <li> <p> <code>sni-only</code>: CloudFront drops the * connection with the browser without returning the object.</p> </li> </ul> </li> * <li> <p> <b>If you're using the CloudFront domain name for your distribution, * such as <code>d111111abcdef8.cloudfront.net</code> </b>: Specify the following * value:</p> <p> * <code>&lt;CloudFrontDefaultCertificate&gt;true&lt;CloudFrontDefaultCertificate&gt; * </code> </p> </li> </ul> <p>If you want viewers to use HTTPS, you must also * specify one of the following values in your cache behaviors:</p> <ul> <li> <p> * <code> &lt;ViewerProtocolPolicy&gt;https-only&lt;ViewerProtocolPolicy&gt;</code> * </p> </li> <li> <p> * <code>&lt;ViewerProtocolPolicy&gt;redirect-to-https&lt;ViewerProtocolPolicy&gt;</code> * </p> </li> </ul> <p>You can also optionally require that CloudFront use HTTPS to * communicate with your origin by specifying one of the following values for the * applicable origins:</p> <ul> <li> <p> * <code>&lt;OriginProtocolPolicy&gt;https-only&lt;OriginProtocolPolicy&gt; </code> * </p> </li> <li> <p> * <code>&lt;OriginProtocolPolicy&gt;match-viewer&lt;OriginProtocolPolicy&gt; * </code> </p> </li> </ul> <p>For more information, see <a * href="http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/SecureConnections.html#CNAMEsAndHTTPS">Using * Alternate Domain Names and HTTPS</a> in the <i>Amazon CloudFront Developer * Guide</i>.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/cloudfront-2018-06-18/ViewerCertificate">AWS * API Reference</a></p> */ class AWS_CLOUDFRONT_API ViewerCertificate { public: ViewerCertificate(); ViewerCertificate(const Aws::Utils::Xml::XmlNode& xmlNode); ViewerCertificate& operator=(const Aws::Utils::Xml::XmlNode& xmlNode); void AddToNode(Aws::Utils::Xml::XmlNode& parentNode) const; /** * <p>For information about how and when to use * <code>CloudFrontDefaultCertificate</code>, see <a>ViewerCertificate</a>.</p> */ inline bool GetCloudFrontDefaultCertificate() const{ return m_cloudFrontDefaultCertificate; } /** * <p>For information about how and when to use * <code>CloudFrontDefaultCertificate</code>, see <a>ViewerCertificate</a>.</p> */ inline void SetCloudFrontDefaultCertificate(bool value) { m_cloudFrontDefaultCertificateHasBeenSet = true; m_cloudFrontDefaultCertificate = value; } /** * <p>For information about how and when to use * <code>CloudFrontDefaultCertificate</code>, see <a>ViewerCertificate</a>.</p> */ inline ViewerCertificate& WithCloudFrontDefaultCertificate(bool value) { SetCloudFrontDefaultCertificate(value); return *this;} /** * <p>For information about how and when to use <code>IAMCertificateId</code>, see * <a>ViewerCertificate</a>.</p> */ inline const Aws::String& GetIAMCertificateId() const{ return m_iAMCertificateId; } /** * <p>For information about how and when to use <code>IAMCertificateId</code>, see * <a>ViewerCertificate</a>.</p> */ inline void SetIAMCertificateId(const Aws::String& value) { m_iAMCertificateIdHasBeenSet = true; m_iAMCertificateId = value; } /** * <p>For information about how and when to use <code>IAMCertificateId</code>, see * <a>ViewerCertificate</a>.</p> */ inline void SetIAMCertificateId(Aws::String&& value) { m_iAMCertificateIdHasBeenSet = true; m_iAMCertificateId = std::move(value); } /** * <p>For information about how and when to use <code>IAMCertificateId</code>, see * <a>ViewerCertificate</a>.</p> */ inline void SetIAMCertificateId(const char* value) { m_iAMCertificateIdHasBeenSet = true; m_iAMCertificateId.assign(value); } /** * <p>For information about how and when to use <code>IAMCertificateId</code>, see * <a>ViewerCertificate</a>.</p> */ inline ViewerCertificate& WithIAMCertificateId(const Aws::String& value) { SetIAMCertificateId(value); return *this;} /** * <p>For information about how and when to use <code>IAMCertificateId</code>, see * <a>ViewerCertificate</a>.</p> */ inline ViewerCertificate& WithIAMCertificateId(Aws::String&& value) { SetIAMCertificateId(std::move(value)); return *this;} /** * <p>For information about how and when to use <code>IAMCertificateId</code>, see * <a>ViewerCertificate</a>.</p> */ inline ViewerCertificate& WithIAMCertificateId(const char* value) { SetIAMCertificateId(value); return *this;} /** * <p>For information about how and when to use <code>ACMCertificateArn</code>, see * <a>ViewerCertificate</a>.</p> */ inline const Aws::String& GetACMCertificateArn() const{ return m_aCMCertificateArn; } /** * <p>For information about how and when to use <code>ACMCertificateArn</code>, see * <a>ViewerCertificate</a>.</p> */ inline void SetACMCertificateArn(const Aws::String& value) { m_aCMCertificateArnHasBeenSet = true; m_aCMCertificateArn = value; } /** * <p>For information about how and when to use <code>ACMCertificateArn</code>, see * <a>ViewerCertificate</a>.</p> */ inline void SetACMCertificateArn(Aws::String&& value) { m_aCMCertificateArnHasBeenSet = true; m_aCMCertificateArn = std::move(value); } /** * <p>For information about how and when to use <code>ACMCertificateArn</code>, see * <a>ViewerCertificate</a>.</p> */ inline void SetACMCertificateArn(const char* value) { m_aCMCertificateArnHasBeenSet = true; m_aCMCertificateArn.assign(value); } /** * <p>For information about how and when to use <code>ACMCertificateArn</code>, see * <a>ViewerCertificate</a>.</p> */ inline ViewerCertificate& WithACMCertificateArn(const Aws::String& value) { SetACMCertificateArn(value); return *this;} /** * <p>For information about how and when to use <code>ACMCertificateArn</code>, see * <a>ViewerCertificate</a>.</p> */ inline ViewerCertificate& WithACMCertificateArn(Aws::String&& value) { SetACMCertificateArn(std::move(value)); return *this;} /** * <p>For information about how and when to use <code>ACMCertificateArn</code>, see * <a>ViewerCertificate</a>.</p> */ inline ViewerCertificate& WithACMCertificateArn(const char* value) { SetACMCertificateArn(value); return *this;} /** * <p>If you specify a value for <a>ViewerCertificate$ACMCertificateArn</a> or for * <a>ViewerCertificate$IAMCertificateId</a>, you must also specify how you want * CloudFront to serve HTTPS requests: using a method that works for all clients or * one that works for most clients:</p> <ul> <li> <p> <code>vip</code>: CloudFront * uses dedicated IP addresses for your content and can respond to HTTPS requests * from any viewer. However, you will incur additional monthly charges.</p> </li> * <li> <p> <code>sni-only</code>: CloudFront can respond to HTTPS requests from * viewers that support Server Name Indication (SNI). All modern browsers support * SNI, but some browsers still in use don't support SNI. If some of your users' * browsers don't support SNI, we recommend that you do one of the following:</p> * <ul> <li> <p>Use the <code>vip</code> option (dedicated IP addresses) instead of * <code>sni-only</code>.</p> </li> <li> <p>Use the CloudFront SSL/TLS certificate * instead of a custom certificate. This requires that you use the CloudFront * domain name of your distribution in the URLs for your objects, for example, * <code>https://d111111abcdef8.cloudfront.net/logo.png</code>.</p> </li> <li> * <p>If you can control which browser your users use, upgrade the browser to one * that supports SNI.</p> </li> <li> <p>Use HTTP instead of HTTPS.</p> </li> </ul> * </li> </ul> <p>Don't specify a value for <code>SSLSupportMethod</code> if you * specified * <code>&lt;CloudFrontDefaultCertificate&gt;true&lt;CloudFrontDefaultCertificate&gt;</code>.</p> * <p>For more information, see <a * href="http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/SecureConnections.html#CNAMEsAndHTTPS.html">Using * Alternate Domain Names and HTTPS</a> in the <i>Amazon CloudFront Developer * Guide</i>.</p> */ inline const SSLSupportMethod& GetSSLSupportMethod() const{ return m_sSLSupportMethod; } /** * <p>If you specify a value for <a>ViewerCertificate$ACMCertificateArn</a> or for * <a>ViewerCertificate$IAMCertificateId</a>, you must also specify how you want * CloudFront to serve HTTPS requests: using a method that works for all clients or * one that works for most clients:</p> <ul> <li> <p> <code>vip</code>: CloudFront * uses dedicated IP addresses for your content and can respond to HTTPS requests * from any viewer. However, you will incur additional monthly charges.</p> </li> * <li> <p> <code>sni-only</code>: CloudFront can respond to HTTPS requests from * viewers that support Server Name Indication (SNI). All modern browsers support * SNI, but some browsers still in use don't support SNI. If some of your users' * browsers don't support SNI, we recommend that you do one of the following:</p> * <ul> <li> <p>Use the <code>vip</code> option (dedicated IP addresses) instead of * <code>sni-only</code>.</p> </li> <li> <p>Use the CloudFront SSL/TLS certificate * instead of a custom certificate. This requires that you use the CloudFront * domain name of your distribution in the URLs for your objects, for example, * <code>https://d111111abcdef8.cloudfront.net/logo.png</code>.</p> </li> <li> * <p>If you can control which browser your users use, upgrade the browser to one * that supports SNI.</p> </li> <li> <p>Use HTTP instead of HTTPS.</p> </li> </ul> * </li> </ul> <p>Don't specify a value for <code>SSLSupportMethod</code> if you * specified * <code>&lt;CloudFrontDefaultCertificate&gt;true&lt;CloudFrontDefaultCertificate&gt;</code>.</p> * <p>For more information, see <a * href="http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/SecureConnections.html#CNAMEsAndHTTPS.html">Using * Alternate Domain Names and HTTPS</a> in the <i>Amazon CloudFront Developer * Guide</i>.</p> */ inline void SetSSLSupportMethod(const SSLSupportMethod& value) { m_sSLSupportMethodHasBeenSet = true; m_sSLSupportMethod = value; } /** * <p>If you specify a value for <a>ViewerCertificate$ACMCertificateArn</a> or for * <a>ViewerCertificate$IAMCertificateId</a>, you must also specify how you want * CloudFront to serve HTTPS requests: using a method that works for all clients or * one that works for most clients:</p> <ul> <li> <p> <code>vip</code>: CloudFront * uses dedicated IP addresses for your content and can respond to HTTPS requests * from any viewer. However, you will incur additional monthly charges.</p> </li> * <li> <p> <code>sni-only</code>: CloudFront can respond to HTTPS requests from * viewers that support Server Name Indication (SNI). All modern browsers support * SNI, but some browsers still in use don't support SNI. If some of your users' * browsers don't support SNI, we recommend that you do one of the following:</p> * <ul> <li> <p>Use the <code>vip</code> option (dedicated IP addresses) instead of * <code>sni-only</code>.</p> </li> <li> <p>Use the CloudFront SSL/TLS certificate * instead of a custom certificate. This requires that you use the CloudFront * domain name of your distribution in the URLs for your objects, for example, * <code>https://d111111abcdef8.cloudfront.net/logo.png</code>.</p> </li> <li> * <p>If you can control which browser your users use, upgrade the browser to one * that supports SNI.</p> </li> <li> <p>Use HTTP instead of HTTPS.</p> </li> </ul> * </li> </ul> <p>Don't specify a value for <code>SSLSupportMethod</code> if you * specified * <code>&lt;CloudFrontDefaultCertificate&gt;true&lt;CloudFrontDefaultCertificate&gt;</code>.</p> * <p>For more information, see <a * href="http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/SecureConnections.html#CNAMEsAndHTTPS.html">Using * Alternate Domain Names and HTTPS</a> in the <i>Amazon CloudFront Developer * Guide</i>.</p> */ inline void SetSSLSupportMethod(SSLSupportMethod&& value) { m_sSLSupportMethodHasBeenSet = true; m_sSLSupportMethod = std::move(value); } /** * <p>If you specify a value for <a>ViewerCertificate$ACMCertificateArn</a> or for * <a>ViewerCertificate$IAMCertificateId</a>, you must also specify how you want * CloudFront to serve HTTPS requests: using a method that works for all clients or * one that works for most clients:</p> <ul> <li> <p> <code>vip</code>: CloudFront * uses dedicated IP addresses for your content and can respond to HTTPS requests * from any viewer. However, you will incur additional monthly charges.</p> </li> * <li> <p> <code>sni-only</code>: CloudFront can respond to HTTPS requests from * viewers that support Server Name Indication (SNI). All modern browsers support * SNI, but some browsers still in use don't support SNI. If some of your users' * browsers don't support SNI, we recommend that you do one of the following:</p> * <ul> <li> <p>Use the <code>vip</code> option (dedicated IP addresses) instead of * <code>sni-only</code>.</p> </li> <li> <p>Use the CloudFront SSL/TLS certificate * instead of a custom certificate. This requires that you use the CloudFront * domain name of your distribution in the URLs for your objects, for example, * <code>https://d111111abcdef8.cloudfront.net/logo.png</code>.</p> </li> <li> * <p>If you can control which browser your users use, upgrade the browser to one * that supports SNI.</p> </li> <li> <p>Use HTTP instead of HTTPS.</p> </li> </ul> * </li> </ul> <p>Don't specify a value for <code>SSLSupportMethod</code> if you * specified * <code>&lt;CloudFrontDefaultCertificate&gt;true&lt;CloudFrontDefaultCertificate&gt;</code>.</p> * <p>For more information, see <a * href="http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/SecureConnections.html#CNAMEsAndHTTPS.html">Using * Alternate Domain Names and HTTPS</a> in the <i>Amazon CloudFront Developer * Guide</i>.</p> */ inline ViewerCertificate& WithSSLSupportMethod(const SSLSupportMethod& value) { SetSSLSupportMethod(value); return *this;} /** * <p>If you specify a value for <a>ViewerCertificate$ACMCertificateArn</a> or for * <a>ViewerCertificate$IAMCertificateId</a>, you must also specify how you want * CloudFront to serve HTTPS requests: using a method that works for all clients or * one that works for most clients:</p> <ul> <li> <p> <code>vip</code>: CloudFront * uses dedicated IP addresses for your content and can respond to HTTPS requests * from any viewer. However, you will incur additional monthly charges.</p> </li> * <li> <p> <code>sni-only</code>: CloudFront can respond to HTTPS requests from * viewers that support Server Name Indication (SNI). All modern browsers support * SNI, but some browsers still in use don't support SNI. If some of your users' * browsers don't support SNI, we recommend that you do one of the following:</p> * <ul> <li> <p>Use the <code>vip</code> option (dedicated IP addresses) instead of * <code>sni-only</code>.</p> </li> <li> <p>Use the CloudFront SSL/TLS certificate * instead of a custom certificate. This requires that you use the CloudFront * domain name of your distribution in the URLs for your objects, for example, * <code>https://d111111abcdef8.cloudfront.net/logo.png</code>.</p> </li> <li> * <p>If you can control which browser your users use, upgrade the browser to one * that supports SNI.</p> </li> <li> <p>Use HTTP instead of HTTPS.</p> </li> </ul> * </li> </ul> <p>Don't specify a value for <code>SSLSupportMethod</code> if you * specified * <code>&lt;CloudFrontDefaultCertificate&gt;true&lt;CloudFrontDefaultCertificate&gt;</code>.</p> * <p>For more information, see <a * href="http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/SecureConnections.html#CNAMEsAndHTTPS.html">Using * Alternate Domain Names and HTTPS</a> in the <i>Amazon CloudFront Developer * Guide</i>.</p> */ inline ViewerCertificate& WithSSLSupportMethod(SSLSupportMethod&& value) { SetSSLSupportMethod(std::move(value)); return *this;} /** * <p>Specify the security policy that you want CloudFront to use for HTTPS * connections. A security policy determines two settings:</p> <ul> <li> <p>The * minimum SSL/TLS protocol that CloudFront uses to communicate with viewers</p> * </li> <li> <p>The cipher that CloudFront uses to encrypt the content that it * returns to viewers</p> </li> </ul> <note> <p>On the CloudFront console, this * setting is called <b>Security policy</b>.</p> </note> <p>We recommend that you * specify <code>TLSv1.1_2016</code> unless your users are using browsers or * devices that do not support TLSv1.1 or later.</p> <p>When both of the following * are true, you must specify <code>TLSv1</code> or later for the security policy: * </p> <ul> <li> <p>You're using a custom certificate: you specified a value for * <code>ACMCertificateArn</code> or for <code>IAMCertificateId</code> </p> </li> * <li> <p>You're using SNI: you specified <code>sni-only</code> for * <code>SSLSupportMethod</code> </p> </li> </ul> <p>If you specify * <code>true</code> for <code>CloudFrontDefaultCertificate</code>, CloudFront * automatically sets the security policy to <code>TLSv1</code> regardless of the * value that you specify for <code>MinimumProtocolVersion</code>.</p> <p>For * information about the relationship between the security policy that you choose * and the protocols and ciphers that CloudFront uses to communicate with viewers, * see <a * href="http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/secure-connections-supported-viewer-protocols-ciphers.html#secure-connections-supported-ciphers"> * Supported SSL/TLS Protocols and Ciphers for Communication Between Viewers and * CloudFront</a> in the <i>Amazon CloudFront Developer Guide</i>.</p> */ inline const MinimumProtocolVersion& GetMinimumProtocolVersion() const{ return m_minimumProtocolVersion; } /** * <p>Specify the security policy that you want CloudFront to use for HTTPS * connections. A security policy determines two settings:</p> <ul> <li> <p>The * minimum SSL/TLS protocol that CloudFront uses to communicate with viewers</p> * </li> <li> <p>The cipher that CloudFront uses to encrypt the content that it * returns to viewers</p> </li> </ul> <note> <p>On the CloudFront console, this * setting is called <b>Security policy</b>.</p> </note> <p>We recommend that you * specify <code>TLSv1.1_2016</code> unless your users are using browsers or * devices that do not support TLSv1.1 or later.</p> <p>When both of the following * are true, you must specify <code>TLSv1</code> or later for the security policy: * </p> <ul> <li> <p>You're using a custom certificate: you specified a value for * <code>ACMCertificateArn</code> or for <code>IAMCertificateId</code> </p> </li> * <li> <p>You're using SNI: you specified <code>sni-only</code> for * <code>SSLSupportMethod</code> </p> </li> </ul> <p>If you specify * <code>true</code> for <code>CloudFrontDefaultCertificate</code>, CloudFront * automatically sets the security policy to <code>TLSv1</code> regardless of the * value that you specify for <code>MinimumProtocolVersion</code>.</p> <p>For * information about the relationship between the security policy that you choose * and the protocols and ciphers that CloudFront uses to communicate with viewers, * see <a * href="http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/secure-connections-supported-viewer-protocols-ciphers.html#secure-connections-supported-ciphers"> * Supported SSL/TLS Protocols and Ciphers for Communication Between Viewers and * CloudFront</a> in the <i>Amazon CloudFront Developer Guide</i>.</p> */ inline void SetMinimumProtocolVersion(const MinimumProtocolVersion& value) { m_minimumProtocolVersionHasBeenSet = true; m_minimumProtocolVersion = value; } /** * <p>Specify the security policy that you want CloudFront to use for HTTPS * connections. A security policy determines two settings:</p> <ul> <li> <p>The * minimum SSL/TLS protocol that CloudFront uses to communicate with viewers</p> * </li> <li> <p>The cipher that CloudFront uses to encrypt the content that it * returns to viewers</p> </li> </ul> <note> <p>On the CloudFront console, this * setting is called <b>Security policy</b>.</p> </note> <p>We recommend that you * specify <code>TLSv1.1_2016</code> unless your users are using browsers or * devices that do not support TLSv1.1 or later.</p> <p>When both of the following * are true, you must specify <code>TLSv1</code> or later for the security policy: * </p> <ul> <li> <p>You're using a custom certificate: you specified a value for * <code>ACMCertificateArn</code> or for <code>IAMCertificateId</code> </p> </li> * <li> <p>You're using SNI: you specified <code>sni-only</code> for * <code>SSLSupportMethod</code> </p> </li> </ul> <p>If you specify * <code>true</code> for <code>CloudFrontDefaultCertificate</code>, CloudFront * automatically sets the security policy to <code>TLSv1</code> regardless of the * value that you specify for <code>MinimumProtocolVersion</code>.</p> <p>For * information about the relationship between the security policy that you choose * and the protocols and ciphers that CloudFront uses to communicate with viewers, * see <a * href="http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/secure-connections-supported-viewer-protocols-ciphers.html#secure-connections-supported-ciphers"> * Supported SSL/TLS Protocols and Ciphers for Communication Between Viewers and * CloudFront</a> in the <i>Amazon CloudFront Developer Guide</i>.</p> */ inline void SetMinimumProtocolVersion(MinimumProtocolVersion&& value) { m_minimumProtocolVersionHasBeenSet = true; m_minimumProtocolVersion = std::move(value); } /** * <p>Specify the security policy that you want CloudFront to use for HTTPS * connections. A security policy determines two settings:</p> <ul> <li> <p>The * minimum SSL/TLS protocol that CloudFront uses to communicate with viewers</p> * </li> <li> <p>The cipher that CloudFront uses to encrypt the content that it * returns to viewers</p> </li> </ul> <note> <p>On the CloudFront console, this * setting is called <b>Security policy</b>.</p> </note> <p>We recommend that you * specify <code>TLSv1.1_2016</code> unless your users are using browsers or * devices that do not support TLSv1.1 or later.</p> <p>When both of the following * are true, you must specify <code>TLSv1</code> or later for the security policy: * </p> <ul> <li> <p>You're using a custom certificate: you specified a value for * <code>ACMCertificateArn</code> or for <code>IAMCertificateId</code> </p> </li> * <li> <p>You're using SNI: you specified <code>sni-only</code> for * <code>SSLSupportMethod</code> </p> </li> </ul> <p>If you specify * <code>true</code> for <code>CloudFrontDefaultCertificate</code>, CloudFront * automatically sets the security policy to <code>TLSv1</code> regardless of the * value that you specify for <code>MinimumProtocolVersion</code>.</p> <p>For * information about the relationship between the security policy that you choose * and the protocols and ciphers that CloudFront uses to communicate with viewers, * see <a * href="http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/secure-connections-supported-viewer-protocols-ciphers.html#secure-connections-supported-ciphers"> * Supported SSL/TLS Protocols and Ciphers for Communication Between Viewers and * CloudFront</a> in the <i>Amazon CloudFront Developer Guide</i>.</p> */ inline ViewerCertificate& WithMinimumProtocolVersion(const MinimumProtocolVersion& value) { SetMinimumProtocolVersion(value); return *this;} /** * <p>Specify the security policy that you want CloudFront to use for HTTPS * connections. A security policy determines two settings:</p> <ul> <li> <p>The * minimum SSL/TLS protocol that CloudFront uses to communicate with viewers</p> * </li> <li> <p>The cipher that CloudFront uses to encrypt the content that it * returns to viewers</p> </li> </ul> <note> <p>On the CloudFront console, this * setting is called <b>Security policy</b>.</p> </note> <p>We recommend that you * specify <code>TLSv1.1_2016</code> unless your users are using browsers or * devices that do not support TLSv1.1 or later.</p> <p>When both of the following * are true, you must specify <code>TLSv1</code> or later for the security policy: * </p> <ul> <li> <p>You're using a custom certificate: you specified a value for * <code>ACMCertificateArn</code> or for <code>IAMCertificateId</code> </p> </li> * <li> <p>You're using SNI: you specified <code>sni-only</code> for * <code>SSLSupportMethod</code> </p> </li> </ul> <p>If you specify * <code>true</code> for <code>CloudFrontDefaultCertificate</code>, CloudFront * automatically sets the security policy to <code>TLSv1</code> regardless of the * value that you specify for <code>MinimumProtocolVersion</code>.</p> <p>For * information about the relationship between the security policy that you choose * and the protocols and ciphers that CloudFront uses to communicate with viewers, * see <a * href="http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/secure-connections-supported-viewer-protocols-ciphers.html#secure-connections-supported-ciphers"> * Supported SSL/TLS Protocols and Ciphers for Communication Between Viewers and * CloudFront</a> in the <i>Amazon CloudFront Developer Guide</i>.</p> */ inline ViewerCertificate& WithMinimumProtocolVersion(MinimumProtocolVersion&& value) { SetMinimumProtocolVersion(std::move(value)); return *this;} private: bool m_cloudFrontDefaultCertificate; bool m_cloudFrontDefaultCertificateHasBeenSet; Aws::String m_iAMCertificateId; bool m_iAMCertificateIdHasBeenSet; Aws::String m_aCMCertificateArn; bool m_aCMCertificateArnHasBeenSet; SSLSupportMethod m_sSLSupportMethod; bool m_sSLSupportMethodHasBeenSet; MinimumProtocolVersion m_minimumProtocolVersion; bool m_minimumProtocolVersionHasBeenSet; }; } // namespace Model } // namespace CloudFront } // namespace Aws
kmestry/PROBLEM_SOLVING_HACKERRANK_LEETCODE
src/com/leetcode/RandomPointInNonOverlappingRectangles.java
<reponame>kmestry/PROBLEM_SOLVING_HACKERRANK_LEETCODE package com.leetcode; import java.util.Random; import java.util.TreeMap; public class RandomPointInNonOverlappingRectangles { Random random; TreeMap<Integer, int[]> map; int areaSum = 0; public RandomPointInNonOverlappingRectangles(int[][] rects) { this.random = new Random(); this.map = new TreeMap<>(); for (int i = 0; i < rects.length; i++) { int[] rectangeCoordinates = rects[i]; int length = rectangeCoordinates[2] - rectangeCoordinates[0] + 1; // +1 as we need to consider edges also. int breadth = rectangeCoordinates[3] - rectangeCoordinates[1] + 1; areaSum += length * breadth; map.put(areaSum, rectangeCoordinates); } } public static void main(String[] args) { Random random = new Random(); int bound = 7; System.out.println("random = " + random.nextInt(bound + 1)); System.out.println("random = " + random.nextInt(bound + 1)); System.out.println("random = " + random.nextInt(bound + 1)); System.out.println("random = " + random.nextInt(bound + 1)); System.out.println("random = " + random.nextInt(bound + 1)); System.out.println("random = " + random.nextInt(bound + 1)); System.out.println("random = " + random.nextInt(bound + 1)); System.out.println("random = " + random.nextInt(bound + 1)); System.out.println("random = " + random.nextInt(bound + 1)); System.out.println("random = " + random.nextInt(bound + 1)); /* RandomPointInNonOverlappingRectangles obj = new RandomPointInNonOverlappingRectangles(new int[][]{{-2, -2, -1, -1}, {1, 0, 3, 0}}); obj.pick(); obj.pick(); obj.pick(); obj.pick();*/ } public int[] pick() { int key = map.ceilingKey(random.nextInt(areaSum) + 1); //Don't forget to +1 here, because we need [1,area] while nextInt generates [0,area-1] int[] rectangle = map.get(key); int length = rectangle[2] - rectangle[0] + 1; // +1 as we need to consider edges also. int breadth = rectangle[3] - rectangle[1] + 1; int x = rectangle[0] + random.nextInt(length); //return random length from starting position of x int y = rectangle[1] + random.nextInt(breadth); // return random breadth from starting position of y return new int[]{x, y}; } }
MrFreemanser/Bot
cosmos/galaxies/settings/__init__.py
from .administrator import AdministratorSettings __all__ = [ AdministratorSettings, ] def setup(bot): bot.plugins.setup(__file__)
windows-development/Windows-classic-samples
Samples/Win7Samples/tabletpc/advreco/cpp/ChildWnds.cpp
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. // // Module: // ChildWnds.cpp // // Description: // The file contains the definitions of the methods of the classes // CInkInputWnd and CRecoOutputWnd. // See the file ChildWnds.h for the definitions of the classes. //-------------------------------------------------------------------------- #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0500 #endif // Windows header file #include <windows.h> // ATL header files: #include <atlbase.h> // defines CComModule, CComPtr, CComVariant extern CComModule _Module; #include <atlwin.h> // defines CWindowImpl // Tablet PC Automation interfaces header file #include <msinkaut.h> // The application header files #include "resource.h" // main symbols, including command ID's #include "ChildWnds.h" // contains the CInkInputWnd and CRecoOutputWnd definitions #define CLR_BLUE RGB(0x00,0x00,0x80) #define CLR_GRAY RGB(0x80,0x80,0x80) //////////////////////////////////////////////////////// // CInkInputWnd methods //////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// // // CInkInputWnd::CInkInputWnd // // Constructor. // // Parameters: // none // ///////////////////////////////////////////////////////// CInkInputWnd::CInkInputWnd() : m_cRows(0), m_cColumns(0), m_iMidline(-1) { m_ptGridLT.x = m_ptGridLT.y = 0; m_szWritingBox.cx = m_szWritingBox.cy = 0; ::SetRectEmpty(&m_rcDrawnBox); } ///////////////////////////////////////////////////////// // // CInkInputWnd::SetGuide // // Data members access method for setting the guide // drawing parameters. // // Parameters: // _InkRecoGuide& irg : see the Tablet PC Automation API // reference for the description // of the structure // // Return Values (void): // none // ///////////////////////////////////////////////////////// void CInkInputWnd::SetGuide(const _InkRecoGuide& irg) { // Initialize the data members with values from the recognition guide structure m_ptGridLT.x = irg.rectWritingBox.left; m_ptGridLT.y = irg.rectWritingBox.top; m_szWritingBox.cx = irg.rectWritingBox.right - irg.rectWritingBox.left; m_szWritingBox.cy = irg.rectWritingBox.bottom - irg.rectWritingBox.top; m_rcDrawnBox = irg.rectDrawnBox; m_iMidline = irg.midline; m_cRows = irg.cRows; m_cColumns = irg.cColumns; // Update the window if (IsWindow()) { Invalidate(); } } ///////////////////////////////////////////////////////// // // CInkInputWnd::SetGuide // // Data members access method for setting the number // of the guide's rows and columns. // // Parameters: // int iRows : the number of rows // int iColumns : the number of columns // // Return Values (void): // none // ///////////////////////////////////////////////////////// void CInkInputWnd::SetRowsCols(int iRows, int iColumns) { m_cRows = iRows; m_cColumns = iColumns; // Update the window if (IsWindow()) { Invalidate(); } } ///////////////////////////////////////////////////////// // // CInkInputWnd::OnPaint // // The WM_PAINT message handler. The ATL calls this member // function when Windows or an application makes a request // to repaint a portion of the CInkInputWnd object's window. // The method paints the window's background and draws // the guide if necessary. // // Parameters: // defined in the ATL's MESSAGE_HANDLER macro, // none is used here // // Return Value (LRESULT): // always 0 // ///////////////////////////////////////////////////////// LRESULT CInkInputWnd::OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { RECT rcClip; if (FALSE == GetUpdateRect(&rcClip)) return 0; // there's no update region, so no painting is needed PAINTSTRUCT ps; HDC hdc = BeginPaint(&ps); if (hdc == NULL) return 0; // Get the rectangle to paint. GetClipBox(hdc, &rcClip); // Paint the background. ::FillRect(hdc, &rcClip, (HBRUSH)::GetStockObject(DC_BRUSH)); // Calculate the grid rectangle. Assume that if there are any guides, // they are either boxes or horizontal lines. RECT rcGrid = {m_ptGridLT.x, m_ptGridLT.y, 0, m_ptGridLT.y + m_szWritingBox.cy * m_cRows}; if (0 == m_cColumns && 0 != m_cRows) { rcGrid.right = rcClip.right; } else { rcGrid.right = m_ptGridLT.x + m_szWritingBox.cx * m_cColumns; } // Draw the guide grid, if it's visible and not empty. RECT rcVisible; if (FALSE == ::IsRectEmpty(&rcGrid) && TRUE == ::IntersectRect(&rcVisible, &rcGrid, &rcClip)) { // Create a thin lightgray pen to draw the guides. HPEN hPen = ::CreatePen(PS_SOLID, 1, RGB(192, 192, 192)); HGDIOBJ hOldPen = ::SelectObject(hdc, hPen); if (0 == m_cColumns) { // Draw horizontal lines at the bottom side of the guide's DrawnBox int iY = rcClip.top - ((rcClip.top - m_ptGridLT.y) % m_szWritingBox.cy) + m_rcDrawnBox.bottom; for (int iRow = (rcClip.top - m_ptGridLT.y) / m_szWritingBox.cy; (iRow < m_cRows) && (iY < rcClip.bottom); iRow++, iY += m_szWritingBox.cy) { ::MoveToEx(hdc, rcClip.left, iY, NULL); ::LineTo(hdc, rcClip.right, iY); } } else { // Draw boxes int iY = rcClip.top - ((rcClip.top - m_ptGridLT.y) % m_szWritingBox.cy); for (int iRow = (rcClip.top - m_ptGridLT.y) / m_szWritingBox.cy; (iRow < m_cRows) && (iY < rcClip.bottom); iRow++, iY += m_szWritingBox.cy) { int iX = rcClip.left - ((rcClip.left - m_ptGridLT.x) % m_szWritingBox.cx); RECT rcBox = m_rcDrawnBox; ::OffsetRect(&rcBox, iX, iY); for (int iCol = (rcClip.left - m_ptGridLT.x) / m_szWritingBox.cx; (iCol < m_cColumns) && (rcBox.left < rcClip.right); iCol++) { ::Rectangle(hdc, rcBox.left, rcBox.top, rcBox.right, rcBox.bottom); ::OffsetRect(&rcBox, m_szWritingBox.cx, 0); } } } // Restore the dc and delete the pen ::SelectObject(hdc, hOldPen); ::DeleteObject(hPen); } EndPaint(&ps); return 0; } //////////////////////////////////////////////////////// // CRecoOutputWnd methods //////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// // // CRecoOutputWnd::CRecoOutputWnd // // Constructor. // // Parameters: // none // ///////////////////////////////////////////////////////// CRecoOutputWnd::CRecoOutputWnd() : m_hFont(NULL), m_iFontName(-1), m_nGesture(0), m_bNewGesture(false) { UpdateFont(::GetUserDefaultLangID()); } ///////////////////////////////////////////////////////// // // CRecoOutputWnd::~CRecoOutputWnd // // Destructor. // ///////////////////////////////////////////////////////// CRecoOutputWnd::~CRecoOutputWnd() { if (NULL != m_hFont) { ::DeleteObject(m_hFont); } } // Message handlers ///////////////////////////////////////////////////////// // // CRecoOutputWnd::OnPaint // // The WM_PAINT message handler. The ATL calls this member // function when Windows or an application makes a request // to repaint a portion of the CRecoOutputWnd object's window. // // Parameters: // defined in the ATL's MESSAGE_HANDLER macro, // none is used here // // Return Value (void): // none // ///////////////////////////////////////////////////////// LRESULT CRecoOutputWnd::OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { RECT rc; if (FALSE == GetUpdateRect(&rc)) return 0; // there's no update region, so no painting is needed PAINTSTRUCT ps; HDC hdc = BeginPaint(&ps); if (hdc == NULL) return 0; GetClientRect(&rc); // Paint the background ::FillRect(hdc, &rc, (HBRUSH)::GetStockObject(WHITE_BRUSH)); // Use blue color to draw the latest results, and gray for the old ones COLORREF clrGesture, clrText; if (true == m_bNewGesture) { clrGesture = CLR_BLUE; clrText = CLR_GRAY; } else { clrGesture = CLR_GRAY; clrText = CLR_BLUE; } COLORREF clrOld = ::SetTextColor(hdc, clrGesture); // Output the name of the last gesture if (0 != m_nGesture) { TCHAR buffer[100]; if (::LoadString(_Module.GetResourceInstance(), m_nGesture, buffer, sizeof(buffer)/sizeof(buffer[0])) != 0) { ::TextOut(hdc, mc_iMarginX, mc_iMarginY, buffer, _tcslen(buffer)); } } // Output the handwriting recognition results HGDIOBJ hOldFont; if (NULL != m_hFont) { hOldFont = ::SelectObject(hdc, m_hFont); } ::SetTextColor(hdc, clrText); for (int i = 0; i < mc_iNumResults; i++) { int iLength = m_bstrResults[i].Length(); if (iLength) { ::TextOutW(hdc, mc_iMarginX, mc_iMarginY + (i + 1) * mc_iFontHeight, m_bstrResults[i], iLength); } } // Restore the dc ::SetTextColor(hdc, clrOld); if (NULL != m_hFont) { ::SelectObject(hdc, hOldFont); } EndPaint(&ps); return 0; } // Helper methods ///////////////////////////////////////////////////////// // // CRecoOutputWnd::ResetResults // // Empties the output strings. // // Parameters: // none // // Return Value (void): // none // ///////////////////////////////////////////////////////// void CRecoOutputWnd::ResetResults() { m_bNewGesture = false; m_nGesture = 0; for (int i = 0; i < mc_iNumResults; i++) m_bstrResults[i].Empty(); } ///////////////////////////////////////////////////////// // // CRecoOutputWnd::GetBestHeight // // Returns a height of the window the best to show all // the strings (the mc_iNumResults result strings and // the name of the last geesture). // // This method is called by CAdvRecoApp object when it updates // the layouts of its child windows. // ///////////////////////////////////////////////////////// int CRecoOutputWnd::GetBestHeight() { return (mc_iMarginX * 2 + mc_iFontHeight * (mc_iNumResults + 1)); } ///////////////////////////////////////////////////////// // // CRecoOutputWnd::UpdateFont // // The method creates an appropriate font for text output // based on the language id. It's called by the application // when user selects a recognizer. // // Parameters: // LANGID wLangId : [in] the id of the language of the text // // Return Value (bool): // true, if succeded to create a font appropriate for the language // false otherwise // ///////////////////////////////////////////////////////// bool CRecoOutputWnd::UpdateFont(LANGID wLangId) { static LPCTSTR pszFontNames[] = { TEXT("MS Shell Dlg"), TEXT("MS Mincho"), TEXT("Mingliu"), TEXT("Gullim") }; bool bOk = true; int i; DWORD dwCharSet; // Select a font by the primary language id (the lower byte) switch(wLangId & 0xFF) { default: i = 0; dwCharSet = DEFAULT_CHARSET; break; case LANG_JAPANESE: i = 1; dwCharSet = SHIFTJIS_CHARSET; break; case LANG_CHINESE: i = 2; dwCharSet = CHINESEBIG5_CHARSET; break; case LANG_KOREAN: i = 3; dwCharSet = JOHAB_CHARSET; break; } if (i != m_iFontName) { HFONT hFont = ::CreateFont(mc_iFontHeight, 0, 0, 0, 0, 0, 0, 0, dwCharSet, 0, 0, 0, 0, pszFontNames[i] // typeface name ); if (NULL != hFont) { if (NULL != m_hFont) ::DeleteObject(m_hFont); m_hFont = hFont; m_iFontName = i; } else { bOk = false; } } return bOk; } ///////////////////////////////////////////////////////// // // CRecoOutputWnd::SetGesture // // The method is called by the application from OnGesture // event handler. It accepts the id if the recognized gesture // and converts it to a string for output. // // Parameters: // InkGestureType idGesture : [in] the id of the language of the text // // Return Value (bool): // true - the name of the gesture is known to this application // false - otherwise // ///////////////////////////////////////////////////////// void CRecoOutputWnd::SetGestureName(UINT nGesture) { m_nGesture = nGesture; m_bNewGesture = true; }
ukchukx/saleor-dashboard
cypress/utils/misc.js
<gh_stars>1-10 import moment from "moment-timezone"; export function getDatePeriod(days) { if (days < 1) { return {}; } const end = moment().startOf("day"); const start = end.subtract(days - 1); const format = "YYYY-MM-DD"; return { gte: start.format(format), lte: end.format(format) }; }
ttungbmt/BecaGIS_GeoPortal
geonode/geonode/qgis_server/models.py
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # 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/>. # ######################################################################### import logging import os from shutil import rmtree from xml.etree import ElementTree import requests from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from geonode.security.models import PermissionLevelMixin from lxml import etree from defusedxml import lxml as dlxml from six import string_types from geonode import qgis_server from geonode.compat import ensure_string from geonode.layers.models import Layer from geonode.maps.models import Map from geonode.utils import check_ogc_backend logger = logging.getLogger("geonode.qgis_server.models") if check_ogc_backend(qgis_server.BACKEND_PACKAGE): QGIS_LAYER_DIRECTORY = settings.QGIS_SERVER_CONFIG['layer_directory'] QGIS_TILES_DIRECTORY = settings.QGIS_SERVER_CONFIG['tiles_directory'] if not os.path.exists(QGIS_LAYER_DIRECTORY): os.mkdir(QGIS_LAYER_DIRECTORY) class QGISServerLayer(models.Model, PermissionLevelMixin): """Model for Layer in QGIS Server Backend. """ accepted_format = [ 'tif', 'tiff', 'asc', 'shp', 'shx', 'dbf', 'prj', 'qml', 'xml', 'qgs'] geotiff_format = ['tif', 'tiff'] ascii_format = ['asc'] layer = models.OneToOneField( Layer, primary_key=True, related_name='qgis_layer', on_delete=models.CASCADE ) base_layer_path = models.CharField( name='base_layer_path', verbose_name='Base Layer Path', help_text='Location of the base layer.', max_length=2000 ) default_style = models.ForeignKey( 'qgis_server.QGISServerStyle', related_name='layer_default_style', default=None, null=True, on_delete=models.SET_NULL) styles = models.ManyToManyField( 'qgis_server.QGISServerStyle', related_name='layer_styles') @property def files(self): """Returned all files related with this layer. :return: List of related paths :rtype: list(str) """ base_path = self.base_layer_path base_name, __ = os.path.splitext(base_path) extensions_list = list(QGISServerLayer.accepted_format) # QGIS can create a .aux.xml too extensions_list += ['.aux.xml'] found_files = [] for ext in extensions_list: file_path = f'{base_name}.{ext}' if os.path.exists(file_path): found_files.append(file_path) return found_files @property def qgis_layer_path_prefix(self): """Returned QGIS layer path prefix. Example base path: /usr/src/app/geonode/qgis_layer/jakarta_flood.shp Path prefix: /usr/src/app/geonode/qgis_layer/jakarta_flood """ prefix, __ = os.path.splitext(self.base_layer_path) return prefix @property def qgis_layer_name(self): """Returned QGIS Layer name associated with this layer. Example base path: /usr/src/app/geonode/qgis_layer/jakarta_flood.shp QGIS Layer name: jakarta_flood """ return os.path.basename(self.qgis_layer_path_prefix) @property def qgis_project_path(self): """Returned QGIS Project path related with this layer. Example base path: /usr/src/app/geonode/qgis_layer/jakarta_flood.shp QGIS Project path: /usr/src/app/geonode/qgis_layer/jakarta_flood.qgs """ return f'{self.qgis_layer_path_prefix}.qgs' @property def cache_path(self): """Returned the location of tile cache for this layer. Example base path: /usr/src/app/geonode/qgis_layer/jakarta_flood.shp QGIS cache path: /usr/src/app/geonode/qgis_tiles/jakarta_flood :return: Base path of layer cache :rtype: str """ return os.path.join(QGIS_TILES_DIRECTORY, self.qgis_layer_name) @property def qml_path(self): """Returned the location of QML path for this layer (if any). Example base path: /usr/src/app/geonode/qgis_layer/jakarta_flood.shp QGIS QML path: /usr/src/app/geonode/qgis_tiles/jakarta_flood.qml :return: Base path of qml style :rtype: str """ return f'{self.qgis_layer_path_prefix}.qml' def delete_qgis_layer(self): """Delete all files related to this object from disk.""" for file_path in self.files: try: os.remove(file_path) except OSError: pass # Removing the cache. path = self.cache_path logger.debug(f'Removing the cache from a qgis layer : {path}') try: rmtree(path) except OSError: pass # Removing orphaned styles for style in QGISServerStyle.objects.filter(layer_styles=None): style.delete() def get_self_resource(self): """Get associated resource base.""" # Associate this model with resource try: return self.layer.get_self_resource() except Exception: return None class Meta: app_label = "qgis_server" class QGISServerStyle(models.Model, PermissionLevelMixin): """Model wrapper for QGIS Server styles.""" name = models.CharField(_('style name'), max_length=255) title = models.CharField(max_length=255, null=True, blank=True) body = models.TextField(_('style xml'), null=True, blank=True) style_url = models.CharField(_('style url'), null=True, max_length=1000) style_legend_url = models.CharField( _('style legend url'), null=True, max_length=1000) @classmethod def from_get_capabilities_style_xml( cls, qgis_layer, style_xml, style_url=None, synchronize=True): """Convert to this model from GetCapabilities Style tag. :param qgis_layer: Associated QGIS Server Layer :type qgis_layer: QGISServerLayer :param style_xml: xml string or object :type style_xml: str | lxml.etree.Element | xml.etree.ElementTree.Element :param style_url: style information stored as xml :type style_url: str :param synchronize: Flag, if true then synchronize the new value :type synchronize: bool :return: QGISServerStyle model and boolean flag created :rtype: QGISServerStyle, bool """ if isinstance(style_xml, string_types): style_xml = dlxml.fromstring(style_xml) elif isinstance(style_xml, ElementTree.Element): style_xml = dlxml.fromstring( ElementTree.tostring( style_xml, encoding='utf-8', method='xml')) namespaces = { 'wms': 'http://www.opengis.net/wms', 'xlink': 'http://www.w3.org/1999/xlink' } filter_dict = { 'name': style_xml.xpath( 'wms:Name', namespaces=namespaces)[0].text, 'layer_styles': qgis_layer } # if style_body is none, try fetch it from QGIS Server if not style_url: from geonode.qgis_server.helpers import style_get_url style_url = style_get_url( qgis_layer.layer, filter_dict['name'], internal=False) response = requests.get(style_url) style_body = etree.tostring( dlxml.fromstring(ensure_string(response.content)), pretty_print=True) default_dict = { 'title': style_xml.xpath( 'wms:Title', namespaces=namespaces)[0].text, 'style_legend_url': style_xml.xpath( 'wms:LegendURL/wms:OnlineResource', namespaces=namespaces)[0].attrib[ '{http://www.w3.org/1999/xlink}href'], 'style_url': style_url, 'body': style_body } # filter_dict['defaults'] = default_dict # Can't use get_or_create function for some reason. # So use regular query try: style_obj = QGISServerStyle.objects.get(**filter_dict) created = False except QGISServerStyle.DoesNotExist: style_obj = QGISServerStyle(**default_dict) style_obj.name = filter_dict['name'] style_obj.save() created = True if created or synchronize: # Try to synchronize this model with the given parameters style_obj.name = filter_dict['name'] style_obj.style_url = default_dict['style_url'] style_obj.body = default_dict['body'] style_obj.title = default_dict['title'] style_obj.style_legend_url = default_dict['style_legend_url'] style_obj.save() style_obj.layer_styles.add(qgis_layer) style_obj.save() return style_obj, created @property def style_tile_cache_path(self): """Returned the location of tile cache for this layer style. Example base path: /usr/src/app/geonode/qgis_layer/jakarta_flood.shp QGIS cache path: /usr/src/app/geonode/qgis_tiles/jakarta_flood/ default_style :return: Base path of layer cache :rtype: str """ return os.path.join( QGIS_TILES_DIRECTORY, self.layer_styles.first().layer.name, self.name) def get_self_resource(self): """Get associated resource base.""" # Associate this model with resource try: qgis_layer = self.layer_styles.first() """:type: QGISServerLayer""" return qgis_layer.get_self_resource() except Exception: return None class Meta: app_label = "qgis_server" class QGISServerMap(models.Model, PermissionLevelMixin): """Model wrapper for QGIS Server Map.""" map = models.OneToOneField( Map, primary_key=True, name='map', on_delete=models.CASCADE ) map_name_format = 'map_{id}' @property def qgis_map_name(self): """Returned QGIS Map name associated with this layer. based on map_name_format Example QGIS Map name: map_1 """ return self.map_name_format.format(id=self.map.id) @property def qgis_map_path_prefix(self): """Returned QGIS map path prefix. based on map_name_format Path prefix: /usr/src/app/geonode/qgis_layer/map_1 """ return os.path.join(QGIS_LAYER_DIRECTORY, self.qgis_map_name) @property def qgis_project_path(self): """Returned QGIS Project path related with this map. based on map_name_format QGIS Project path: /usr/src/app/geonode/qgis_layer/map_1.qgs """ return f'{self.qgis_map_path_prefix}.qgs' @property def cache_path(self): """Returned the location of tile cache for this layer. based on map_name_format QGIS cache path: /usr/src/app/geonode/qgis_tiles/map_1 :return: Base path of layer cache :rtype: str """ return os.path.join(QGIS_TILES_DIRECTORY, self.qgis_map_name) def get_self_resource(self): """Get associated resource base.""" # Associate this model with resource try: return self.layer.get_self_resource() except Exception: return None class Meta: app_label = "qgis_server"
REANNZ/discovery-service
spec/lib/discovery_service/persistence/entity_cache_spec.rb
# frozen_string_literal: true RSpec.describe DiscoveryService::Persistence::EntityCache do include_context 'build_entity_data' let(:redis) { Redis::Namespace.new(:discovery_service, redis: Redis.new) } let(:instance) { DiscoveryService::Persistence::EntityCache.new } let(:group) { Faker::Lorem.word } describe '#entities(group)' do subject { instance.entities(group) } context 'when entities do not exist for group' do it { is_expected.to be_nil } end context 'when entities exist for group' do let(:entity) { build_entity_data } let(:entities) { to_hash([entity]).to_json } before { redis.set("entities:#{group}", entities) } it 'returns the entities as json string' do expect(subject) .to eq("{\"#{entity[:entity_id]}\":{"\ "\"names\":[{\"value\":\"#{entity[:names].first[:value]}\","\ "\"lang\":\"#{entity[:names].first[:lang]}\"}],"\ "\"tags\":#{entity[:tags].to_json},"\ "\"logos\":[{\"url\":\"#{entity[:logos].first[:url]}\","\ "\"lang\":\"#{entity[:logos].first[:lang]}\"}],"\ "\"domains\":#{entity[:domains]}}}") end end end describe '#entities_as_hash(group)' do subject { instance.entities_as_hash(group) } context 'when entities do not exist for group' do it { is_expected.to be_nil } end context 'when entities exist for group' do let(:entity) { build_entity_data } let(:entities) { to_hash([entity]).to_json } before { redis.set("entities:#{group}", entities) } it 'returns the entities as hash with key as entity id' do expect(subject).to eq(to_hash([entity])) end end end describe '#entities_exist?(group)' do subject { instance.entities(group) } context 'when entities do not exist for group' do it { is_expected.to be_falsey } end context 'when entities exist for group' do let(:entity) { build_entity_data } let(:entities) { to_hash([entity]).to_json } before { redis.set("entities:#{group}", entities) } it { is_expected.to be_truthy } end end describe '#save_entities(entities, group)' do let(:entity) { build_entity_data } subject { instance.save_entities([entity], group) } it { is_expected.to eq('OK') } context 'the stored entity' do before { instance.save_entities([entity], group) } subject { redis.get("entities:#{group}") } it 'is a json string' do expect(subject) .to eq("{\"#{entity[:entity_id]}\":{"\ "\"names\":[{\"value\":\"#{entity[:names].first[:value]}\","\ "\"lang\":\"#{entity[:names].first[:lang]}\"}],"\ "\"tags\":#{entity[:tags].to_json},"\ "\"logos\":[{\"url\":\"#{entity[:logos].first[:url]}\","\ "\"lang\":\"#{entity[:logos].first[:lang]}\"}],"\ "\"domains\":#{entity[:domains]}}}") end end end describe '#group_page(group)' do subject { instance.group_page(group) } context 'when group page does not exist for group' do it { is_expected.to be_nil } end context 'when group page exists for group' do before { redis.set("pages:group:#{group}", 'content') } it 'returns the raw content' do expect(subject).to eq('content') end end end describe '#group_page_exists?(group)' do subject { instance.group_page_exists?(group) } context 'when group page does not exist for group' do it { is_expected.to be_falsey } end context 'when group page exists for group' do before { redis.set("pages:group:#{group}", 'content') } it { is_expected.to be_truthy } end end describe '#save_group_page(group, page)' do let(:content) { 'group page content' } subject { instance.save_group_page(group, content) } it { is_expected.to eq('OK') } context 'the stored page' do before { instance.save_group_page(group, content) } subject { redis.get("pages:group:#{group}") } it { is_expected.to eq(content) } end end describe '#update_expiry(group)' do let(:original_ttl) { 10 } let(:expiry) { 28.days.to_i } let(:entity) { build_entity_data } let(:entities) { to_hash([entity]).to_json } let(:page_content) { 'page content here' } let(:page_key) { "pages:group:#{group}" } let(:entities_key) { "entities:#{group}" } before do redis.set(entities_key, entities) redis.set(page_key, page_content) end it 'updates expiry' do Timecop.freeze do redis.expire(entities_key, original_ttl) redis.expire(page_key, original_ttl) end instance.update_expiry(group) expect(redis.ttl(entities_key)).to(equal(expiry)) expect(redis.ttl(page_key)).to(equal(expiry)) end end describe '#entities_diff(group, entities)' do let(:entity) { build_entity_data } let(:entities_key) { "entities:#{group}" } let(:original_entities) { to_hash([entity]).to_json } before { redis.set(entities_key, original_entities) } let(:updated_names) do [{ value: "#{entity[:names].first[:value]} Version 2", lang: entity[:names].first[:lang] }] end let(:updated_entity) do { entity_id: entity[:entity_id], names: updated_names, tags: entity[:tags], logos: entity[:logos], domains: entity[:domains] } end let(:new_entity) { build_entity_data } let(:updated_entities) { [updated_entity, new_entity] } subject { instance.entities_diff(group, updated_entities) } it 'returns a diff of the updated and new entity' do expect(subject) .to eq([['-', "#{entity[:entity_id]}.names[0]", { value: entity[:names].first[:value], lang: entity[:names].first[:lang] }], ['+', "#{entity[:entity_id]}.names[0]", { value: updated_entity[:names].first[:value], lang: updated_entity[:names].first[:lang] }], ['+', new_entity[:entity_id], { names: new_entity[:names], tags: new_entity[:tags], logos: new_entity[:logos], domains: new_entity[:domains] }]]) end end describe '#default_discovery_response(group, entity_id)' do context 'when entity does not exist' do subject do instance.default_discovery_response(group, Faker::Internet.url) end it { is_expected.to be_nil } end context 'when entity without discovery response exists' do let(:entity) do build_sp_data.except(:discovery_response) end let(:entities) { to_hash([entity]).to_json } before { redis.set("entities:#{group}", entities) } subject { instance.default_discovery_response(group, entity[:entity_id]) } it { is_expected.to be_nil } end context 'when entity with discovery response exists' do let(:entity) { build_sp_data } let(:entities) { to_hash([entity]).to_json } before { redis.set("entities:#{group}", entities) } subject { instance.default_discovery_response(group, entity[:entity_id]) } it 'should eq discovery response' do expect(subject).to eq(entity[:discovery_response]) end end end describe '#all_discovery_response(group, entity_id)' do context 'when entity does not exist' do subject do instance.all_discovery_response(group, Faker::Internet.url) end it { is_expected.to be_nil } end context 'when entity without discovery response exists' do let(:entity) do build_sp_data.except(:discovery_response, :all_discovery_response_endpoints) end let(:entities) { to_hash([entity]).to_json } before { redis.set("entities:#{group}", entities) } subject { instance.all_discovery_response(group, entity[:entity_id]) } it { is_expected.to be_nil } end context 'when entity with discovery response exists' do let(:entity) { build_sp_data } let(:entities) { to_hash([entity]).to_json } before { redis.set("entities:#{group}", entities) } subject { instance.all_discovery_response(group, entity[:entity_id]) } it 'should eq discovery response' do expect(subject).to eq(entity[:all_discovery_response_endpoints]) end end end end
cfsengineering/tigl
src/geometry/CTiglInterpolateLinearWire.h
/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2010-08-13 <NAME> <<EMAIL>> * 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. */ /** * @file * @brief Implementation of routines for building a wire from a std::vector * of points by linear interpolation. */ #ifndef CTIGLINTERPOLATELINEARWIRE_H #define CTIGLINTERPOLATELINEARWIRE_H #include "tigl_internal.h" #include "ITiglWireAlgorithm.h" namespace tigl { class CTiglInterpolateLinearWire : public ITiglWireAlgorithm { public: // Constructor TIGL_EXPORT CTiglInterpolateLinearWire(); // Destructor TIGL_EXPORT ~CTiglInterpolateLinearWire() OVERRIDE; // Builds the wire from the given points TIGL_EXPORT TopoDS_Wire BuildWire(const CPointContainer& points, bool forceClosed = false) const OVERRIDE; // Returns the algorithm code identifier for an algorithm TIGL_EXPORT TiglAlgorithmCode GetAlgorithmCode() const OVERRIDE; // Returns the point on the wire with the smallest x value TIGL_EXPORT gp_Pnt GetPointWithMinX(const CPointContainer& points) const OVERRIDE; // Returns the point on the wire with the biggest x value TIGL_EXPORT gp_Pnt GetPointWithMaxX(const CPointContainer& points) const OVERRIDE; // Returns the point on the wire with the smallest y value TIGL_EXPORT gp_Pnt GetPointWithMinY(const CPointContainer& points) const OVERRIDE; // Returns the point on the wire with the biggest y value TIGL_EXPORT gp_Pnt GetPointWithMaxY(const CPointContainer& points) const OVERRIDE; private: // Copy constructor CTiglInterpolateLinearWire(const CTiglInterpolateLinearWire& ) { /* Do nothing */ } // Assignment operator void operator=(const CTiglInterpolateLinearWire& ) { /* Do nothing */ } }; } // end namespace tigl #endif // CTIGLINTERPOLATELINEARWIRE_H
redwebdew/ovirt-engine
backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/businessentities/Cluster.java
<reponame>redwebdew/ovirt-engine package org.ovirt.engine.core.common.businessentities; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.ovirt.engine.core.common.network.FirewallType; import org.ovirt.engine.core.common.network.SwitchType; import org.ovirt.engine.core.common.scheduling.ClusterPolicy; import org.ovirt.engine.core.common.scheduling.OptimizationType; import org.ovirt.engine.core.common.validation.annotation.ValidI18NName; import org.ovirt.engine.core.common.validation.annotation.ValidSerialNumberPolicy; import org.ovirt.engine.core.common.validation.annotation.ValidUri; import org.ovirt.engine.core.common.validation.group.CreateEntity; import org.ovirt.engine.core.common.validation.group.UpdateEntity; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.Version; @ValidSerialNumberPolicy(groups = {CreateEntity.class, UpdateEntity.class}) public class Cluster implements Queryable, BusinessEntity<Guid>, HasStoragePool, Nameable, Commented, HasSerialNumberPolicy, HasMigrationOptions { private static final long serialVersionUID = -5607824129488532099L; private Guid id; @NotNull(message = "VALIDATION_CLUSTER_NAME_NOT_NULL", groups = { CreateEntity.class, UpdateEntity.class }) @Size(min = 1, max = BusinessEntitiesDefinitions.CLUSTER_NAME_SIZE, message = "VALIDATION_CLUSTER_NAME_MAX", groups = { CreateEntity.class, UpdateEntity.class }) @ValidI18NName(message = "VALIDATION_CLUSTER_NAME_INVALID", groups = { CreateEntity.class, UpdateEntity.class }) private String name; @Size(max = BusinessEntitiesDefinitions.GENERAL_MAX_SIZE) @NotNull private String description; @NotNull private String comment; @Size(max = BusinessEntitiesDefinitions.CLUSTER_CPU_NAME_SIZE) private String cpuName; private String cpuFlags; private String cpuVerb; private String configuredCpuVerb; private Guid storagePoolId; @Size(max = BusinessEntitiesDefinitions.DATACENTER_NAME_SIZE) private String storagePoolName; private int maxVdsMemoryOverCommit; private boolean enableBallooning; private boolean enableKsm; private boolean countThreadsAsCores; private boolean upgradeRunning; private boolean smtDisabled; @Size(max = BusinessEntitiesDefinitions.GENERAL_VERSION_SIZE) private String compatibilityVersion; private Version compatVersion; private boolean transparentHugepages; private MigrateOnErrorOptions migrateOnError; private boolean virtService; private boolean glusterService; private boolean glusterCliBasedSchedulingOn; private boolean tunnelMigration; private String emulatedMachine; private BiosType biosType; private boolean trustedService; private boolean haReservation; private boolean hasHostWithMissingCpuFlags; private Guid clusterPolicyId; private String clusterPolicyName; private Set<SupportedAdditionalClusterFeature> addtionalFeaturesSupported; private Integer logMaxMemoryUsedThreshold; private LogMaxMemoryUsedThresholdType logMaxMemoryUsedThresholdType; /** * Currently we want all networks of sole cluster to have same switch type. */ private SwitchType requiredSwitchTypeForCluster; @ValidUri(message = "VALIDATION_CLUSTER_SPICE_PROXY_HOSTNAME_OR_IP", groups = { CreateEntity.class, UpdateEntity.class }) @Size(max = BusinessEntitiesDefinitions.SPICE_PROXY_ADDR_SIZE) private String spiceProxy; private Map<String, String> clusterPolicyProperties; private boolean detectEmulatedMachine; private ArchitectureType architecture; private OptimizationType optimizationType; private SerialNumberPolicy serialNumberPolicy; private ClusterHostsAndVMs clusterHostsAndVms; @Size(max = BusinessEntitiesDefinitions.VM_SERIAL_NUMBER_SIZE) private String customSerialNumber; /** * Set of rng sources that are required in addition to mandatory {@link VmRngDevice.Source.RANDOM} * or {@link VmRngDevice.Source.URANDOM}. */ private Set<VmRngDevice.Source> additionalRngSources; private FencingPolicy fencingPolicy; private Boolean autoConverge; private Boolean migrateCompressed; private Boolean migrateEncrypted; private String glusterTunedProfile; private boolean ksmMergeAcrossNumaNodes; private boolean clusterCompatibilityLevelUpgradeNeeded; private FirewallType firewallType; private boolean vncEncryptionEnabled; /** * How max sum of bandwidths of both outgoing and incoming migrations on one host are limited */ @NotNull private MigrationBandwidthLimitType migrationBandwidthLimitType; /** * Maximum of sum of bandwidths of both outgoing and incoming migrations on one host. <br/> * Relevant only if {@link #migrationBandwidthLimitType} is {@link MigrationBandwidthLimitType#CUSTOM}. * In that case, it may not be null. <br/> * Unit: Mbps */ @Min(1) private Integer customMigrationNetworkBandwidth; private Guid migrationPolicyId; private Guid macPoolId; private Guid defaultNetworkProviderId; private String hostNamesOutOfSync; private boolean managed; public Cluster() { migrateOnError = MigrateOnErrorOptions.YES; name = ""; virtService = true; optimizationType = OptimizationType.NONE; additionalRngSources = new HashSet<>(); fencingPolicy = new FencingPolicy(); addtionalFeaturesSupported = new HashSet<>(); enableKsm = true; ksmMergeAcrossNumaNodes = true; migrationBandwidthLimitType = MigrationBandwidthLimitType.DEFAULT; requiredSwitchTypeForCluster = SwitchType.LEGACY; logMaxMemoryUsedThresholdType = LogMaxMemoryUsedThresholdType.PERCENTAGE; description = ""; comment = ""; cpuName = ""; vncEncryptionEnabled = true; hostNamesOutOfSync = ""; managed = true; enableBallooning = true; } @Override public Guid getId() { return id; } @Override public void setId(Guid value) { id = value; } public void setClusterId(Guid value) { setId(value); } @Override public String getName() { return name; } public void setName(String value) { name = value; } public String getDescription() { return description; } public void setDescription(String value) { description = value == null ? "" : value; } @Override public String getComment() { return comment; } @Override public void setComment(String value) { comment = value == null ? "" : value; } public String getCpuName() { return cpuName; } public void setCpuName(String value) { cpuName = value; } public String getCpuFlags() { return cpuFlags; } public void setCpuFlags(String cpuFlags) { this.cpuFlags = cpuFlags; } public String getCpuVerb() { return cpuVerb; } public void setCpuVerb(String cpuVerb) { this.cpuVerb = cpuVerb; } public String getConfiguredCpuVerb() { return configuredCpuVerb; } public void setConfiguredCpuVerb(String configuredCpuVerb) { this.configuredCpuVerb = configuredCpuVerb; } @Override public Guid getStoragePoolId() { return storagePoolId; } @Override public void setStoragePoolId(Guid storagePoolId) { this.storagePoolId = storagePoolId; } public String getStoragePoolName() { return storagePoolName; } public void setStoragePoolName(String value) { storagePoolName = value; } public int getMaxVdsMemoryOverCommit() { return maxVdsMemoryOverCommit; } public void setMaxVdsMemoryOverCommit(int value) { maxVdsMemoryOverCommit = value; } public boolean getCountThreadsAsCores() { return countThreadsAsCores; } public void setCountThreadsAsCores(boolean value) { countThreadsAsCores = value; } public boolean isUpgradeRunning() { return upgradeRunning; } /** * Sets the readonly cluster upgrade running flag. This is not saved to the database when updating or saving the * cluster to the database. * * @param upgradeRunning the flag indicating if the cluster upgrade is running. */ public void setUpgradeRunning(boolean upgradeRunning) { this.upgradeRunning = upgradeRunning; } public boolean getSmtDisabled() { return smtDisabled; } public void setSmtDisabled(boolean smtDisabled) { this.smtDisabled = smtDisabled; } public Version getCompatibilityVersion() { return compatVersion; } public void setCompatibilityVersion(Version value) { compatibilityVersion = value.getValue(); compatVersion = value; } public boolean getTransparentHugepages() { return transparentHugepages; } public void setTransparentHugepages(boolean value) { transparentHugepages = value; } @Override public Object getQueryableId() { return getId(); } public void setMigrateOnError(MigrateOnErrorOptions migrateOnError) { this.migrateOnError = migrateOnError; } public MigrateOnErrorOptions getMigrateOnError() { return migrateOnError; } public void setVirtService(boolean virtService) { this.virtService = virtService; } public boolean supportsVirtService() { return virtService; } public void setGlusterService(boolean glusterService) { this.glusterService = glusterService; } public boolean supportsGlusterService() { return glusterService; } public void setGlusterCliBasedSchedulingOn(boolean glusterCliBasedSchedulingOn) { this.glusterCliBasedSchedulingOn = glusterCliBasedSchedulingOn; } public boolean isGlusterCliBasedSchedulingOn() { return this.glusterCliBasedSchedulingOn; } public boolean isTunnelMigration() { return tunnelMigration; } public void setTunnelMigration(boolean value) { tunnelMigration = value; } public String getEmulatedMachine() { return emulatedMachine; } public void setEmulatedMachine(String emulatedMachine) { this.emulatedMachine = emulatedMachine; } public BiosType getBiosType() { return biosType; } public void setBiosType(BiosType biosType) { this.biosType = biosType; } public void setTrustedService(boolean trustedService) { this.trustedService = trustedService; } public boolean supportsTrustedService() { return trustedService; } public boolean supportsHaReservation() { return haReservation; } public void setHaReservation(boolean haReservation) { this.haReservation = haReservation; } public boolean hasHostWithMissingCpuFlags() { return hasHostWithMissingCpuFlags; } public void setHasHostWithMissingCpuFlags(boolean hasHostWithMissingCpuFlags) { this.hasHostWithMissingCpuFlags = hasHostWithMissingCpuFlags; } public boolean isInUpgradeMode(){ return ClusterPolicy.UPGRADE_POLICY_GUID.equals(clusterPolicyId); } public Guid getClusterPolicyId() { return clusterPolicyId; } public void setClusterPolicyId(Guid clusterPolicyId) { this.clusterPolicyId = clusterPolicyId; } public String getClusterPolicyName() { return clusterPolicyName; } public void setClusterPolicyName(String clusterPolicyName) { this.clusterPolicyName = clusterPolicyName; } public Map<String, String> getClusterPolicyProperties() { return clusterPolicyProperties; } public void setClusterPolicyProperties(Map<String, String> clusterPolicyProperties) { this.clusterPolicyProperties = clusterPolicyProperties; } public boolean isEnableKsm() { return enableKsm; } public void setEnableKsm(boolean enableKsm) { this.enableKsm = enableKsm; } public boolean isEnableBallooning() { return enableBallooning; } public void setEnableBallooning(boolean enableBallooning) { this.enableBallooning = enableBallooning; } public void setDetectEmulatedMachine(boolean detectEmulatedMachine) { this.detectEmulatedMachine = detectEmulatedMachine; } public boolean isDetectEmulatedMachine() { return detectEmulatedMachine; } public ArchitectureType getArchitecture() { return architecture; } public void setArchitecture (ArchitectureType architecture) { this.architecture = architecture; } public OptimizationType getOptimizationType() { return optimizationType; } public void setOptimizationType(OptimizationType optimizationType) { this.optimizationType = optimizationType; } public String getSpiceProxy() { return spiceProxy; } public void setSpiceProxy(String spiceProxy) { this.spiceProxy = spiceProxy; } @Override public String getCustomSerialNumber() { return customSerialNumber; } @Override public void setCustomSerialNumber(String customSerialNumber) { this.customSerialNumber = customSerialNumber; } @Override public SerialNumberPolicy getSerialNumberPolicy() { return serialNumberPolicy; } @Override public void setSerialNumberPolicy(SerialNumberPolicy serialNumberPolicy) { this.serialNumberPolicy = serialNumberPolicy; } public Set<VmRngDevice.Source> getAdditionalRngSources() { return additionalRngSources; } public void setAdditionalRngSources(Set<VmRngDevice.Source> additionalRngSources) { this.additionalRngSources = additionalRngSources; } /** * @return Set of required rng sources. */ public Set<VmRngDevice.Source> getRequiredRngSources() { final Set<VmRngDevice.Source> requiredRngSources = new HashSet<>(getAdditionalRngSources()); requiredRngSources.add(VmRngDevice.Source.getUrandomOrRandomFor(getCompatibilityVersion())); return Collections.unmodifiableSet(requiredRngSources); } public FencingPolicy getFencingPolicy() { return fencingPolicy; } public void setFencingPolicy(FencingPolicy fencingPolicy) { this.fencingPolicy = fencingPolicy; } public Boolean getAutoConverge() { return autoConverge; } public void setAutoConverge(Boolean autoConverge) { this.autoConverge = autoConverge; } public Boolean getMigrateCompressed() { return migrateCompressed; } public void setMigrateCompressed(Boolean migrateCompressed) { this.migrateCompressed = migrateCompressed; } public Boolean getMigrateEncrypted() { return migrateEncrypted; } public void setMigrateEncrypted(Boolean migrateEncrypted) { this.migrateEncrypted = migrateEncrypted; } public ClusterHostsAndVMs getClusterHostsAndVms() { return clusterHostsAndVms; } public void setClusterHostsAndVms(ClusterHostsAndVMs clusterHostsAndVms) { this.clusterHostsAndVms = clusterHostsAndVms; } public String getGlusterTunedProfile() { return glusterTunedProfile; } public void setGlusterTunedProfile(String glusterTunedProfile) { this.glusterTunedProfile = glusterTunedProfile; } public Set<SupportedAdditionalClusterFeature> getAddtionalFeaturesSupported() { return addtionalFeaturesSupported; } public void setAddtionalFeaturesSupported(Set<SupportedAdditionalClusterFeature> addtionalFeaturesSupported) { this.addtionalFeaturesSupported = addtionalFeaturesSupported; } public boolean isKsmMergeAcrossNumaNodes() { return ksmMergeAcrossNumaNodes; } public void setKsmMergeAcrossNumaNodes(boolean ksmMergeAcrossNumaNodes) { this.ksmMergeAcrossNumaNodes = ksmMergeAcrossNumaNodes; } public Integer getCustomMigrationNetworkBandwidth() { return customMigrationNetworkBandwidth; } public void setCustomMigrationNetworkBandwidth(Integer customMigrationNetworkBandwidth) { this.customMigrationNetworkBandwidth = customMigrationNetworkBandwidth; } public MigrationBandwidthLimitType getMigrationBandwidthLimitType() { return migrationBandwidthLimitType; } public void setMigrationBandwidthLimitType(MigrationBandwidthLimitType migrationBandwidthLimitType) { this.migrationBandwidthLimitType = migrationBandwidthLimitType; } public Guid getMigrationPolicyId() { return migrationPolicyId; } public void setMigrationPolicyId(Guid migrationPolicyId) { this.migrationPolicyId = migrationPolicyId; } public Guid getMacPoolId() { return macPoolId; } public void setMacPoolId(Guid macPoolId) { this.macPoolId = macPoolId; } public SwitchType getRequiredSwitchTypeForCluster() { return requiredSwitchTypeForCluster; } public void setRequiredSwitchTypeForCluster(SwitchType requiredSwitchTypeForCluster) { this.requiredSwitchTypeForCluster = requiredSwitchTypeForCluster; } public boolean isClusterCompatibilityLevelUpgradeNeeded() { return clusterCompatibilityLevelUpgradeNeeded; } public void setClusterCompatibilityLevelUpgradeNeeded(boolean clusterCompatibilityLevelUpgradeNeeded) { this.clusterCompatibilityLevelUpgradeNeeded = clusterCompatibilityLevelUpgradeNeeded; } public FirewallType getFirewallType() { return firewallType; } public void setFirewallType(FirewallType firewallType) { this.firewallType = firewallType; } public Guid getDefaultNetworkProviderId() { return defaultNetworkProviderId; } public void setDefaultNetworkProviderId(Guid defaultNetworkProviderId) { this.defaultNetworkProviderId = defaultNetworkProviderId; } public boolean isSetRequiredSwitchType() { return requiredSwitchTypeForCluster != null; } public boolean hasRequiredSwitchType(SwitchType switchType) { return Objects.equals(getRequiredSwitchTypeForCluster(), switchType); } public boolean isSetDefaultNetworkProviderId() { return defaultNetworkProviderId != null; } public boolean hasDefaultNetworkProviderId(Guid providerId) { return Objects.equals(getDefaultNetworkProviderId(), providerId); } public Integer getLogMaxMemoryUsedThreshold() { return logMaxMemoryUsedThreshold; } public void setLogMaxMemoryUsedThreshold(Integer logMaxMemoryUsedThreshold) { this.logMaxMemoryUsedThreshold = logMaxMemoryUsedThreshold; } public LogMaxMemoryUsedThresholdType getLogMaxMemoryUsedThresholdType() { return logMaxMemoryUsedThresholdType; } public void setLogMaxMemoryUsedThresholdType(LogMaxMemoryUsedThresholdType logMaxMemoryUsedThresholdType) { this.logMaxMemoryUsedThresholdType = logMaxMemoryUsedThresholdType; } public boolean isVncEncryptionEnabled() { return vncEncryptionEnabled; } public void setVncEncryptionEnabled(boolean vncEncryptionEnabled) { this.vncEncryptionEnabled = vncEncryptionEnabled; } public String getHostNamesOutOfSync() { return hostNamesOutOfSync; } public void setHostNamesOutOfSync(String hostNamesOutOfSync) { this.hostNamesOutOfSync = hostNamesOutOfSync; } @Override public boolean isManaged() { return managed; } public void setManaged(boolean managed) { this.managed = managed; } @Override public int hashCode() { return Objects.hash( id, compatVersion, compatibilityVersion, cpuName, cpuFlags, cpuVerb, description, maxVdsMemoryOverCommit, countThreadsAsCores, migrateOnError, name, storagePoolId, storagePoolName, requiredSwitchTypeForCluster, transparentHugepages, virtService, glusterService, glusterCliBasedSchedulingOn, tunnelMigration, emulatedMachine, biosType, trustedService, haReservation, hasHostWithMissingCpuFlags, clusterPolicyName, clusterPolicyProperties, additionalRngSources, enableKsm, enableBallooning, optimizationType, serialNumberPolicy, customSerialNumber, clusterHostsAndVms, fencingPolicy, autoConverge, migrateCompressed, migrateEncrypted, glusterTunedProfile, addtionalFeaturesSupported, ksmMergeAcrossNumaNodes, customMigrationNetworkBandwidth, migrationBandwidthLimitType, migrationPolicyId, macPoolId, firewallType, defaultNetworkProviderId, logMaxMemoryUsedThreshold, logMaxMemoryUsedThresholdType, vncEncryptionEnabled, hostNamesOutOfSync, managed ); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Cluster)) { return false; } Cluster other = (Cluster) obj; // *ATTENTION* when adding fields to this, please make sure that equals still works, if not this will // cause all kinds of havoc in the UI when clusters are refreshed. return Objects.equals(id, other.id) && Objects.equals(compatVersion, other.compatVersion) && Objects.equals(compatibilityVersion, other.compatibilityVersion) && Objects.equals(cpuName, other.cpuName) && Objects.equals(cpuFlags, other.cpuFlags) && Objects.equals(cpuVerb, other.cpuVerb) && Objects.equals(description, other.description) && maxVdsMemoryOverCommit == other.maxVdsMemoryOverCommit && countThreadsAsCores == other.countThreadsAsCores && migrateOnError == other.migrateOnError && Objects.equals(name, other.name) && Objects.equals(storagePoolId, other.storagePoolId) && Objects.equals(storagePoolName, other.storagePoolName) && Objects.equals(requiredSwitchTypeForCluster, other.requiredSwitchTypeForCluster) && transparentHugepages == other.transparentHugepages && virtService == other.virtService && glusterService == other.glusterService && glusterCliBasedSchedulingOn == other.glusterCliBasedSchedulingOn && tunnelMigration == other.tunnelMigration && Objects.equals(emulatedMachine, other.emulatedMachine) && biosType == other.biosType && trustedService == other.trustedService && haReservation == other.haReservation && hasHostWithMissingCpuFlags == other.hasHostWithMissingCpuFlags && Objects.equals(clusterPolicyId, other.clusterPolicyId) && Objects.equals(clusterPolicyName, other.clusterPolicyName) && Objects.equals(clusterPolicyProperties, other.clusterPolicyProperties) && enableKsm == other.enableKsm && enableBallooning == other.enableBallooning && detectEmulatedMachine == other.detectEmulatedMachine && optimizationType == other.optimizationType && serialNumberPolicy == other.serialNumberPolicy && Objects.equals(customSerialNumber, other.customSerialNumber) && Objects.equals(clusterHostsAndVms, other.clusterHostsAndVms) && Objects.equals(additionalRngSources, other.additionalRngSources) && Objects.equals(fencingPolicy, other.fencingPolicy) && Objects.equals(autoConverge, other.autoConverge) && Objects.equals(migrateCompressed, other.migrateCompressed) && Objects.equals(migrateEncrypted, other.migrateEncrypted) && Objects.equals(glusterTunedProfile, other.glusterTunedProfile) && Objects.equals(addtionalFeaturesSupported, other.addtionalFeaturesSupported) && ksmMergeAcrossNumaNodes == other.ksmMergeAcrossNumaNodes && Objects.equals(customMigrationNetworkBandwidth, other.customMigrationNetworkBandwidth) && Objects.equals(migrationBandwidthLimitType, other.migrationBandwidthLimitType) && Objects.equals(migrationPolicyId, other.migrationPolicyId) && Objects.equals(macPoolId, other.macPoolId) && Objects.equals(firewallType, other.firewallType) && Objects.equals(defaultNetworkProviderId, other.defaultNetworkProviderId) && Objects.equals(logMaxMemoryUsedThreshold, other.logMaxMemoryUsedThreshold) && logMaxMemoryUsedThresholdType == other.logMaxMemoryUsedThresholdType && vncEncryptionEnabled == other.vncEncryptionEnabled && Objects.equals(hostNamesOutOfSync, other.hostNamesOutOfSync) && managed == other.managed; } @Override public String toString() { return "Cluster [" + name + "]"; } }
vidkidz/crossbridge
gnustep/core/gui/Headers/AppKit/NSColorPanel.h
/* NSColorPanel.h System generic color panel Copyright (C) 1996 Free Software Foundation, Inc. Author: <NAME> <<EMAIL>> Date: 1996 This file is part of the GNUstep GUI Library. 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 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; see the file COPYING.LIB. If not, see <http://www.gnu.org/licenses/> or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _GNUstep_H_NSColorPanel #define _GNUstep_H_NSColorPanel #import <GNUstepBase/GSVersionMacros.h> #import <AppKit/AppKitDefines.h> #import <AppKit/NSApplication.h> #import <AppKit/NSColorPicking.h> #import <AppKit/NSColorWell.h> #import <AppKit/NSNibDeclarations.h> #import <AppKit/NSPanel.h> @class NSBox; @class NSButton; @class NSColorList; @class NSEvent; @class NSMatrix; @class NSSlider; @class NSSplitView; @class NSView; enum { NSGrayModeColorPanel, NSRGBModeColorPanel, NSCMYKModeColorPanel, NSHSBModeColorPanel, NSCustomPaletteModeColorPanel, NSColorListModeColorPanel, NSWheelModeColorPanel, NSCrayonModeColorPanel }; enum { NSColorPanelGrayModeMask = 1, NSColorPanelRGBModeMask = 2, NSColorPanelCMYKModeMask = 4, NSColorPanelHSBModeMask = 8, NSColorPanelCustomPaletteModeMask = 16, NSColorPanelColorListModeMask = 32, NSColorPanelWheelModeMask = 64, NSColorPanelCrayonModeMask = 128, NSColorPanelAllModesMask = 255 }; @interface NSApplication (NSColorPanel) - (void) orderFrontColorPanel: (id)sender; @end @interface NSColorPanel : NSPanel { // Attributes NSView *_topView; NSColorWell *_colorWell; NSButton *_magnifyButton; NSMatrix *_pickerMatrix; NSBox *_pickerBox; NSSlider *_alphaSlider; NSSplitView *_splitView; NSView *_accessoryView; //NSMatrix *_swatches; NSMutableArray *_pickers; id<NSColorPickingCustom,NSColorPickingDefault> _currentPicker; id _target; SEL _action; BOOL _isContinuous; BOOL _showsAlpha; } // // Creating the NSColorPanel // + (NSColorPanel *)sharedColorPanel; + (BOOL)sharedColorPanelExists; // // Setting the NSColorPanel // + (void)setPickerMask:(int)mask; + (void)setPickerMode:(int)mode; - (NSView *)accessoryView; - (BOOL)isContinuous; - (int)mode; - (void)setAccessoryView:(NSView *)aView; - (void)setAction:(SEL)aSelector; - (void)setContinuous:(BOOL)flag; - (void)setMode:(int)mode; - (void)setShowsAlpha:(BOOL)flag; - (void)setTarget:(id)anObject; - (BOOL)showsAlpha; // // Attaching a Color List // - (void)attachColorList:(NSColorList *)aColorList; - (void)detachColorList:(NSColorList *)aColorList; // // Setting Color // + (BOOL)dragColor:(NSColor *)aColor withEvent:(NSEvent *)anEvent fromView:(NSView *)sourceView; - (void)setColor:(NSColor *)aColor; - (float)alpha; - (NSColor *)color; @end /* Notifications */ APPKIT_EXPORT NSString *NSColorPanelColorDidChangeNotification; #endif // _GNUstep_H_NSColorPanel
konexios/moonstone
selene-device-zigbee/src/main/java/moonstone/selene/device/xbee/XbeeSensorModule.java
package moonstone.selene.device.xbee; import java.time.Instant; import com.digi.xbee.api.RemoteXBeeDevice; import com.digi.xbee.api.XBeeDevice; import com.digi.xbee.api.XBeeNetwork; import com.digi.xbee.api.io.IOLine; import com.digi.xbee.api.io.IOSample; import com.digi.xbee.api.listeners.IIOSampleReceiveListener; import moonstone.selene.SeleneException; import moonstone.selene.engine.DeviceModuleAbstract; import moonstone.selene.engine.Utils; public class XbeeSensorModule extends DeviceModuleAbstract<XbeeSensorInfo, XbeeSensorProperties, XbeeSensorStates, XbeeSensorData> { private XBeeDevice device; private Thread discoveryThread; private Receiver receiver; @Override protected void startDevice() { super.startDevice(); String method = "sendCommand"; try { logInfo(method, "opening xbee %s : %d", getInfo().getPort(), getInfo().getBaudRate()); device = new XBeeDevice(getInfo().getPort(), getInfo().getBaudRate()); device.open(); logInfo(method, "xbee port opened!"); receiver = new Receiver(); device.addIOSampleListener(receiver); logInfo(method, "added receiver to xbee coordinator"); discoveryThread = new Thread(receiver, "discoveryThread"); logInfo(method, "starting discovery thread ..."); discoveryThread.start(); logInfo(method, "started"); } catch (Exception e) { throw new SeleneException("unable to start xbee device", e); } } @Override public void stop() { super.stop(); String method = "stop"; moonstone.acn.client.utils.Utils.shutdownThread(discoveryThread); if (device != null) { logInfo(method, "closing device ..."); device.close(); } } @Override protected XbeeSensorProperties createProperties() { return new XbeeSensorProperties(); } @Override protected XbeeSensorInfo createInfo() { return new XbeeSensorInfo(); } @Override protected XbeeSensorStates createStates() { return new XbeeSensorStates(); } private class Receiver implements IIOSampleReceiveListener, Runnable { private boolean deviceFound = false; private long lastReceived = 0; @Override public void run() { String method = "run"; XBeeNetwork network = device.getNetwork(); deviceFound = false; int monitorInterval = getProperties().getPollingInterval() * 3; while (!isShuttingDown()) { if (deviceFound) { if (Instant.now().toEpochMilli() - lastReceived > monitorInterval) { logInfo(method, "no data has been received recently, let's search for it ..."); deviceFound = false; } } if (!deviceFound) { try { logInfo(method, "searching for remote sensor %s", getInfo().getNodeId()); RemoteXBeeDevice remote = network.discoverDevice(getInfo().getNodeId()); if (remote != null) { logInfo(method, "found remote sensor: %s / %s", remote.getNodeID(), remote.get64BitAddress().toString()); remote.setDestinationAddress(device.get64BitAddress()); remote.setIOSamplingRate(getProperties().getPollingInterval()); deviceFound = true; } } catch (Exception e) { logError(method, "error connecting to remote sensor", e); } } if (!deviceFound) { logError(method, "remote sensor not found, retrying in %d ms", getProperties().getRetryInterval()); try { Thread.sleep(getProperties().getRetryInterval()); } catch (Exception x) { } } else { logError(method, "remote sensor connected, re-checking in %d ms", monitorInterval); try { Thread.sleep(monitorInterval); } catch (Exception x) { } } } logInfo(method, "complete"); } @Override public void ioSampleReceived(RemoteXBeeDevice remoteDevice, IOSample ioSample) { String method = "ioSampleReceived"; lastReceived = Instant.now().toEpochMilli(); try { int a1 = ioSample.getAnalogValue(IOLine.DIO1_AD1); int a2 = ioSample.getAnalogValue(IOLine.DIO2_AD2); int a3 = ioSample.getAnalogValue(IOLine.DIO3_AD3); double mv = a2 / 1023.0 * 1200.0; double temperature = Utils.celsiusToFahrenheit((mv - 500.0) / 10.0); mv = a3 / 1023.0 * 1200.0; double humidity = (mv * 108.2 / 33.2 / 5000 - 0.16) / 0.0062; double brightness = a1 / 1023.0 * 1200.0; logInfo(method, "received: %.2f / %.2f / %.2f", temperature, humidity, brightness); queueDataForSending(new XbeeSensorDataImpl(temperature, humidity, brightness)); } catch (Exception e) { logError(method, "Error processing sample data from remote sensor", e); } } } }
rigarash/monolish-debian-package
src/vml/matrix/math_2op/matsinh.hpp
#pragma once namespace monolish { namespace { template <typename F1, typename F2> void msinh_core(const F1 &A, F2 &C) { Logger &logger = Logger::get_instance(); logger.func_in(monolish_func); // err assert(util::is_same_size(A, C)); assert(util::is_same_structure(A, C)); assert(util::is_same_device_mem_stat(A, C)); internal::vsinh(A.get_nnz(), A.val.data(), C.val.data(), A.get_device_mem_stat()); logger.func_out(); } } // namespace } // namespace monolish
stefanlechner/rtfparserkit
src/main/java/com/rtfparserkit/parser/standard/FontCharset.java
/* * Copyright 2013 <NAME> * * 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.rtfparserkit.parser.standard; /** * Represents font character sets which may be encountered in an RTF file. */ class FontCharset { /** * Convert a font character set to an encoding name. */ public static String getCharset(int parameter) { String result = null; if (parameter >= 0 && parameter < MAPPING.length) { result = MAPPING[parameter]; } return result; } private static final String[] MAPPING = new String[256]; static { MAPPING[0] = "1252"; // ANSI MAPPING[1] = null; // Default MAPPING[2] = "1252"; // Symbol - according to the specs this is codepage 42 "Symbol". What's the Java equivalent? 1252 seems to work... MAPPING[77] = "10000"; // Mac Roman MAPPING[78] = "10001"; // Mac Shift Jis MAPPING[79] = "10003"; // Mac Hangul MAPPING[80] = "10008"; // Mac GB2312 MAPPING[81] = "10002"; // Mac Big5 MAPPING[82] = null; // Mac Johab (old) MAPPING[83] = "10005"; // Mac Hebrew MAPPING[84] = "10004"; // Mac Arabic MAPPING[85] = "10006"; // Mac Greek MAPPING[86] = "10081"; // Mac Turkish MAPPING[87] = "10021"; // Mac Thai MAPPING[88] = "10029"; // Mac East Europe MAPPING[89] = "10007"; // Mac Russian MAPPING[128] = "932"; // Shift JIS MAPPING[129] = "949"; // Hangul MAPPING[130] = "1361"; // Johab MAPPING[134] = "936"; // GB2312 MAPPING[136] = "950"; // Big5 MAPPING[161] = "1253"; // Greek MAPPING[162] = "1254"; // Turkish MAPPING[163] = "1258"; // Vietnamese MAPPING[177] = "1255"; // Hebrew MAPPING[178] = "1256"; // Arabic MAPPING[179] = null; // Arabic Traditional (old) MAPPING[180] = null; // Arabic user (old) MAPPING[181] = null; // Hebrew user (old) MAPPING[186] = "1257"; // Baltic MAPPING[204] = "1251"; // Russian MAPPING[222] = "874"; // Thai MAPPING[238] = "1250"; // Eastern European MAPPING[254] = "437"; // PC 437 MAPPING[255] = "850"; // OEM } }
T-Terra/Exercises-of-Python
world challenges 2/df43.py
<gh_stars>0 altura = float(input('Qual é sua altura? (m) ')) peso = float(input('Qual é seu peso? (kg) ')) imc = peso / (altura ** 2) if imc <= 18.5: print('Seu imc é de {:.1f} você está \033[31mabaixo do peso!!!'.format(imc)) elif imc <= 25: print('Seu imc é {:.1f} e você está no \033[33mPeso ideal!!!'.format(imc)) elif imc < 30: print('Seu imc é de {:.1f} e você está com \033[31mSOBREPESO!!!'.format(imc)) elif imc < 40: print('Seu imc é de {:.1f} e você está com \033[31mOBESIDADE!!'.format(imc)) elif imc >= 40: print('Seu imc é de {:.1f} e você está com \033[31mOBESIDADE MÓRBIDA!!!'.format(imc))
softwarecapital/google.pdfium
core/fxcrt/css/cfx_csscomputedstyle.cpp
// Copyright 2017 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "core/fxcrt/css/cfx_csscomputedstyle.h" #include "core/fxcrt/css/cfx_cssstringvalue.h" #include "core/fxcrt/css/cfx_cssvaluelist.h" #include "third_party/base/containers/adapters.h" CFX_CSSComputedStyle::CFX_CSSComputedStyle() = default; CFX_CSSComputedStyle::~CFX_CSSComputedStyle() = default; bool CFX_CSSComputedStyle::GetCustomStyle(const WideString& wsName, WideString* pValue) const { for (const auto& prop : pdfium::base::Reversed(m_CustomProperties)) { if (wsName == prop.name()) { *pValue = prop.value(); return true; } } return false; } Optional<WideString> CFX_CSSComputedStyle::GetLastFontFamily() const { if (!m_InheritedData.m_pFontFamily || m_InheritedData.m_pFontFamily->values().empty()) { return pdfium::nullopt; } return m_InheritedData.m_pFontFamily->values() .back() .As<CFX_CSSStringValue>() ->Value(); } uint16_t CFX_CSSComputedStyle::GetFontWeight() const { return m_InheritedData.m_wFontWeight; } CFX_CSSFontVariant CFX_CSSComputedStyle::GetFontVariant() const { return m_InheritedData.m_eFontVariant; } CFX_CSSFontStyle CFX_CSSComputedStyle::GetFontStyle() const { return m_InheritedData.m_eFontStyle; } float CFX_CSSComputedStyle::GetFontSize() const { return m_InheritedData.m_fFontSize; } FX_ARGB CFX_CSSComputedStyle::GetColor() const { return m_InheritedData.m_dwFontColor; } void CFX_CSSComputedStyle::SetFontWeight(uint16_t wFontWeight) { m_InheritedData.m_wFontWeight = wFontWeight; } void CFX_CSSComputedStyle::SetFontVariant(CFX_CSSFontVariant eFontVariant) { m_InheritedData.m_eFontVariant = eFontVariant; } void CFX_CSSComputedStyle::SetFontStyle(CFX_CSSFontStyle eFontStyle) { m_InheritedData.m_eFontStyle = eFontStyle; } void CFX_CSSComputedStyle::SetFontSize(float fFontSize) { m_InheritedData.m_fFontSize = fFontSize; } void CFX_CSSComputedStyle::SetColor(FX_ARGB dwFontColor) { m_InheritedData.m_dwFontColor = dwFontColor; } const CFX_CSSRect* CFX_CSSComputedStyle::GetBorderWidth() const { return m_NonInheritedData.m_bHasBorder ? &(m_NonInheritedData.m_BorderWidth) : nullptr; } const CFX_CSSRect* CFX_CSSComputedStyle::GetMarginWidth() const { return m_NonInheritedData.m_bHasMargin ? &(m_NonInheritedData.m_MarginWidth) : nullptr; } const CFX_CSSRect* CFX_CSSComputedStyle::GetPaddingWidth() const { return m_NonInheritedData.m_bHasPadding ? &(m_NonInheritedData.m_PaddingWidth) : nullptr; } void CFX_CSSComputedStyle::SetMarginWidth(const CFX_CSSRect& rect) { m_NonInheritedData.m_MarginWidth = rect; m_NonInheritedData.m_bHasMargin = true; } void CFX_CSSComputedStyle::SetPaddingWidth(const CFX_CSSRect& rect) { m_NonInheritedData.m_PaddingWidth = rect; m_NonInheritedData.m_bHasPadding = true; } CFX_CSSDisplay CFX_CSSComputedStyle::GetDisplay() const { return m_NonInheritedData.m_eDisplay; } float CFX_CSSComputedStyle::GetLineHeight() const { return m_InheritedData.m_fLineHeight; } const CFX_CSSLength& CFX_CSSComputedStyle::GetTextIndent() const { return m_InheritedData.m_TextIndent; } CFX_CSSTextAlign CFX_CSSComputedStyle::GetTextAlign() const { return m_InheritedData.m_eTextAlign; } CFX_CSSVerticalAlign CFX_CSSComputedStyle::GetVerticalAlign() const { return m_NonInheritedData.m_eVerticalAlignType; } float CFX_CSSComputedStyle::GetNumberVerticalAlign() const { return m_NonInheritedData.m_fVerticalAlign; } uint32_t CFX_CSSComputedStyle::GetTextDecoration() const { return m_NonInheritedData.m_dwTextDecoration; } const CFX_CSSLength& CFX_CSSComputedStyle::GetLetterSpacing() const { return m_InheritedData.m_LetterSpacing; } void CFX_CSSComputedStyle::SetLineHeight(float fLineHeight) { m_InheritedData.m_fLineHeight = fLineHeight; } void CFX_CSSComputedStyle::SetTextIndent(const CFX_CSSLength& textIndent) { m_InheritedData.m_TextIndent = textIndent; } void CFX_CSSComputedStyle::SetTextAlign(CFX_CSSTextAlign eTextAlign) { m_InheritedData.m_eTextAlign = eTextAlign; } void CFX_CSSComputedStyle::SetNumberVerticalAlign(float fAlign) { m_NonInheritedData.m_eVerticalAlignType = CFX_CSSVerticalAlign::Number, m_NonInheritedData.m_fVerticalAlign = fAlign; } void CFX_CSSComputedStyle::SetTextDecoration(uint32_t dwTextDecoration) { m_NonInheritedData.m_dwTextDecoration = dwTextDecoration; } void CFX_CSSComputedStyle::SetLetterSpacing( const CFX_CSSLength& letterSpacing) { m_InheritedData.m_LetterSpacing = letterSpacing; } void CFX_CSSComputedStyle::AddCustomStyle(const CFX_CSSCustomProperty& prop) { // Force the property to be copied so we aren't dependent on the lifetime // of whatever currently owns it. m_CustomProperties.push_back(prop); } CFX_CSSComputedStyle::InheritedData::InheritedData() = default; CFX_CSSComputedStyle::InheritedData::~InheritedData() = default; CFX_CSSComputedStyle::NonInheritedData::NonInheritedData() = default;
AltSysrq/Abendstern
src/abendstern.hxx
/** * @file * @author <NAME> * @date 2012.05.20 * @brief Provides access to core ("kernel") functionality implemented in * abendstern.cxx, such as the preliminary run mode. */ #ifndef ABENDSTERN_HXX_ #define ABENDSTERN_HXX_ /** * The possible OpenGL builds. */ enum AbendsternGLType { AGLT14=0, AGLT21, AGLT32 }; #if defined(AB_OPENGL_14) #define THIS_GL_TYPE AGLT14 #elif defined(AB_OPENGL_21) #define THIS_GL_TYPE AGLT21 #else ///This OpenGL build #define THIS_GL_TYPE AGLT32 #endif ///In the preliminary configuration, the recommended OpenGL build to switch to extern AbendsternGLType recommendedGLType; /** * Set to true iff running in preliminary run mode. * * Preliminary run mode, initiated with the -prelim or -prelimauto flags, is a * special mode intended to allow the user to configure Abendstern before * starting the game proper. */ extern bool preliminaryRunMode; /** * Restarts Abendstern and starts the GL version indicated by * recommendedGLType. * * This call will never return. */ void exitPreliminaryRunMode(); #endif /* ABENDSTERN_HXX_ */
iot-dsa-v2/sdk-dslink-java
dslink-v2/src/test/java/org/iot/dsa/dslink/RequesterInvokeTest.java
package org.iot.dsa.dslink; import com.acuity.iot.dsa.dslink.test.V1TestLink; import com.acuity.iot.dsa.dslink.test.V2TestLink; import org.iot.dsa.dslink.requester.SimpleInvokeHandler; import org.iot.dsa.node.DSBool; import org.iot.dsa.node.DSInt; import org.iot.dsa.node.DSMap; import org.iot.dsa.node.DSNode; import org.iot.dsa.node.action.DSAction; import org.iot.dsa.node.action.DSIActionRequest; import org.testng.Assert; import org.testng.annotations.Test; /** * @author <NAME> */ public class RequesterInvokeTest { // Fields // ------ private static boolean success = false; // Methods // ------- @Test public void test() throws Exception { doit(new V1TestLink(new MyMain())); doit(new V2TestLink(new MyMain())); } private void doit(DSLink link) { success = false; Thread t = new Thread(link, "DSLink Runner"); t.start(); link.getConnection().waitForConnection(5000); Assert.assertTrue(link.getConnection().isConnected()); DSIRequester requester = link.getConnection().getRequester(); SimpleInvokeHandler res = (SimpleInvokeHandler) requester.invoke( "/main/simpleAction", null, new SimpleInvokeHandler()); res.waitForClose(1000); res = (SimpleInvokeHandler) requester.invoke( "/main/simpleParam", new DSMap().put("param", true), new SimpleInvokeHandler()); res.waitForClose(1000); Assert.assertTrue(success); try { success = false; res = (SimpleInvokeHandler) requester.invoke( "/main/exception", new DSMap().put("param", true), new SimpleInvokeHandler()); res.waitForClose(5000); } catch (Exception x) { success = true; } Assert.assertTrue(success); link.shutdown(); } // Inner Classes // ------------- public static class ANode extends DSNode { @Override public void declareDefaults() { declareDefault("int", DSInt.valueOf(0)); } @Override public ActionResults invoke(DSIActionRequest request) { return null; } } public static class MyMain extends DSMainNode { @Override public void declareDefaults() { declareDefault("anode", new ANode()); declareDefault("simpleAction", DSAction.DEFAULT); DSAction action = new DSAction(); action.addParameter("param", DSBool.NULL, "a desc"); declareDefault("simpleParam", action); declareDefault("exception", DSAction.DEFAULT); } @Override public ActionResults invoke(DSIActionRequest request) { String name = request.getActionInfo().getName(); if (name.equals("simpleAction")) { success = true; } else if (name.equals("simpleParam")) { DSMap params = request.getParameters(); success = params.get("param", false); } else if (name.equals("exception")) { throw new IllegalStateException("Expected exception"); } return null; } } }
zyhzgx/rax
templates/template-retail/templates/default/pages/index/components/QuickEntry/index.js
import { Component, PropTypes, createElement } from 'rax'; import { View, Text, Image, RecyclerView } from 'rax-components'; import OpenUrl from '../../mods/openUrl'; import style from './style'; const QuickEntry = function(props) { let sourceData = props.sourceData; if (sourceData.length === 0) { return null; } return ( <RecyclerView.Cell style={style.container}> {sourceData.map(getEntryItem)} </RecyclerView.Cell> ); }; function getEntryItem(item = {}) { if (!item.appImg) return null; const appUrl = item.appUrl; return ( <OpenUrl style={style.item} url={appUrl}> <View> <Image source={{uri: item.appImg}} style={style.image} /> <Text style={style.text}>{item.title}</Text> </View> </OpenUrl> ); } QuickEntry.propTypes = { sourceData: PropTypes.array }; QuickEntry.defaultProps = { sourceData: [] }; export default QuickEntry;
mrmuxl/june
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name='june', version='0.9.0', author='<NAME>', author_email='<EMAIL>', url='http://project.lepture.com/june', packages=find_packages(), description='June: a forum', install_requires=[ 'july', 'misaka', 'pygments', 'sqlalchemy', 'MySQL-python', 'python-memcached', ], include_package_data=True, license='BSD License', )
yangxulexis/pivot
dist-amd/layout/Popup.js
(function (root, factory) { if (typeof define === "function" && define.amd) { define(["d3", "../common/HTMLWidget", "../layout/Surface", "../common/Icon"], factory); } else { root.layout_Popup = factory(root.d3, root.common_HTMLWidget, root.layout_Surface, root.common_Icon); } }(this, function (d3, HTMLWidget, Surface, Icon) { function Popup() { HTMLWidget.call(this); this._tag = "div"; this._surfaceButtons = []; } Popup.prototype = Object.create(HTMLWidget.prototype); Popup.prototype.constructor = Popup; Popup.prototype._class += " layout_Popup"; Popup.prototype.publish("popupState", false, "boolean", "State of the popup, visible (true) or hidden (false)",null,{}); Popup.prototype.publish("shrinkWrap", false, "boolean", "The popup parent container either shrinks to the size of its contents (true) or expands to fit thge popup's parentDiv (false)",null,{}); Popup.prototype.publish("centerPopup", "none", "set", "Center the widget in its container element (target) or in the window",["none", "container", "window"],{}); Popup.prototype.publish("top", null, "number", "Top position property of popup",null,{}); Popup.prototype.publish("bottom", null, "number", "Bottom position property of popup",null,{}); Popup.prototype.publish("left", null, "number", "Left position property of popup",null,{}); Popup.prototype.publish("right", null, "number", "Right position property of popup",null,{}); Popup.prototype.publish("position", "relative", "set", "Value of the 'position' property",["absolute", "relative", "fixed", "static", "initial", "inherit" ],{tags:["Private"]}); Popup.prototype.publish("widget", null, "widget", "Widget",null,{tags:["Private"]}); Popup.prototype.updateState = function (visible) { visible = visible || !this.popupState(); this.popupState(visible).render(); }; Popup.prototype.enter = function (domNode, element) { HTMLWidget.prototype.enter.apply(this, arguments); this.widget() .target(domNode) ; this._originalPosition = this.position(); }; Popup.prototype.update = function (domNode, element) { HTMLWidget.prototype.update.apply(this, arguments); element.style({ visibility: this.popupState() ? null : "hidden", opacity: this.popupState() ? null : 0, width: this.shrinkWrap() ? this.widget().width() + "px": this._size.width + "px", height: this.shrinkWrap() ? this.widget().height() + "px" : this._size.height + "px", }); if (this.widget().size().height === 0 ) { this.widget().resize(this.size()); } }; Popup.prototype.postUpdate = function (domNode, element) { var left, top; switch (this.centerPopup()) { case "container": if (this._parentElement) { left = parseInt(this._parentElement.style("width"))/2 - this.widget().width()/2; top = parseInt(this._parentElement.style("height"))/2 - this.widget().height()/2; } this.position("absolute"); break; case "window": left = window.innerWidth/2 - this.widget().width()/2; top = window.innerHeight/2 - this.widget().height()/2; this.position("fixed"); break; default: left = 0; top = 0; this.position(this._originalPosition); break; } this.pos({ x: left, y: top }); HTMLWidget.prototype.postUpdate.apply(this, arguments); element .style("position",this.position()) .style("left",this.left() + "px") .style("right",this.right() + "px") .style("top",this.top() + "px") .style("bottom",this.bottom() + "px") ; }; Popup.prototype.exit = function (domNode, element) { if (this.widget()) { this.widget(null); this.render(); } HTMLWidget.prototype.exit.apply(this, arguments); }; Popup.prototype.click = function(obj) { console.log("Clicked: " + obj.id); }; return Popup; }));
tuanalexeu/logiweb-microservices
logiweb-service/src/main/java/com/alekseytyan/logiweb/service/implementation/MessageServiceImpl.java
<gh_stars>1-10 package com.alekseytyan.logiweb.service.implementation; import com.alekseytyan.logiweb.service.api.MessageService; import com.google.api.core.ApiFuture; import com.google.cloud.pubsub.v1.Publisher; import com.google.protobuf.ByteString; import com.google.pubsub.v1.PubsubMessage; import com.google.pubsub.v1.TopicName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @Service public class MessageServiceImpl implements MessageService { @Value("${PUBSUB_TOPIC}") private String topicId; @Value("${PROJECT_ID_ENV}") private String projectId; private static final Logger logger = LoggerFactory.getLogger(MessageServiceImpl.class); @Override public void send(String message) { try { publishMessage(projectId, topicId, message); } catch (IOException | ExecutionException | InterruptedException e) { e.printStackTrace(); } } public static void publishMessage(String projectId, String topicId, String message) throws IOException, ExecutionException, InterruptedException { TopicName topicName = TopicName.of(projectId, topicId); Publisher publisher = null; try { // Create a publisher instance with default settings bound to the topic publisher = Publisher.newBuilder(topicName).build(); ByteString data = ByteString.copyFromUtf8(message); PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build(); // Once published, returns a server-assigned message id (unique within the topic) ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage); String messageId = messageIdFuture.get(); logger.info("Published message ID: " + messageId); } finally { if (publisher != null) { // When finished with the publisher, shutdown to free up resources. publisher.shutdown(); publisher.awaitTermination(1, TimeUnit.MINUTES); } } } }
maruilong/tx-lcn
tx-client/src/main/java/com/codingapi/tx/datasource/package-info.java
<reponame>maruilong/tx-lcn /** * 连接池 * * create by lorne on 2017/11/11 */ package com.codingapi.tx.datasource;
grondo/mvapich2-cce
src/mpid/ch3/channels/common/include/rdma_3dtorus.h
<reponame>grondo/mvapich2-cce<filename>src/mpid/ch3/channels/common/include/rdma_3dtorus.h<gh_stars>1-10 /* Copyright (c) 2003-2011, The Ohio State University. All rights * reserved. * * This file is part of the MVAPICH2 software package developed by the * team members of The Ohio State University's Network-Based Computing * Laboratory (NBCL), headed by Professor <NAME>. (<NAME>. * * For detailed copyright and licensing information, please refer to the * copyright file COPYRIGHT in the top level MVAPICH2 directory. * */ #ifndef RDMA_3DTORUS_H #define RDMA_3DTORUS_H #include <netinet/in.h> #include <infiniband/verbs.h> #include <infiniband/umad.h> #include <mpidi_ch3_impl.h> #define IB_MGMT_BASE_VERSION 1 #define IB_MGMT_CLASS_SUBN_ADM 0x03 #define IB_MGMT_METHOD_GET 0x01 #define IB_SA_TID_GET_PATH_REC_0 0xCA000000UL #define IB_SA_TID_GET_PATH_REC_1 0xBEEF0000UL struct ib_gid_half { uint8_t bytes[8]; }; struct ib_gid { union { uint8_t bytes[16]; uint16_t words[8]; uint32_t dwords[4]; struct ib_gid_half half[2]; } u; }; struct ib_smp_class_specific { uint8_t hop_pointer; uint8_t hop_count; } __attribute__ (( packed )); union ib_mad_class_specific { uint16_t raw; struct ib_smp_class_specific smp; } __attribute__ (( packed )); struct ib_mad_hdr { uint8_t base_version; uint8_t mgmt_class; uint8_t class_version; uint8_t method; uint16_t status; union ib_mad_class_specific class_specific; uint32_t tid[2]; uint16_t attr_id; uint8_t reserved[2]; uint32_t attr_mod; } __attribute__ (( packed )); struct ib_rmpp_hdr { uint32_t raw[3]; } __attribute__ (( packed )); struct ib_sa_hdr { uint32_t sm_key[2]; uint16_t reserved; uint16_t attrib_offset; uint32_t comp_mask[2]; } __attribute__ (( packed )); #define IB_SA_ATTR_PATH_REC 0x35 struct ib_path_record { uint32_t reserved0[2]; struct ib_gid dgid; struct ib_gid sgid; uint16_t dlid; uint16_t slid; uint32_t hop_limit__flow_label__raw_traffic; uint32_t pkey__numb_path__reversible__tclass; uint8_t reserved1; uint8_t reserved__sl; uint8_t mtu_selector__mtu; uint8_t rate_selector__rate; uint32_t preference__packet_lifetime__packet_lifetime_selector; uint32_t reserved2[35]; } __attribute__ (( packed )); #define IB_SA_PATH_REC_DLID (1<<4) #define IB_SA_PATH_REC_SLID (1<<5) union ib_sa_data { struct ib_path_record path_record; } __attribute__ (( packed )); struct ib_mad_sa { struct ib_mad_hdr mad_hdr; struct ib_rmpp_hdr rmpp_hdr; struct ib_sa_hdr sa_hdr; union ib_sa_data sa_data; } __attribute__ (( packed )); #define IB_SA_QPN 1 #define IB_GLOBAL_QKEY 0x80010000UL struct openib_sa_qp_cache_t { /* There will be a MR with the one send and receive buffer together */ /* The send buffer is first, the receive buffer is second */ /* The receive buffer in a UD queue pair needs room for the 40 byte GRH */ /* The buffers are first in the structure for page alignment */ char send_recv_buffer[sizeof(struct ib_mad_sa) * 2 + 40]; struct openib_sa_qp_cache_t *next; struct ibv_context *context; char *device_name; uint32_t port_num; struct ibv_qp *qp; struct ibv_ah *ah; struct ibv_cq *cq; struct ibv_mr *mr; struct ibv_recv_wr rwr; struct ibv_sge rsge; char sl_values[65536]; }; int mv2_release_3d_torus_resources(); int mv2_get_path_rec_sl(struct ibv_context *context_arg, struct ibv_pd *hca_pd, uint32_t port_num, uint16_t lid, uint16_t rem_lid, int network_is_3dtorus, int num_sa_retries); #endif /* RDMA_3DTORUS_H */
google/nearby
internal/platform/implementation/windows/generated/winrt/Windows.Services.TargetedContent.h
<gh_stars>10-100 // WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.220531.1 #pragma once #ifndef WINRT_Windows_Services_TargetedContent_H #define WINRT_Windows_Services_TargetedContent_H #include "winrt/base.h" static_assert(winrt::check_version(CPPWINRT_VERSION, "2.0.220531.1"), "Mismatched C++/WinRT headers."); #define CPPWINRT_VERSION "2.0.220531.1" #include "winrt/impl/Windows.Foundation.2.h" #include "winrt/impl/Windows.Foundation.Collections.2.h" #include "winrt/impl/Windows.Storage.Streams.2.h" #include "winrt/impl/Windows.Services.TargetedContent.2.h" namespace winrt::impl { template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentAction<D>::InvokeAsync() const { void* asyncAction{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentAction)->InvokeAsync(&asyncAction)); return winrt::Windows::Foundation::IAsyncAction{ asyncAction, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentAvailabilityChangedEventArgs<D>::GetDeferral() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentAvailabilityChangedEventArgs)->GetDeferral(&value)); return winrt::Windows::Foundation::Deferral{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentChangedEventArgs<D>::GetDeferral() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentChangedEventArgs)->GetDeferral(&value)); return winrt::Windows::Foundation::Deferral{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentChangedEventArgs<D>::HasPreviousContentExpired() const { bool value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentChangedEventArgs)->get_HasPreviousContentExpired(&value)); return value; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentCollection<D>::Id() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentCollection)->get_Id(&value)); return hstring{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentCollection<D>::ReportInteraction(winrt::Windows::Services::TargetedContent::TargetedContentInteraction const& interaction) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentCollection)->ReportInteraction(static_cast<int32_t>(interaction))); } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentCollection<D>::ReportCustomInteraction(param::hstring const& customInteractionName) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentCollection)->ReportCustomInteraction(*(void**)(&customInteractionName))); } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentCollection<D>::Path() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentCollection)->get_Path(&value)); return hstring{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentCollection<D>::Properties() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentCollection)->get_Properties(&value)); return winrt::Windows::Foundation::Collections::IMapView<hstring, winrt::Windows::Services::TargetedContent::TargetedContentValue>{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentCollection<D>::Collections() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentCollection)->get_Collections(&value)); return winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::Services::TargetedContent::TargetedContentCollection>{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentCollection<D>::Items() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentCollection)->get_Items(&value)); return winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::Services::TargetedContent::TargetedContentItem>{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentContainer<D>::Id() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentContainer)->get_Id(&value)); return hstring{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentContainer<D>::Timestamp() const { winrt::Windows::Foundation::DateTime value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentContainer)->get_Timestamp(put_abi(value))); return value; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentContainer<D>::Availability() const { winrt::Windows::Services::TargetedContent::TargetedContentAvailability value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentContainer)->get_Availability(reinterpret_cast<int32_t*>(&value))); return value; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentContainer<D>::Content() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentContainer)->get_Content(&value)); return winrt::Windows::Services::TargetedContent::TargetedContentCollection{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentContainer<D>::SelectSingleObject(param::hstring const& path) const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentContainer)->SelectSingleObject(*(void**)(&path), &value)); return winrt::Windows::Services::TargetedContent::TargetedContentObject{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentContainerStatics<D>::GetAsync(param::hstring const& contentId) const { void* asyncOperation{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentContainerStatics)->GetAsync(*(void**)(&contentId), &asyncOperation)); return winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Services::TargetedContent::TargetedContentContainer>{ asyncOperation, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentImage<D>::Height() const { uint32_t value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentImage)->get_Height(&value)); return value; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentImage<D>::Width() const { uint32_t value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentImage)->get_Width(&value)); return value; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentItem<D>::Path() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentItem)->get_Path(&value)); return hstring{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentItem<D>::ReportInteraction(winrt::Windows::Services::TargetedContent::TargetedContentInteraction const& interaction) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentItem)->ReportInteraction(static_cast<int32_t>(interaction))); } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentItem<D>::ReportCustomInteraction(param::hstring const& customInteractionName) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentItem)->ReportCustomInteraction(*(void**)(&customInteractionName))); } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentItem<D>::State() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentItem)->get_State(&value)); return winrt::Windows::Services::TargetedContent::TargetedContentItemState{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentItem<D>::Properties() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentItem)->get_Properties(&value)); return winrt::Windows::Foundation::Collections::IMapView<hstring, winrt::Windows::Services::TargetedContent::TargetedContentValue>{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentItem<D>::Collections() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentItem)->get_Collections(&value)); return winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::Services::TargetedContent::TargetedContentCollection>{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentItemState<D>::ShouldDisplay() const { bool value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentItemState)->get_ShouldDisplay(&value)); return value; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentItemState<D>::AppInstallationState() const { winrt::Windows::Services::TargetedContent::TargetedContentAppInstallationState value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentItemState)->get_AppInstallationState(reinterpret_cast<int32_t*>(&value))); return value; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentObject<D>::ObjectKind() const { winrt::Windows::Services::TargetedContent::TargetedContentObjectKind value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentObject)->get_ObjectKind(reinterpret_cast<int32_t*>(&value))); return value; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentObject<D>::Collection() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentObject)->get_Collection(&value)); return winrt::Windows::Services::TargetedContent::TargetedContentCollection{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentObject<D>::Item() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentObject)->get_Item(&value)); return winrt::Windows::Services::TargetedContent::TargetedContentItem{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentObject<D>::Value() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentObject)->get_Value(&value)); return winrt::Windows::Services::TargetedContent::TargetedContentValue{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentStateChangedEventArgs<D>::GetDeferral() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentStateChangedEventArgs)->GetDeferral(&value)); return winrt::Windows::Foundation::Deferral{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscription<D>::Id() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentSubscription)->get_Id(&value)); return hstring{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscription<D>::GetContentContainerAsync() const { void* asyncOperation{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentSubscription)->GetContentContainerAsync(&asyncOperation)); return winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Services::TargetedContent::TargetedContentContainer>{ asyncOperation, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscription<D>::ContentChanged(winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Services::TargetedContent::TargetedContentSubscription, winrt::Windows::Services::TargetedContent::TargetedContentChangedEventArgs> const& handler) const { winrt::event_token cookie{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentSubscription)->add_ContentChanged(*(void**)(&handler), put_abi(cookie))); return cookie; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscription<D>::ContentChanged(auto_revoke_t, winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Services::TargetedContent::TargetedContentSubscription, winrt::Windows::Services::TargetedContent::TargetedContentChangedEventArgs> const& handler) const { return impl::make_event_revoker<D, ContentChanged_revoker>(this, ContentChanged(handler)); } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscription<D>::ContentChanged(winrt::event_token const& cookie) const noexcept { WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentSubscription)->remove_ContentChanged(impl::bind_in(cookie)); } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscription<D>::AvailabilityChanged(winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Services::TargetedContent::TargetedContentSubscription, winrt::Windows::Services::TargetedContent::TargetedContentAvailabilityChangedEventArgs> const& handler) const { winrt::event_token cookie{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentSubscription)->add_AvailabilityChanged(*(void**)(&handler), put_abi(cookie))); return cookie; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscription<D>::AvailabilityChanged(auto_revoke_t, winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Services::TargetedContent::TargetedContentSubscription, winrt::Windows::Services::TargetedContent::TargetedContentAvailabilityChangedEventArgs> const& handler) const { return impl::make_event_revoker<D, AvailabilityChanged_revoker>(this, AvailabilityChanged(handler)); } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscription<D>::AvailabilityChanged(winrt::event_token const& cookie) const noexcept { WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentSubscription)->remove_AvailabilityChanged(impl::bind_in(cookie)); } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscription<D>::StateChanged(winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Services::TargetedContent::TargetedContentSubscription, winrt::Windows::Services::TargetedContent::TargetedContentStateChangedEventArgs> const& handler) const { winrt::event_token cookie{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentSubscription)->add_StateChanged(*(void**)(&handler), put_abi(cookie))); return cookie; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscription<D>::StateChanged(auto_revoke_t, winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Services::TargetedContent::TargetedContentSubscription, winrt::Windows::Services::TargetedContent::TargetedContentStateChangedEventArgs> const& handler) const { return impl::make_event_revoker<D, StateChanged_revoker>(this, StateChanged(handler)); } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscription<D>::StateChanged(winrt::event_token const& cookie) const noexcept { WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentSubscription)->remove_StateChanged(impl::bind_in(cookie)); } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscriptionOptions<D>::SubscriptionId() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentSubscriptionOptions)->get_SubscriptionId(&value)); return hstring{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscriptionOptions<D>::AllowPartialContentAvailability() const { bool value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentSubscriptionOptions)->get_AllowPartialContentAvailability(&value)); return value; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscriptionOptions<D>::AllowPartialContentAvailability(bool value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentSubscriptionOptions)->put_AllowPartialContentAvailability(value)); } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscriptionOptions<D>::CloudQueryParameters() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentSubscriptionOptions)->get_CloudQueryParameters(&value)); return winrt::Windows::Foundation::Collections::IMap<hstring, hstring>{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscriptionOptions<D>::LocalFilters() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentSubscriptionOptions)->get_LocalFilters(&value)); return winrt::Windows::Foundation::Collections::IVector<hstring>{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscriptionOptions<D>::Update() const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentSubscriptionOptions)->Update()); } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscriptionStatics<D>::GetAsync(param::hstring const& subscriptionId) const { void* asyncOperation{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentSubscriptionStatics)->GetAsync(*(void**)(&subscriptionId), &asyncOperation)); return winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Services::TargetedContent::TargetedContentSubscription>{ asyncOperation, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentSubscriptionStatics<D>::GetOptions(param::hstring const& subscriptionId) const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentSubscriptionStatics)->GetOptions(*(void**)(&subscriptionId), &value)); return winrt::Windows::Services::TargetedContent::TargetedContentSubscriptionOptions{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentValue<D>::ValueKind() const { winrt::Windows::Services::TargetedContent::TargetedContentValueKind value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentValue)->get_ValueKind(reinterpret_cast<int32_t*>(&value))); return value; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentValue<D>::Path() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentValue)->get_Path(&value)); return hstring{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentValue<D>::String() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentValue)->get_String(&value)); return hstring{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentValue<D>::Uri() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentValue)->get_Uri(&value)); return winrt::Windows::Foundation::Uri{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentValue<D>::Number() const { double value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentValue)->get_Number(&value)); return value; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentValue<D>::Boolean() const { bool value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentValue)->get_Boolean(&value)); return value; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentValue<D>::File() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentValue)->get_File(&value)); return winrt::Windows::Services::TargetedContent::TargetedContentFile{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentValue<D>::ImageFile() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentValue)->get_ImageFile(&value)); return winrt::Windows::Services::TargetedContent::TargetedContentImage{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentValue<D>::Action() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentValue)->get_Action(&value)); return winrt::Windows::Services::TargetedContent::TargetedContentAction{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentValue<D>::Strings() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentValue)->get_Strings(&value)); return winrt::Windows::Foundation::Collections::IVectorView<hstring>{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentValue<D>::Uris() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentValue)->get_Uris(&value)); return winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::Foundation::Uri>{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentValue<D>::Numbers() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentValue)->get_Numbers(&value)); return winrt::Windows::Foundation::Collections::IVectorView<double>{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentValue<D>::Booleans() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentValue)->get_Booleans(&value)); return winrt::Windows::Foundation::Collections::IVectorView<bool>{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentValue<D>::Files() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentValue)->get_Files(&value)); return winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::Services::TargetedContent::TargetedContentFile>{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentValue<D>::ImageFiles() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentValue)->get_ImageFiles(&value)); return winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::Services::TargetedContent::TargetedContentImage>{ value, take_ownership_from_abi }; } template <typename D> auto consume_Windows_Services_TargetedContent_ITargetedContentValue<D>::Actions() const { void* value{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::Services::TargetedContent::ITargetedContentValue)->get_Actions(&value)); return winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::Services::TargetedContent::TargetedContentAction>{ value, take_ownership_from_abi }; } #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, winrt::Windows::Services::TargetedContent::ITargetedContentAction> : produce_base<D, winrt::Windows::Services::TargetedContent::ITargetedContentAction> { int32_t __stdcall InvokeAsync(void** asyncAction) noexcept final try { clear_abi(asyncAction); typename D::abi_guard guard(this->shim()); *asyncAction = detach_from<winrt::Windows::Foundation::IAsyncAction>(this->shim().InvokeAsync()); return 0; } catch (...) { return to_hresult(); } }; #endif #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, winrt::Windows::Services::TargetedContent::ITargetedContentAvailabilityChangedEventArgs> : produce_base<D, winrt::Windows::Services::TargetedContent::ITargetedContentAvailabilityChangedEventArgs> { int32_t __stdcall GetDeferral(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::Deferral>(this->shim().GetDeferral()); return 0; } catch (...) { return to_hresult(); } }; #endif #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, winrt::Windows::Services::TargetedContent::ITargetedContentChangedEventArgs> : produce_base<D, winrt::Windows::Services::TargetedContent::ITargetedContentChangedEventArgs> { int32_t __stdcall GetDeferral(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::Deferral>(this->shim().GetDeferral()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_HasPreviousContentExpired(bool* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<bool>(this->shim().HasPreviousContentExpired()); return 0; } catch (...) { return to_hresult(); } }; #endif #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, winrt::Windows::Services::TargetedContent::ITargetedContentCollection> : produce_base<D, winrt::Windows::Services::TargetedContent::ITargetedContentCollection> { int32_t __stdcall get_Id(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<hstring>(this->shim().Id()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall ReportInteraction(int32_t interaction) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().ReportInteraction(*reinterpret_cast<winrt::Windows::Services::TargetedContent::TargetedContentInteraction const*>(&interaction)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall ReportCustomInteraction(void* customInteractionName) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().ReportCustomInteraction(*reinterpret_cast<hstring const*>(&customInteractionName)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Path(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<hstring>(this->shim().Path()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Properties(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::Collections::IMapView<hstring, winrt::Windows::Services::TargetedContent::TargetedContentValue>>(this->shim().Properties()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Collections(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::Services::TargetedContent::TargetedContentCollection>>(this->shim().Collections()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Items(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::Services::TargetedContent::TargetedContentItem>>(this->shim().Items()); return 0; } catch (...) { return to_hresult(); } }; #endif #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, winrt::Windows::Services::TargetedContent::ITargetedContentContainer> : produce_base<D, winrt::Windows::Services::TargetedContent::ITargetedContentContainer> { int32_t __stdcall get_Id(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<hstring>(this->shim().Id()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Timestamp(int64_t* value) noexcept final try { zero_abi<winrt::Windows::Foundation::DateTime>(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::DateTime>(this->shim().Timestamp()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Availability(int32_t* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Services::TargetedContent::TargetedContentAvailability>(this->shim().Availability()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Content(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Services::TargetedContent::TargetedContentCollection>(this->shim().Content()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SelectSingleObject(void* path, void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Services::TargetedContent::TargetedContentObject>(this->shim().SelectSingleObject(*reinterpret_cast<hstring const*>(&path))); return 0; } catch (...) { return to_hresult(); } }; #endif #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, winrt::Windows::Services::TargetedContent::ITargetedContentContainerStatics> : produce_base<D, winrt::Windows::Services::TargetedContent::ITargetedContentContainerStatics> { int32_t __stdcall GetAsync(void* contentId, void** asyncOperation) noexcept final try { clear_abi(asyncOperation); typename D::abi_guard guard(this->shim()); *asyncOperation = detach_from<winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Services::TargetedContent::TargetedContentContainer>>(this->shim().GetAsync(*reinterpret_cast<hstring const*>(&contentId))); return 0; } catch (...) { return to_hresult(); } }; #endif #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, winrt::Windows::Services::TargetedContent::ITargetedContentImage> : produce_base<D, winrt::Windows::Services::TargetedContent::ITargetedContentImage> { int32_t __stdcall get_Height(uint32_t* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<uint32_t>(this->shim().Height()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Width(uint32_t* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<uint32_t>(this->shim().Width()); return 0; } catch (...) { return to_hresult(); } }; #endif #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, winrt::Windows::Services::TargetedContent::ITargetedContentItem> : produce_base<D, winrt::Windows::Services::TargetedContent::ITargetedContentItem> { int32_t __stdcall get_Path(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<hstring>(this->shim().Path()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall ReportInteraction(int32_t interaction) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().ReportInteraction(*reinterpret_cast<winrt::Windows::Services::TargetedContent::TargetedContentInteraction const*>(&interaction)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall ReportCustomInteraction(void* customInteractionName) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().ReportCustomInteraction(*reinterpret_cast<hstring const*>(&customInteractionName)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_State(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Services::TargetedContent::TargetedContentItemState>(this->shim().State()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Properties(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::Collections::IMapView<hstring, winrt::Windows::Services::TargetedContent::TargetedContentValue>>(this->shim().Properties()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Collections(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::Services::TargetedContent::TargetedContentCollection>>(this->shim().Collections()); return 0; } catch (...) { return to_hresult(); } }; #endif #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, winrt::Windows::Services::TargetedContent::ITargetedContentItemState> : produce_base<D, winrt::Windows::Services::TargetedContent::ITargetedContentItemState> { int32_t __stdcall get_ShouldDisplay(bool* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<bool>(this->shim().ShouldDisplay()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_AppInstallationState(int32_t* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Services::TargetedContent::TargetedContentAppInstallationState>(this->shim().AppInstallationState()); return 0; } catch (...) { return to_hresult(); } }; #endif #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, winrt::Windows::Services::TargetedContent::ITargetedContentObject> : produce_base<D, winrt::Windows::Services::TargetedContent::ITargetedContentObject> { int32_t __stdcall get_ObjectKind(int32_t* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Services::TargetedContent::TargetedContentObjectKind>(this->shim().ObjectKind()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Collection(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Services::TargetedContent::TargetedContentCollection>(this->shim().Collection()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Item(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Services::TargetedContent::TargetedContentItem>(this->shim().Item()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Value(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Services::TargetedContent::TargetedContentValue>(this->shim().Value()); return 0; } catch (...) { return to_hresult(); } }; #endif #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, winrt::Windows::Services::TargetedContent::ITargetedContentStateChangedEventArgs> : produce_base<D, winrt::Windows::Services::TargetedContent::ITargetedContentStateChangedEventArgs> { int32_t __stdcall GetDeferral(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::Deferral>(this->shim().GetDeferral()); return 0; } catch (...) { return to_hresult(); } }; #endif #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, winrt::Windows::Services::TargetedContent::ITargetedContentSubscription> : produce_base<D, winrt::Windows::Services::TargetedContent::ITargetedContentSubscription> { int32_t __stdcall get_Id(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<hstring>(this->shim().Id()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetContentContainerAsync(void** asyncOperation) noexcept final try { clear_abi(asyncOperation); typename D::abi_guard guard(this->shim()); *asyncOperation = detach_from<winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Services::TargetedContent::TargetedContentContainer>>(this->shim().GetContentContainerAsync()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall add_ContentChanged(void* handler, winrt::event_token* cookie) noexcept final try { zero_abi<winrt::event_token>(cookie); typename D::abi_guard guard(this->shim()); *cookie = detach_from<winrt::event_token>(this->shim().ContentChanged(*reinterpret_cast<winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Services::TargetedContent::TargetedContentSubscription, winrt::Windows::Services::TargetedContent::TargetedContentChangedEventArgs> const*>(&handler))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall remove_ContentChanged(winrt::event_token cookie) noexcept final { typename D::abi_guard guard(this->shim()); this->shim().ContentChanged(*reinterpret_cast<winrt::event_token const*>(&cookie)); return 0; } int32_t __stdcall add_AvailabilityChanged(void* handler, winrt::event_token* cookie) noexcept final try { zero_abi<winrt::event_token>(cookie); typename D::abi_guard guard(this->shim()); *cookie = detach_from<winrt::event_token>(this->shim().AvailabilityChanged(*reinterpret_cast<winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Services::TargetedContent::TargetedContentSubscription, winrt::Windows::Services::TargetedContent::TargetedContentAvailabilityChangedEventArgs> const*>(&handler))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall remove_AvailabilityChanged(winrt::event_token cookie) noexcept final { typename D::abi_guard guard(this->shim()); this->shim().AvailabilityChanged(*reinterpret_cast<winrt::event_token const*>(&cookie)); return 0; } int32_t __stdcall add_StateChanged(void* handler, winrt::event_token* cookie) noexcept final try { zero_abi<winrt::event_token>(cookie); typename D::abi_guard guard(this->shim()); *cookie = detach_from<winrt::event_token>(this->shim().StateChanged(*reinterpret_cast<winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Services::TargetedContent::TargetedContentSubscription, winrt::Windows::Services::TargetedContent::TargetedContentStateChangedEventArgs> const*>(&handler))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall remove_StateChanged(winrt::event_token cookie) noexcept final { typename D::abi_guard guard(this->shim()); this->shim().StateChanged(*reinterpret_cast<winrt::event_token const*>(&cookie)); return 0; } }; #endif #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, winrt::Windows::Services::TargetedContent::ITargetedContentSubscriptionOptions> : produce_base<D, winrt::Windows::Services::TargetedContent::ITargetedContentSubscriptionOptions> { int32_t __stdcall get_SubscriptionId(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<hstring>(this->shim().SubscriptionId()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_AllowPartialContentAvailability(bool* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<bool>(this->shim().AllowPartialContentAvailability()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall put_AllowPartialContentAvailability(bool value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().AllowPartialContentAvailability(value); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_CloudQueryParameters(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::Collections::IMap<hstring, hstring>>(this->shim().CloudQueryParameters()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_LocalFilters(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::Collections::IVector<hstring>>(this->shim().LocalFilters()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall Update() noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().Update(); return 0; } catch (...) { return to_hresult(); } }; #endif #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, winrt::Windows::Services::TargetedContent::ITargetedContentSubscriptionStatics> : produce_base<D, winrt::Windows::Services::TargetedContent::ITargetedContentSubscriptionStatics> { int32_t __stdcall GetAsync(void* subscriptionId, void** asyncOperation) noexcept final try { clear_abi(asyncOperation); typename D::abi_guard guard(this->shim()); *asyncOperation = detach_from<winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Services::TargetedContent::TargetedContentSubscription>>(this->shim().GetAsync(*reinterpret_cast<hstring const*>(&subscriptionId))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetOptions(void* subscriptionId, void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Services::TargetedContent::TargetedContentSubscriptionOptions>(this->shim().GetOptions(*reinterpret_cast<hstring const*>(&subscriptionId))); return 0; } catch (...) { return to_hresult(); } }; #endif #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, winrt::Windows::Services::TargetedContent::ITargetedContentValue> : produce_base<D, winrt::Windows::Services::TargetedContent::ITargetedContentValue> { int32_t __stdcall get_ValueKind(int32_t* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Services::TargetedContent::TargetedContentValueKind>(this->shim().ValueKind()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Path(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<hstring>(this->shim().Path()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_String(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<hstring>(this->shim().String()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Uri(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::Uri>(this->shim().Uri()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Number(double* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<double>(this->shim().Number()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Boolean(bool* value) noexcept final try { typename D::abi_guard guard(this->shim()); *value = detach_from<bool>(this->shim().Boolean()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_File(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Services::TargetedContent::TargetedContentFile>(this->shim().File()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_ImageFile(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Services::TargetedContent::TargetedContentImage>(this->shim().ImageFile()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Action(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Services::TargetedContent::TargetedContentAction>(this->shim().Action()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Strings(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::Collections::IVectorView<hstring>>(this->shim().Strings()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Uris(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::Foundation::Uri>>(this->shim().Uris()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Numbers(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::Collections::IVectorView<double>>(this->shim().Numbers()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Booleans(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::Collections::IVectorView<bool>>(this->shim().Booleans()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Files(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::Services::TargetedContent::TargetedContentFile>>(this->shim().Files()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_ImageFiles(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::Services::TargetedContent::TargetedContentImage>>(this->shim().ImageFiles()); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall get_Actions(void** value) noexcept final try { clear_abi(value); typename D::abi_guard guard(this->shim()); *value = detach_from<winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::Services::TargetedContent::TargetedContentAction>>(this->shim().Actions()); return 0; } catch (...) { return to_hresult(); } }; #endif } WINRT_EXPORT namespace winrt::Windows::Services::TargetedContent { inline auto TargetedContentContainer::GetAsync(param::hstring const& contentId) { return impl::call_factory<TargetedContentContainer, ITargetedContentContainerStatics>([&](ITargetedContentContainerStatics const& f) { return f.GetAsync(contentId); }); } inline auto TargetedContentSubscription::GetAsync(param::hstring const& subscriptionId) { return impl::call_factory<TargetedContentSubscription, ITargetedContentSubscriptionStatics>([&](ITargetedContentSubscriptionStatics const& f) { return f.GetAsync(subscriptionId); }); } inline auto TargetedContentSubscription::GetOptions(param::hstring const& subscriptionId) { return impl::call_factory<TargetedContentSubscription, ITargetedContentSubscriptionStatics>([&](ITargetedContentSubscriptionStatics const& f) { return f.GetOptions(subscriptionId); }); } } namespace std { #ifndef WINRT_LEAN_AND_MEAN template<> struct hash<winrt::Windows::Services::TargetedContent::ITargetedContentAction> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::ITargetedContentAvailabilityChangedEventArgs> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::ITargetedContentChangedEventArgs> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::ITargetedContentCollection> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::ITargetedContentContainer> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::ITargetedContentContainerStatics> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::ITargetedContentImage> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::ITargetedContentItem> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::ITargetedContentItemState> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::ITargetedContentObject> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::ITargetedContentStateChangedEventArgs> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::ITargetedContentSubscription> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::ITargetedContentSubscriptionOptions> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::ITargetedContentSubscriptionStatics> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::ITargetedContentValue> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::TargetedContentAction> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::TargetedContentAvailabilityChangedEventArgs> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::TargetedContentChangedEventArgs> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::TargetedContentCollection> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::TargetedContentContainer> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::TargetedContentFile> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::TargetedContentImage> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::TargetedContentItem> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::TargetedContentItemState> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::TargetedContentObject> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::TargetedContentStateChangedEventArgs> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::TargetedContentSubscription> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::TargetedContentSubscriptionOptions> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::Services::TargetedContent::TargetedContentValue> : winrt::impl::hash_base {}; #endif #ifdef __cpp_lib_format #endif } #endif
ScalablyTyped/SlinkyTyped
g/gaea-model/src/main/scala/typingsSlinky/gaeaModel/FitGaea/DiffRemove.scala
package typingsSlinky.gaeaModel.FitGaea import org.scalablytyped.runtime.StringDictionary import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait DiffRemove extends ViewportComponentFullInfo { // 删除的位置 var index: Double = js.native // 父级元素 mapKey var parentMapUniqueKey: String = js.native } object DiffRemove { @scala.inline def apply( childs: StringDictionary[ViewportComponentInfo], componentInfo: ViewportComponentInfo, index: Double, mapUniqueKey: String, parentMapUniqueKey: String ): DiffRemove = { val __obj = js.Dynamic.literal(childs = childs.asInstanceOf[js.Any], componentInfo = componentInfo.asInstanceOf[js.Any], index = index.asInstanceOf[js.Any], mapUniqueKey = mapUniqueKey.asInstanceOf[js.Any], parentMapUniqueKey = parentMapUniqueKey.asInstanceOf[js.Any]) __obj.asInstanceOf[DiffRemove] } @scala.inline implicit class DiffRemoveMutableBuilder[Self <: DiffRemove] (val x: Self) extends AnyVal { @scala.inline def setIndex(value: Double): Self = StObject.set(x, "index", value.asInstanceOf[js.Any]) @scala.inline def setParentMapUniqueKey(value: String): Self = StObject.set(x, "parentMapUniqueKey", value.asInstanceOf[js.Any]) } }
gstingy/uc_python_api
ultracart/models/affiliate_click.py
# coding: utf-8 """ UltraCart Rest API V2 UltraCart REST API Version 2 OpenAPI spec version: 2.0.0 Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class AffiliateClick(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'affiliate_click_oid': 'int', 'affiliate_link_oid': 'int', 'affiliate_oid': 'int', 'click_dts': 'str', 'ip_address': 'str', 'landing_page': 'str', 'landing_page_query_string': 'str', 'link': 'AffiliateLink', 'referrer': 'str', 'referrer_query_string': 'str', 'sub_id': 'str' } attribute_map = { 'affiliate_click_oid': 'affiliate_click_oid', 'affiliate_link_oid': 'affiliate_link_oid', 'affiliate_oid': 'affiliate_oid', 'click_dts': 'click_dts', 'ip_address': 'ip_address', 'landing_page': 'landing_page', 'landing_page_query_string': 'landing_page_query_string', 'link': 'link', 'referrer': 'referrer', 'referrer_query_string': 'referrer_query_string', 'sub_id': 'sub_id' } def __init__(self, affiliate_click_oid=None, affiliate_link_oid=None, affiliate_oid=None, click_dts=None, ip_address=None, landing_page=None, landing_page_query_string=None, link=None, referrer=None, referrer_query_string=None, sub_id=None): """ AffiliateClick - a model defined in Swagger """ self._affiliate_click_oid = None self._affiliate_link_oid = None self._affiliate_oid = None self._click_dts = None self._ip_address = None self._landing_page = None self._landing_page_query_string = None self._link = None self._referrer = None self._referrer_query_string = None self._sub_id = None self.discriminator = None if affiliate_click_oid is not None: self.affiliate_click_oid = affiliate_click_oid if affiliate_link_oid is not None: self.affiliate_link_oid = affiliate_link_oid if affiliate_oid is not None: self.affiliate_oid = affiliate_oid if click_dts is not None: self.click_dts = click_dts if ip_address is not None: self.ip_address = ip_address if landing_page is not None: self.landing_page = landing_page if landing_page_query_string is not None: self.landing_page_query_string = landing_page_query_string if link is not None: self.link = link if referrer is not None: self.referrer = referrer if referrer_query_string is not None: self.referrer_query_string = referrer_query_string if sub_id is not None: self.sub_id = sub_id @property def affiliate_click_oid(self): """ Gets the affiliate_click_oid of this AffiliateClick. Unique object identifier for this click :return: The affiliate_click_oid of this AffiliateClick. :rtype: int """ return self._affiliate_click_oid @affiliate_click_oid.setter def affiliate_click_oid(self, affiliate_click_oid): """ Sets the affiliate_click_oid of this AffiliateClick. Unique object identifier for this click :param affiliate_click_oid: The affiliate_click_oid of this AffiliateClick. :type: int """ self._affiliate_click_oid = affiliate_click_oid @property def affiliate_link_oid(self): """ Gets the affiliate_link_oid of this AffiliateClick. Unique object identifier for for the link that this click is associated with :return: The affiliate_link_oid of this AffiliateClick. :rtype: int """ return self._affiliate_link_oid @affiliate_link_oid.setter def affiliate_link_oid(self, affiliate_link_oid): """ Sets the affiliate_link_oid of this AffiliateClick. Unique object identifier for for the link that this click is associated with :param affiliate_link_oid: The affiliate_link_oid of this AffiliateClick. :type: int """ self._affiliate_link_oid = affiliate_link_oid @property def affiliate_oid(self): """ Gets the affiliate_oid of this AffiliateClick. Affiliate object ID associated with this click :return: The affiliate_oid of this AffiliateClick. :rtype: int """ return self._affiliate_oid @affiliate_oid.setter def affiliate_oid(self, affiliate_oid): """ Sets the affiliate_oid of this AffiliateClick. Affiliate object ID associated with this click :param affiliate_oid: The affiliate_oid of this AffiliateClick. :type: int """ self._affiliate_oid = affiliate_oid @property def click_dts(self): """ Gets the click_dts of this AffiliateClick. Date/time that the click was made :return: The click_dts of this AffiliateClick. :rtype: str """ return self._click_dts @click_dts.setter def click_dts(self, click_dts): """ Sets the click_dts of this AffiliateClick. Date/time that the click was made :param click_dts: The click_dts of this AffiliateClick. :type: str """ self._click_dts = click_dts @property def ip_address(self): """ Gets the ip_address of this AffiliateClick. IP address that generated the click :return: The ip_address of this AffiliateClick. :rtype: str """ return self._ip_address @ip_address.setter def ip_address(self, ip_address): """ Sets the ip_address of this AffiliateClick. IP address that generated the click :param ip_address: The ip_address of this AffiliateClick. :type: str """ self._ip_address = ip_address @property def landing_page(self): """ Gets the landing_page of this AffiliateClick. URL of the landing page the customer was sent to. :return: The landing_page of this AffiliateClick. :rtype: str """ return self._landing_page @landing_page.setter def landing_page(self, landing_page): """ Sets the landing_page of this AffiliateClick. URL of the landing page the customer was sent to. :param landing_page: The landing_page of this AffiliateClick. :type: str """ self._landing_page = landing_page @property def landing_page_query_string(self): """ Gets the landing_page_query_string of this AffiliateClick. Query string on the landing page URL the customer was sent to. :return: The landing_page_query_string of this AffiliateClick. :rtype: str """ return self._landing_page_query_string @landing_page_query_string.setter def landing_page_query_string(self, landing_page_query_string): """ Sets the landing_page_query_string of this AffiliateClick. Query string on the landing page URL the customer was sent to. :param landing_page_query_string: The landing_page_query_string of this AffiliateClick. :type: str """ self._landing_page_query_string = landing_page_query_string @property def link(self): """ Gets the link of this AffiliateClick. :return: The link of this AffiliateClick. :rtype: AffiliateLink """ return self._link @link.setter def link(self, link): """ Sets the link of this AffiliateClick. :param link: The link of this AffiliateClick. :type: AffiliateLink """ self._link = link @property def referrer(self): """ Gets the referrer of this AffiliateClick. URL that referred the click (Browser Header Referer) :return: The referrer of this AffiliateClick. :rtype: str """ return self._referrer @referrer.setter def referrer(self, referrer): """ Sets the referrer of this AffiliateClick. URL that referred the click (Browser Header Referer) :param referrer: The referrer of this AffiliateClick. :type: str """ self._referrer = referrer @property def referrer_query_string(self): """ Gets the referrer_query_string of this AffiliateClick. Query string that was on the referrer URL. :return: The referrer_query_string of this AffiliateClick. :rtype: str """ return self._referrer_query_string @referrer_query_string.setter def referrer_query_string(self, referrer_query_string): """ Sets the referrer_query_string of this AffiliateClick. Query string that was on the referrer URL. :param referrer_query_string: The referrer_query_string of this AffiliateClick. :type: str """ self._referrer_query_string = referrer_query_string @property def sub_id(self): """ Gets the sub_id of this AffiliateClick. Sub ID value passed on the click :return: The sub_id of this AffiliateClick. :rtype: str """ return self._sub_id @sub_id.setter def sub_id(self, sub_id): """ Sets the sub_id of this AffiliateClick. Sub ID value passed on the click :param sub_id: The sub_id of this AffiliateClick. :type: str """ self._sub_id = sub_id def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, AffiliateClick): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
IUST-DMLab/farsbase
raw/nlp-utils/src/main/java/ir/ac/iust/dml/kg/raw/extractor/FilterType.java
/* * Farsi Knowledge Graph Project * Iran University of Science and Technology (Year 2017) * Developed by <NAME>. */ package ir.ac.iust.dml.kg.raw.extractor; public enum FilterType { CommonPosTags, CommonPosTagsStrict, AnyResources, Things, Properties, Villages, Ambiguities, NotMatchedLabels, EmptyClassTree, NotNullDisambiguatedFrom, FilteredWords, TelevisionShows, Films, MusicalWorks }
jeroennelis/VR_engine
VR Engine/src/TexturedModel.cpp
<gh_stars>0 #include "TexturedModel.h" TexturedModel::TexturedModel(RawModel *model, ModelTexture *texture) :m_RawModel(model), m_Texture(texture) { } TexturedModel::~TexturedModel() { //delete m_RawModel; //delete m_Texture; }
HeyItsFelipe/PracticeProblems
LeetCode/Medium/maxIncreaseKeepCitySkyline.js
/* https://leetcode.com/problems/max-increase-to-keep-city-skyline/ In a 2 dimensional array grid, each value grid[i][j] represents the height of a building located there. We are allowed to increase the height of any number of buildings, by any amount (the amounts can be different for different buildings). Height 0 is considered to be a building as well. At the end, the "skyline" when viewed from all four directions of the grid, i.e. top, bottom, left, and right, must be the same as the skyline of the original grid. A city's skyline is the outer contour of the rectangles formed by all the buildings when viewed from a distance. See the following example. What is the maximum total sum that the height of the buildings can be increased? Example: Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]] Output: 35 Explanation: The grid is: [ [3, 0, 8, 4], [2, 4, 5, 7], [9, 2, 6, 3], [0, 3, 1, 0] ] The skyline viewed from top or bottom is: [9, 4, 8, 7] The skyline viewed from left or right is: [8, 7, 9, 3] The grid after increasing the height of buildings without affecting skylines is: gridNew = [ [8, 4, 8, 7], [7, 4, 7, 7], [9, 4, 8, 7], [3, 3, 3, 3] ] Notes: 1 < grid.length = grid[0].length <= 50. All heights grid[i][j] are in the range [0, 100]. All buildings in grid[i][j] occupy the entire grid cell: that is, they are a 1 x 1 x grid[i][j] rectangular prism. */ const maxIncreaseKeepingSkyline = grid => { let largestInCol = []; for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[i].length; j++) { if (!largestInCol[j]) { largestInCol[j] = grid[i][j]; } if (grid[i][j] > largestInCol[j]) { largestInCol[j] = grid[i][j]; } } } let largestInRow = []; for (let i = 0; i < grid.length; i++) { largestInRow[i] = Math.max(...grid[i]); } let sum = 0; for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[i].length; j++) { let min = Math.min(largestInCol[j], largestInRow[i]); if (grid[i][j] < min) { sum += min - grid[i][j]; } } } return sum; }; console.log(maxIncreaseKeepingSkyline([[3, 0, 8, 4], [2, 4, 5, 7], [9, 2, 6, 3], [0, 3, 1, 0]])); /* We use Math.min and Math.max, so we have to keep that in mind when analyzing time complexity. Max.max here is used with a linear complexity as it looks through an array of a certain length. Max.min only analyzes two values at a time so it can be concluded to be constant. Considering the above statments we can say we use 3 nested for loops. Therefore this function is quadratic. In terms of the grid (nxm), time complexity will be 3(n x m). */
cityssm/corporate-records-manager
helpers/recordsDB/updateStatus.js
import * as sqlPool from "@cityssm/mssql-multi-pool"; import * as configFns from "../configFns.js"; import debug from "debug"; const debugSQL = debug("corporate-records-manager:recordsDB:updateStatus"); export const updateStatus = async (statusForm, requestSession) => { try { const pool = await sqlPool.connect(configFns.getProperty("mssqlConfig")); const statusTime = new Date(statusForm.statusDateString + " " + statusForm.statusTimeString); await pool.request() .input("statusTypeKey", statusForm.statusTypeKey) .input("statusTime", statusTime) .input("statusLog", statusForm.statusLog) .input("recordUpdate_userName", requestSession.user.userName) .input("recordUpdate_datetime", new Date()) .input("statusLogID", statusForm.statusLogID) .query("update CR.RecordStatusLog" + " set statusTypeKey = @statusTypeKey," + " statusTime = @statusTime," + " statusLog = @statusLog," + " recordUpdate_userName = @recordUpdate_userName," + " recordUpdate_datetime = @recordUpdate_datetime" + " where statusLogID = @statusLogID" + " and recordDelete_datetime is null"); return true; } catch (error) { debugSQL(error); } return false; }; export default updateStatus;
nattaponaie/Intelligent-Tutoring-System-for-Situated-Decision-Making-in-Dental-Surgery
app/src/main/java/com/surgical/decision3/common/bean/procedure/BaseProcedure.java
<gh_stars>0 package com.surgical.decision3.common.bean.procedure; import org.simpleframework.xml.Attribute; import org.simpleframework.xml.Root; @Root public class BaseProcedure { public BaseProcedure() { super(); } public BaseProcedure( int id, String name, String code, String desc ) { super(); this.id = id; this.name = name; this.code = code; this.description = desc; } @Attribute private int id; @Attribute (required=false) private String name; @Attribute (required=false) private String code; @Attribute (required=false) private String description; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
kosinaz/Rot-Magus
src/world/director.js
// eslint-disable-next-line no-unused-vars import WorldMap from './worldMap.js'; // eslint-disable-next-line no-unused-vars import Troupe from './troupe.js'; import PreciseShadowcasting from '../../lib/rot/fov/precise-shadowcasting.js'; import AStar from '../../lib/rot/path/astar.js'; export default class Director { /** * Creates an instance of Director. * @param {WorldMap} map * @param {Troupe} actors * @memberof Director */ constructor(map, actors) { this.map = map; this.actors = actors; this.viewUpdater = new PreciseShadowcasting((x, y) => { if (actors.hasPCAt(x, y)) return true; return map.isTransparentAt(x, y); }); } direct(actor) { actor.clearView(); this.viewUpdater.compute(actor.x, actor.y, 10, actor.addToView.bind(actor)); this.actors.updateView(); if (actor.isPC) this.directPC(actor); else this.directNPC(actor); } directPC(pc) { this.map.updateVisibility(this.actors.view); // The world will stop if the player character doesn't have any actions // left from their last order to let the player give another order. // Otherwise the player character will scan their surroundings for enemies // or newly discovered items, and the world will stop just like in the // other case, if there is any. // However, if there is none, there is no reason for the player character // not to continue towards their target, so the game won't stop and won't // reveal anything until any of the above conditions are true again. if (pc.hasOrder && !this.actors.hasVisibleNPC) this.followOrder(pc); else this.waitForOrder(pc); } followOrder(actor) { if (actor.hasOrder) { const xy = actor.orders.shift(); actor.xy = xy; actor.events.emit('move'); actor.waiting = false; } this.direct(this.actors.getNext()); } waitForOrder(pc) { this.actors.updateVisibility(); pc.wait(); this.actors.select(pc); } directNPC(npc) { const pc = npc.view.filter(xy => this.actors.hasPCAt(xy))[0]; if (pc) this.giveOrder(npc, pc); this.followOrder(npc); } /** * Give the actor an order. * * @param {*} actor * @param {*} x * @param {*} y * @memberof Actor */ giveOrder(actor, xy) { xy = xy.split(','); const x = parseInt(xy[0], 10); const y = parseInt(xy[1], 10); // Initialize a new astar pathmap based on the given target. const a = new AStar(x, y, (x, y) => { if (actor.isAt(`${x},${y}`)) return true; return this.map.isWalkableAt(x, y); }); // After generated the pathmap create a new path for the actor. actor.orders = []; // Compute the shortest path between the actor's current position and the // given target position based on the astar map. a.compute(actor.x, actor.y, (x, y) => actor.orders.push({x, y})); // Remove the first order, because that's current position of the actor. actor.orders.shift(); } }
SIEGE/siege
src/examples/shadow.c
<filename>src/examples/shadow.c #include <siege/siege.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <math.h> #define NSHAPES 3 #define NLIGHTS 4 SGLightSpace* space; SGShadowShape* shapes[NSHAPES]; SGLight* lights[NLIGHTS]; SGSurface* lightBuf; SGLight* createLight(SGVec2 pos, SGColor color, float radius, float angle, float arc) { SGLight* light = sgLightCreate(space, pos.x, pos.y, radius); sgLightSetColor4f(light, color.r, color.g, color.b, color.a); sgLightSetAngleDegs(light, angle); sgLightSetConeDegs(light, arc); return light; } // SG_TRUE if they should be mulplicative, SG_FALSE for additive! SGbool multLights = SG_TRUE; SGbool sqrmult = SG_TRUE; SGbool overlayDBG = SG_FALSE; SGSprite* tile; SGSurface* tileset; void evTick(SGEntity* ent) { sgLightSpaceUpdate(space); lights[0]->pos.x = sgMouseGetPosX(); lights[0]->pos.y = sgMouseGetPosY(); } void evDraw(SGEntity* ent) { sgDrawColor4f(1.0, 1.0, 1.0, 1.0); sgSurfaceDraw(tileset); size_t i; for(i = 0; i < NSHAPES; i++) sgShadowShapeDrawDBG(shapes[i], SG_TRUE); for(i = 0; i < NSHAPES; i++) sgShadowShapeDrawDBG(shapes[i], SG_FALSE); sgDrawColor4f(1.0, 1.0, 1.0, 1.0); sgLightSpaceDraw(space, (multLights ? SG_SHADOW_DRAW_MUL : 0) | (sqrmult ? SG_SHADOW_DRAW_SQR : 0)); //sgDrawSetBlendFunc(SG_GRAPHICS_FUNC_SRC_ALPHA, SG_GRAPHICS_FUNC_ONE_MINUS_SRC_ALPHA); if(overlayDBG) sgLightSpaceDrawDBG(space, 0); } void evKeyboardKeyPress(SGEntity* ent, SGenum key) { switch(key) { case SG_KEY_F1: overlayDBG = !overlayDBG; break; default: if('1' <= key && key <= '9') { if(key - '1' < NLIGHTS) sgLightSetActive(lights[key - '1'], !sgLightGetActive(lights[key - '1'])); } break; } } int main(void) { sgInit(/*SG_INIT_RENDERTHREAD*/0); sgWindowOpen(640, 480, 32, 0); sgWindowSetTitlef("SIEGE Shadows Demo - Press F1 for debug overlay, 1-%u to toggle lights", NLIGHTS); sgWindowSetFPSLimit(60.0); space = sgLightSpaceCreate(0, 0); sgLightSpaceSetAmbience4f(space, 0.125, 0.0625, 0.0, 1.0); SGEntity* handler = sgEntityCreate(); handler->evTick = evTick; handler->evDraw = evDraw; handler->evKeyboardKeyPress = evKeyboardKeyPress; tile = sgSpriteCreateFile2f("data/sprites/FloorMetalPlate.png", 0.0, 0.0); tileset = sgSurfaceCreate(640, 480, 32); size_t i, j; sgSurfaceClear(tileset); sgDrawColor4f(1.0, 1.0, 1.0, 1.0); sgSurfaceTarget(tileset); for(i = 0; i <= 640 / sgSpriteGetWidth(tile); i++) for(j = 0; j <= 480 / sgSpriteGetHeight(tile); j++) sgSpriteDraw2f(tile, i * sgSpriteGetWidth(tile), j * sgSpriteGetHeight(tile)); sgSurfaceUntarget(tileset); shapes[0] = sgShadowShapeCreatePoly(space, 0, 0, (float[]){200, 250 ,400, 250 ,375, 350 ,225, 350}, 4); shapes[1] = sgShadowShapeCreatePoly(space, 0, 0, (float[]){100, 50 ,200, 50 ,200, 150 ,100, 150}, 4); shapes[2] = sgShadowShapeCreatePoly(space, 0, 0, (float[]){400, 100 ,500, 100 ,450, 200}, 3); lights[0] = createLight((SGVec2){60 , 60 }, (SGColor){0.5 , 1.0, 1.0, 1.0}, 192, 0, 360); lights[1] = createLight((SGVec2){500, 300}, (SGColor){0.75, 1.0, 0.0, 0.5}, 256, 0, 360); lights[2] = createLight((SGVec2){200, 400}, (SGColor){1.0 , 0.5, 0.0, 1.0}, 128, 0, 360); lights[3] = createLight((SGVec2){50 , 50 }, (SGColor){1.0 , 1.0, 1.0, 1.0}, 320, 45, 60); SGint ret = sgRun(); sgSurfaceDestroy(tileset); sgSpriteDestroy(tile); sgLightSpaceDestroy(space); sgDeinit(); return ret; }
MingAtUWA/SimpleMPM2
SimulationCore/Step_T2D_CHM_s.h
#ifndef __Step_T2D_CHM_s_H__ #define __Step_T2D_CHM_s_H__ #include "Step.h" #include "Model_T2D_CHM_s.h" int solve_substep_T2D_CHM_s(void *_self); // for single object only class Step_T2D_CHM_s : public Step { public: typedef Model_T2D_CHM_s::Particle Particle; typedef Model_T2D_CHM_s::Element Element; typedef Model_T2D_CHM_s::Node Node; protected: int init_calculation(void) override; friend int solve_substep_T2D_CHM_s(void *_self); int finalize_calculation(void) override; public: Step_T2D_CHM_s(); ~Step_T2D_CHM_s(); inline void set_model(Model_T2D_CHM_s &md) { Step::set_model(md); model = &md; } // Restart from previous step inline void set_prev_step(Step_T2D_CHM_s &prev_step) { Step::set_prev_step(prev_step); model = prev_step.model; } inline void set_dtime(double _dt, double dt_max_min_raio = 0.1 /*ad hoc number*/, double t_tol_r = 0.01) { max_dt = _dt; min_dt = max_dt * dt_max_min_raio; time_tol_ratio = t_tol_r; time_tol = min_dt * t_tol_r; dtime = max_dt; } inline void set_damping_ratio(double ra) noexcept { damping_ratio = ra; } inline void set_bv_ratio(double ra) noexcept { bv_ratio = ra; } protected: Model_T2D_CHM_s *model; double min_dt, max_dt; double damping_ratio; // local damping double bv_ratio; // bulk viscosity damping ratio, should be ?? }; #endif
lechium/tvOS10Headers
System/Library/PrivateFrameworks/Memories.framework/MiroSmartMusicUtilities.h
<reponame>lechium/tvOS10Headers /* * This header is generated by classdump-dyld 1.0 * on Wednesday, March 22, 2017 at 9:09:31 AM Mountain Standard Time * Operating System: Version 10.1 (Build 14U593) * Image Source: /System/Library/PrivateFrameworks/Memories.framework/Memories * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <Memories/Memories-Structs.h> @interface MiroSmartMusicUtilities : NSObject +(double)normalizeGainForRendition:(id)arg1 ; +(id)metadataItemAtTime:(SCD_Struct_Mi1)arg1 fromMetadataItems:(id)arg2 findNearest:(BOOL)arg3 ; +(id)beatMetadataItemForBeatIndex:(long long)arg1 andBarIndex:(long long)arg2 nearBeatMetadataItem:(id)arg3 fromBeatMetadataItems:(id)arg4 ; +(id)_peakAndLoudnessForRendition:(id)arg1 ; +(id)metadataItemAtTime:(SCD_Struct_Mi1)arg1 fromMetadataItems:(id)arg2 ; +(double)averageBarDurationForFlexAudioClipInSeconds:(id)arg1 ; +(SCD_Struct_Mi1)averageBarDurationForFlexAudioClip:(id)arg1 ; +(SCD_Struct_Mi1)durationOfOutroForFlexAudioClip:(id)arg1 ; +(SCD_Struct_Mi1)durationOfIntroForFlexAudioClip:(id)arg1 ; @end
perfectrecall/aws-sdk-cpp
aws-cpp-sdk-glue/include/aws/glue/model/OtherMetadataValueListItem.h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/glue/Glue_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace Glue { namespace Model { /** * <p>A structure containing other metadata for a schema version belonging to the * same metadata key.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/OtherMetadataValueListItem">AWS * API Reference</a></p> */ class AWS_GLUE_API OtherMetadataValueListItem { public: OtherMetadataValueListItem(); OtherMetadataValueListItem(Aws::Utils::Json::JsonView jsonValue); OtherMetadataValueListItem& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The metadata key’s corresponding value for the other metadata belonging to * the same metadata key.</p> */ inline const Aws::String& GetMetadataValue() const{ return m_metadataValue; } /** * <p>The metadata key’s corresponding value for the other metadata belonging to * the same metadata key.</p> */ inline bool MetadataValueHasBeenSet() const { return m_metadataValueHasBeenSet; } /** * <p>The metadata key’s corresponding value for the other metadata belonging to * the same metadata key.</p> */ inline void SetMetadataValue(const Aws::String& value) { m_metadataValueHasBeenSet = true; m_metadataValue = value; } /** * <p>The metadata key’s corresponding value for the other metadata belonging to * the same metadata key.</p> */ inline void SetMetadataValue(Aws::String&& value) { m_metadataValueHasBeenSet = true; m_metadataValue = std::move(value); } /** * <p>The metadata key’s corresponding value for the other metadata belonging to * the same metadata key.</p> */ inline void SetMetadataValue(const char* value) { m_metadataValueHasBeenSet = true; m_metadataValue.assign(value); } /** * <p>The metadata key’s corresponding value for the other metadata belonging to * the same metadata key.</p> */ inline OtherMetadataValueListItem& WithMetadataValue(const Aws::String& value) { SetMetadataValue(value); return *this;} /** * <p>The metadata key’s corresponding value for the other metadata belonging to * the same metadata key.</p> */ inline OtherMetadataValueListItem& WithMetadataValue(Aws::String&& value) { SetMetadataValue(std::move(value)); return *this;} /** * <p>The metadata key’s corresponding value for the other metadata belonging to * the same metadata key.</p> */ inline OtherMetadataValueListItem& WithMetadataValue(const char* value) { SetMetadataValue(value); return *this;} /** * <p>The time at which the entry was created.</p> */ inline const Aws::String& GetCreatedTime() const{ return m_createdTime; } /** * <p>The time at which the entry was created.</p> */ inline bool CreatedTimeHasBeenSet() const { return m_createdTimeHasBeenSet; } /** * <p>The time at which the entry was created.</p> */ inline void SetCreatedTime(const Aws::String& value) { m_createdTimeHasBeenSet = true; m_createdTime = value; } /** * <p>The time at which the entry was created.</p> */ inline void SetCreatedTime(Aws::String&& value) { m_createdTimeHasBeenSet = true; m_createdTime = std::move(value); } /** * <p>The time at which the entry was created.</p> */ inline void SetCreatedTime(const char* value) { m_createdTimeHasBeenSet = true; m_createdTime.assign(value); } /** * <p>The time at which the entry was created.</p> */ inline OtherMetadataValueListItem& WithCreatedTime(const Aws::String& value) { SetCreatedTime(value); return *this;} /** * <p>The time at which the entry was created.</p> */ inline OtherMetadataValueListItem& WithCreatedTime(Aws::String&& value) { SetCreatedTime(std::move(value)); return *this;} /** * <p>The time at which the entry was created.</p> */ inline OtherMetadataValueListItem& WithCreatedTime(const char* value) { SetCreatedTime(value); return *this;} private: Aws::String m_metadataValue; bool m_metadataValueHasBeenSet; Aws::String m_createdTime; bool m_createdTimeHasBeenSet; }; } // namespace Model } // namespace Glue } // namespace Aws
jhump/hyper-redis
src/com/bluegosling/redis/concurrent/CompletableFutureCallback.java
package com.bluegosling.redis.concurrent; /** * A future that also implements {@link Callback}, whose methods can be used to complete the * future. * * @author <NAME> (<EMAIL>) * * @param <T> the type of future value */ public class CompletableFutureCallback<T> extends CompletableFuture<T> implements Callback<T> { @Override public void onSuccess(T t) { complete(t); } @Override public void onFailure(Throwable th) { completeExceptionally(th); } }
timmartin19/turbogears
turbogears/identity/saprovider.py
<filename>turbogears/identity/saprovider.py from sqlalchemy.orm import class_mapper from turbogears import config, identity from turbogears.database import session from turbogears.util import load_class import logging log = logging.getLogger("turbogears.identity.saprovider") try: set, frozenset except NameError: # Python 2.3 from sets import Set as set, ImmutableSet as frozenset # Global class references -- # these will be set when the provider is initialized. user_class = None group_class = None permission_class = None visit_class = None class SqlAlchemyIdentity(object): """Identity that uses a model from a database (via SQLAlchemy).""" def __init__(self, visit_key=None, user=None): self.visit_key = visit_key if user: self._user = user if visit_key is not None: self.login() def _get_user(self): """Get user instance for this identity.""" try: return self._user except AttributeError: # User hasn't already been set pass # Attempt to load the user. After this code executes, there *will* be # a _user attribute, even if the value is None. visit = self.visit_link self._user = visit and user_class.query.get(visit.user_id) return self._user user = property(_get_user) def _get_user_name(self): """Get user name of this identity.""" if not self.user: return None return self.user.user_name user_name = property(_get_user_name) def _get_user_id(self): """Get user id of this identity.""" if not self.user: return None return self.user.user_id user_id = property(_get_user_id) def _get_anonymous(self): """Return true if not logged in.""" return not self.user anonymous = property(_get_anonymous) def _get_permissions(self): """Get set of permission names of this identity.""" try: return self._permissions except AttributeError: # Permissions haven't been computed yet pass if not self.user: self._permissions = frozenset() else: self._permissions = frozenset( [p.permission_name for p in self.user.permissions]) return self._permissions permissions = property(_get_permissions) def _get_groups(self): """Get set of group names of this identity.""" try: return self._groups except AttributeError: # Groups haven't been computed yet pass if not self.user: self._groups = frozenset() else: self._groups = frozenset([g.group_name for g in self.user.groups]) return self._groups groups = property(_get_groups) def _get_group_ids(self): """Get set of group IDs of this identity.""" try: return self._group_ids except AttributeError: # Groups haven't been computed yet pass if not self.user: self._group_ids = frozenset() else: self._group_ids = frozenset([g.group_id for g in self.user.groups]) return self._group_ids group_ids = property(_get_group_ids) def _get_visit_link(self): """Get the visit link to this identity.""" if self.visit_key is None: return None return visit_class.query.filter_by(visit_key=self.visit_key).first() visit_link = property(_get_visit_link) def _get_login_url(self): """Get the URL for the login page.""" return identity.get_failure_url() login_url = property(_get_login_url) def login(self): """Set the link between this identity and the visit.""" visit = self.visit_link if visit: visit.user_id = self._user.user_id else: visit = visit_class() visit.visit_key = self.visit_key visit.user_id = self._user.user_id session.flush() def logout(self): """Remove the link between this identity and the visit.""" visit = self.visit_link if visit: session.delete(visit) session.flush() # Clear the current identity identity.set_current_identity(SqlAlchemyIdentity()) class SqlAlchemyIdentityProvider(object): """IdentityProvider that uses a model from a database (via SQLAlchemy).""" def __init__(self): super(SqlAlchemyIdentityProvider, self).__init__() get = config.get global user_class, group_class, permission_class, visit_class user_class_path = get("identity.saprovider.model.user", None) user_class = load_class(user_class_path) group_class_path = get("identity.saprovider.model.group", None) group_class = load_class(group_class_path) permission_class_path = get( "identity.saprovider.model.permission", None) permission_class = load_class(permission_class_path) visit_class_path = get("identity.saprovider.model.visit", None) log.info("Loading: %s", visit_class_path) visit_class = load_class(visit_class_path) # Default encryption algorithm is to use plain text passwords algorithm = get("identity.saprovider.encryption_algorithm", None) self.encrypt_password = lambda pw: \ identity._encrypt_password(algorithm, pw) def create_provider_model(self): """Create the database tables if they don't already exist.""" class_mapper(user_class).local_table.create(checkfirst=True) class_mapper(group_class).local_table.create(checkfirst=True) class_mapper(permission_class).local_table.create(checkfirst=True) class_mapper(visit_class).local_table.create(checkfirst=True) def validate_identity(self, user_name, password, visit_key): """Validate the identity represented by user_name using the password. Must return either None if the credentials weren't valid or an object with the following properties: user_name: original user name user: a provider dependent object (TG_User or similar) groups: a set of group names permissions: a set of permission names """ user = user_class.query.filter_by(user_name=user_name).first() if not user: log.warning("No such user: %s", user_name) return None if not self.validate_password(user, user_name, password): log.info("Passwords don't match for user: %s", user_name) return None log.info("Associating user (%s) with visit (%s)", user_name, visit_key) return SqlAlchemyIdentity(visit_key, user) def validate_password(self, user, user_name, password): """Check the user_name and password against existing credentials. Note: user_name is not used here, but is required by external password validation schemes that might override this method. If you use SqlAlchemyIdentityProvider, but want to check the passwords against an external source (i.e. PAM, LDAP, Windows domain, etc), subclass SqlAlchemyIdentityProvider, and override this method. """ return user.password == self.encrypt_password(password) def load_identity(self, visit_key): """Lookup the principal represented by user_name. Return None if there is no principal for the given user ID. Must return an object with the following properties: user_name: original user name user: a provider dependent object (TG_User or similar) groups: a set of group names permissions: a set of permission names """ return SqlAlchemyIdentity(visit_key) def anonymous_identity(self): """Return anonymous identity. Must return an object with the following properties: user_name: original user name user: a provider dependent object (TG_User or similar) groups: a set of group names permissions: a set of permission names """ return SqlAlchemyIdentity() def authenticated_identity(self, user): """Construct Identity object for users with no visit_key.""" return SqlAlchemyIdentity(user=user)