max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
|---|---|---|
1,345
|
<reponame>MaksHess/napari
import pytest
from napari._qt.widgets.qt_size_preview import (
QtFontSizePreview,
QtSizeSliderPreviewWidget,
)
@pytest.fixture
def preview_widget(qtbot):
def _preview_widget(**kwargs):
widget = QtFontSizePreview(**kwargs)
widget.show()
qtbot.addWidget(widget)
return widget
return _preview_widget
@pytest.fixture
def font_size_preview_widget(qtbot):
def _font_size_preview_widget(**kwargs):
widget = QtSizeSliderPreviewWidget(**kwargs)
widget.show()
qtbot.addWidget(widget)
return widget
return _font_size_preview_widget
# QtFontSizePreview
# ----------------------------------------------------------------------------
def test_qt_font_size_preview_defaults(preview_widget):
preview_widget()
def test_qt_font_size_preview_text(preview_widget):
text = "Some text"
widget = preview_widget(text=text)
assert widget.text() == text
widget = preview_widget()
widget.setText(text)
assert widget.text() == text
# QtSizeSliderPreviewWidget
# ----------------------------------------------------------------------------
def test_qt_size_slider_preview_widget_defaults(font_size_preview_widget):
font_size_preview_widget()
def test_qt_size_slider_preview_widget_description(font_size_preview_widget):
description = "Some text"
widget = font_size_preview_widget(description=description)
assert widget.description() == description
widget = font_size_preview_widget()
widget.setDescription(description)
assert widget.description() == description
def test_qt_size_slider_preview_widget_unit(font_size_preview_widget):
unit = "EM"
widget = font_size_preview_widget(unit=unit)
assert widget.unit() == unit
widget = font_size_preview_widget()
widget.setUnit(unit)
assert widget.unit() == unit
def test_qt_size_slider_preview_widget_preview(font_size_preview_widget):
preview = "Some preview"
widget = font_size_preview_widget(preview_text=preview)
assert widget.previewText() == preview
widget = font_size_preview_widget()
widget.setPreviewText(preview)
assert widget.previewText() == preview
def test_qt_size_slider_preview_widget_minimum(font_size_preview_widget):
minimum = 10
widget = font_size_preview_widget(min_value=minimum)
assert widget.minimum() == minimum
assert widget.value() >= minimum
widget = font_size_preview_widget()
widget.setMinimum(5)
assert widget.minimum() == 5
assert widget._slider.minimum() == 5
assert widget._slider_min_label.text() == "5"
widget.setMinimum(20)
assert widget.minimum() == 20
assert widget.value() == 20
assert widget._slider.minimum() == 20
assert widget._slider_min_label.text() == "20"
assert widget._lineedit.text() == "20"
def test_qt_size_slider_preview_widget_minimum_invalid(
font_size_preview_widget,
):
widget = font_size_preview_widget()
with pytest.raises(ValueError):
widget.setMinimum(60)
def test_qt_size_slider_preview_widget_maximum(font_size_preview_widget):
maximum = 10
widget = font_size_preview_widget(max_value=maximum)
assert widget.maximum() == maximum
assert widget.value() <= maximum
widget = font_size_preview_widget()
widget.setMaximum(20)
assert widget.maximum() == 20
assert widget._slider.maximum() == 20
assert widget._slider_max_label.text() == "20"
widget.setMaximum(5)
assert widget.maximum() == 5
assert widget.value() == 5
assert widget._slider.maximum() == 5
assert widget._lineedit.text() == "5"
assert widget._slider_max_label.text() == "5"
def test_qt_size_slider_preview_widget_maximum_invalid(
font_size_preview_widget,
):
widget = font_size_preview_widget()
with pytest.raises(ValueError):
widget.setMaximum(-5)
def test_qt_size_slider_preview_widget_value(font_size_preview_widget):
widget = font_size_preview_widget(value=5)
assert widget.value() <= 5
widget = font_size_preview_widget()
widget.setValue(5)
assert widget.value() == 5
def test_qt_size_slider_preview_widget_value_invalid(
qtbot, font_size_preview_widget
):
widget = font_size_preview_widget()
widget.setMaximum(50)
widget.setValue(51)
assert widget.value() == 50
assert widget._lineedit.text() == "50"
widget.setMinimum(5)
widget.setValue(1)
assert widget.value() == 5
assert widget._lineedit.text() == "5"
def test_qt_size_slider_preview_signal(qtbot, font_size_preview_widget):
widget = font_size_preview_widget()
with qtbot.waitSignal(widget.valueChanged, timeout=500):
widget.setValue(7)
with qtbot.waitSignal(widget.valueChanged, timeout=500):
widget.setValue(-5)
| 1,771
|
1,467
|
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef IROHA_AMETSUCHI_COMMIT_RESULT_HPP
#define IROHA_AMETSUCHI_COMMIT_RESULT_HPP
#include <memory>
#include <string>
#include "ametsuchi/ledger_state.hpp"
#include "common/result.hpp"
namespace iroha {
namespace ametsuchi {
using CommitResult =
iroha::expected::Result<std::shared_ptr<const iroha::LedgerState>,
std::string>;
}
} // namespace iroha
#endif // IROHA_AMETSUCHI_COMMIT_RESULT_HPP
| 245
|
2,151
|
/* Copyright (c) 2002-2008 Sun Microsystems, Inc. All rights reserved
*
* This program is distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
package org.pantsbuild.jmake;
/**
* Basic operations for writing to a byte array representing a binary file.
*
* @author <NAME>
* 30 January 2002
*/
public class BinaryFileWriter {
protected byte[] buf;
protected int curBufSize, bufInc, curBufPos, threshold;
private boolean bufferIncreaseAllowed = true;
protected void initBuf(int initSize) {
buf = new byte[initSize];
curBufSize = initSize;
bufInc = initSize / 5;
curBufPos = 0;
threshold = curBufSize - bufInc;
}
protected void increaseBuf() {
if (!bufferIncreaseAllowed) {
return;
}
byte newBuf[] = new byte[curBufSize + bufInc];
System.arraycopy(buf, 0, newBuf, 0, curBufPos);
buf = newBuf;
curBufSize = buf.length;
threshold = curBufSize - bufInc;
}
// This should be called with false only when we are sure that we set the exact size of the buffer
// and there is no need to increase it.
protected void setBufferIncreaseMode(boolean increaseMode) {
bufferIncreaseAllowed = increaseMode;
}
public byte[] getBuffer() {
return buf;
}
protected void writeByte(byte b) {
if (curBufPos > threshold) {
increaseBuf();
}
buf[curBufPos++] = b;
}
protected void writeChar(int ch) {
buf[curBufPos++] = (byte) ((ch >> 8) & 255);
buf[curBufPos++] = (byte) (ch & 255);
if (curBufPos > threshold) {
increaseBuf();
}
}
protected void writeInt(int i) {
buf[curBufPos++] = (byte) ((i >> 24) & 255);
buf[curBufPos++] = (byte) ((i >> 16) & 255);
buf[curBufPos++] = (byte) ((i >> 8) & 255);
buf[curBufPos++] = (byte) (i & 255);
if (curBufPos > threshold) {
increaseBuf();
}
}
protected void writeLong(long l) {
buf[curBufPos++] = (byte) ((l >> 56) & 255);
buf[curBufPos++] = (byte) ((l >> 48) & 255);
buf[curBufPos++] = (byte) ((l >> 40) & 255);
buf[curBufPos++] = (byte) ((l >> 32) & 255);
buf[curBufPos++] = (byte) ((l >> 24) & 255);
buf[curBufPos++] = (byte) ((l >> 16) & 255);
buf[curBufPos++] = (byte) ((l >> 8) & 255);
buf[curBufPos++] = (byte) (l & 255);
if (curBufPos > threshold) {
increaseBuf();
}
}
protected void writeFloat(float f) {
int i = Float.floatToIntBits(f);
writeInt(i);
}
protected void writeDouble(double d) {
long l = Double.doubleToLongBits(d);
writeLong(l);
}
}
| 1,272
|
2,542
|
<filename>src/prod/src/Store/ScopedActiveBackupState.cpp
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace Common;
using namespace std;
namespace Store
{
namespace StoreBackupRequester
{
void WriteToTextWriter(__in TextWriter & w, Enum const & e)
{
switch (e)
{
case User: w << "User"; return;
case LogTruncation: w << "LogTruncation"; return;
case System: w << "System"; return;
default: w << "StoreBackupRequester(" << static_cast<ULONG>(e) << ')'; return;
}
}
bool IsValid(Enum const & e)
{
return (e == User || e == LogTruncation || e == System);
}
}
ScopedActiveBackupState::ScopedActiveBackupState(
__in StoreBackupState & activeBackupState,
LONG desiredBackupState)
: activeBackupState_(activeBackupState)
{
hasAcquired_ = activeBackupState_.TryAcquire(desiredBackupState, backupStateIfNotAcquired_);
}
ScopedActiveBackupState::~ScopedActiveBackupState()
{
if (hasAcquired_)
{
activeBackupState_.Release();
}
}
bool ScopedActiveBackupState::TryAcquire(
__in StoreBackupState & activeBackupState,
__in StoreBackupRequester::Enum const & backupRequester,
__out ScopedActiveBackupStateSPtr & scopedBackupState)
{
ASSERT_IFNOT(StoreBackupRequester::IsValid(backupRequester), "ScopedActiveBackupState::TryAcquire(): Invalid value for backupRequester=[{0}]", backupRequester);
LONG desiredState = -1;
switch (backupRequester)
{
case StoreBackupRequester::User:
desiredState = StoreBackupState::ActiveByUser; break;
case StoreBackupRequester::LogTruncation:
desiredState = StoreBackupState::ActiveByLogTruncation; break;
case StoreBackupRequester::System:
desiredState = StoreBackupState::ActiveBySystem; break;
}
scopedBackupState = ScopedActiveBackupStateSPtr(new ScopedActiveBackupState(activeBackupState, desiredState));
return scopedBackupState->hasAcquired_;
}
}
| 1,005
|
777
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/login/auth/extended_authenticator.h"
#include "chromeos/login/auth/extended_authenticator_impl.h"
namespace chromeos {
// static
scoped_refptr<ExtendedAuthenticator> ExtendedAuthenticator::Create(
NewAuthStatusConsumer* consumer) {
return make_scoped_refptr(new ExtendedAuthenticatorImpl(consumer));
}
// static
scoped_refptr<ExtendedAuthenticator> ExtendedAuthenticator::Create(
AuthStatusConsumer* consumer) {
return make_scoped_refptr(new ExtendedAuthenticatorImpl(consumer));
}
ExtendedAuthenticator::ExtendedAuthenticator() {
}
ExtendedAuthenticator::~ExtendedAuthenticator() {
}
} // namespace chromeos
| 240
|
1,144
|
<filename>backend/de.metas.edi/src/main/java/de/metas/edi/api/impl/DesadvBL.java
package de.metas.edi.api.impl;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.Multimaps;
import de.metas.bpartner.BPartnerId;
import de.metas.bpartner.BPartnerLocationAndCaptureId;
import de.metas.bpartner.BPartnerLocationId;
import de.metas.bpartner.service.IBPartnerDAO;
import de.metas.bpartner_product.IBPartnerProductDAO;
import de.metas.common.util.CoalesceUtil;
import de.metas.edi.api.EDIDesadvLinePackId;
import de.metas.edi.api.IDesadvBL;
import de.metas.edi.api.IDesadvDAO;
import de.metas.edi.model.I_C_Order;
import de.metas.edi.model.I_C_OrderLine;
import de.metas.edi.model.I_M_InOut;
import de.metas.edi.model.I_M_InOutLine;
import de.metas.esb.edi.model.I_EDI_Desadv;
import de.metas.esb.edi.model.I_EDI_DesadvLine;
import de.metas.esb.edi.model.I_EDI_DesadvLine_Pack;
import de.metas.handlingunits.HuId;
import de.metas.handlingunits.IHUAssignmentDAO;
import de.metas.handlingunits.IHUPIItemProductDAO;
import de.metas.handlingunits.allocation.ILUTUConfigurationFactory;
import de.metas.handlingunits.attribute.HUAttributeConstants;
import de.metas.handlingunits.attributes.sscc18.ISSCC18CodeBL;
import de.metas.handlingunits.attributes.sscc18.SSCC18;
import de.metas.handlingunits.generichumodel.HU;
import de.metas.handlingunits.generichumodel.HURepository;
import de.metas.handlingunits.generichumodel.PackagingCode;
import de.metas.handlingunits.inout.IHUPackingMaterialDAO;
import de.metas.handlingunits.model.I_M_HU;
import de.metas.handlingunits.model.I_M_HU_LUTU_Configuration;
import de.metas.handlingunits.model.I_M_HU_PI_Item_Product;
import de.metas.handlingunits.model.I_M_HU_PackingMaterial;
import de.metas.handlingunits.model.X_M_HU_PI_Version;
import de.metas.i18n.AdMessageKey;
import de.metas.i18n.IMsgBL;
import de.metas.i18n.ITranslatableString;
import de.metas.inout.IInOutBL;
import de.metas.inout.IInOutDAO;
import de.metas.logging.LogManager;
import de.metas.order.IOrderBL;
import de.metas.order.IOrderDAO;
import de.metas.organization.IOrgDAO;
import de.metas.organization.OrgId;
import de.metas.pricing.InvoicableQtyBasedOn;
import de.metas.process.ProcessExecutionResult;
import de.metas.process.ProcessInfo;
import de.metas.product.IProductDAO;
import de.metas.product.ProductId;
import de.metas.quantity.Quantity;
import de.metas.quantity.Quantitys;
import de.metas.quantity.StockQtyAndUOMQty;
import de.metas.quantity.StockQtyAndUOMQtys;
import de.metas.report.ReportResultData;
import de.metas.report.server.ReportConstants;
import de.metas.uom.IUOMConversionBL;
import de.metas.uom.IUOMDAO;
import de.metas.uom.UOMConversionContext;
import de.metas.uom.UomId;
import de.metas.util.Check;
import de.metas.util.Services;
import de.metas.util.collections.CollectionUtils;
import de.metas.util.lang.Percent;
import lombok.NonNull;
import org.adempiere.ad.trx.api.ITrx;
import org.adempiere.exceptions.AdempiereException;
import org.adempiere.mm.attributes.AttributeSetInstanceId;
import org.adempiere.mm.attributes.api.AttributeConstants;
import org.adempiere.mm.attributes.api.IAttributeDAO;
import org.adempiere.mm.attributes.api.ImmutableAttributeSet;
import org.adempiere.model.InterfaceWrapperHelper;
import org.compiere.model.I_C_BPartner_Product;
import org.compiere.model.I_M_Product;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.TimeUtil;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;
import javax.annotation.Nullable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.time.ZoneId;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import static de.metas.common.util.CoalesceUtil.coalesce;
import static de.metas.util.Check.isEmpty;
import static de.metas.util.Check.isNotBlank;
import static java.math.BigDecimal.ONE;
import static java.math.BigDecimal.ZERO;
import static org.adempiere.model.InterfaceWrapperHelper.create;
import static org.adempiere.model.InterfaceWrapperHelper.delete;
import static org.adempiere.model.InterfaceWrapperHelper.newInstance;
import static org.adempiere.model.InterfaceWrapperHelper.saveRecord;
@Service
public class DesadvBL implements IDesadvBL
{
private final static transient Logger logger = LogManager.getLogger(DesadvBL.class);
private static final AdMessageKey MSG_EDI_DESADV_RefuseSending = AdMessageKey.of("EDI_DESADV_RefuseSending");
/**
* Process used to print the {@link I_EDI_DesadvLine_Pack}s labels
*/
private static final String AD_PROCESS_VALUE_EDI_DesadvLine_SSCC_Print = "EDI_DesadvLine_SSCC_Print";
private final transient IInOutDAO inOutDAO = Services.get(IInOutDAO.class);
private final transient IInOutBL inOutBL = Services.get(IInOutBL.class);
private final transient IHUAssignmentDAO huAssignmentDAO = Services.get(IHUAssignmentDAO.class);
private final transient IDesadvDAO desadvDAO = Services.get(IDesadvDAO.class);
private final transient IProductDAO productDAO = Services.get(IProductDAO.class);
private final transient IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
private final transient IBPartnerProductDAO bPartnerProductDAO = Services.get(IBPartnerProductDAO.class);
private final transient IHUPIItemProductDAO hupiItemProductDAO = Services.get(IHUPIItemProductDAO.class);
private final transient IOrderDAO orderDAO = Services.get(IOrderDAO.class);
private final transient IOrderBL orderBL = Services.get(IOrderBL.class);
private final transient IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class);
private final transient IAttributeDAO attributeDAO = Services.get(IAttributeDAO.class);
private final transient ILUTUConfigurationFactory lutuConfigurationFactory = Services.get(ILUTUConfigurationFactory.class);
private final transient ISSCC18CodeBL sscc18CodeService = Services.get(ISSCC18CodeBL.class);
private final transient HURepository huRepository;
private final transient IUOMDAO uomDAO = Services.get(IUOMDAO.class);
private final transient IBPartnerProductDAO partnerProductDAO = Services.get(IBPartnerProductDAO.class);
private final IHUPackingMaterialDAO packingMaterialDAO = Services.get(IHUPackingMaterialDAO.class);
private final IOrgDAO orgDAO = Services.get(IOrgDAO.class);
// @VisibleForTesting
public DesadvBL(@NonNull final HURepository huRepository)
{
this.huRepository = huRepository;
}
@Override
public List<I_EDI_DesadvLine> retrieveLinesByIds(final Collection<Integer> desadvLineIds)
{
return desadvDAO.retrieveLinesByIds(desadvLineIds);
}
@Override
public I_EDI_Desadv addToDesadvCreateForOrderIfNotExist(@NonNull final I_C_Order orderRecord)
{
Check.assumeNotEmpty(orderRecord.getPOReference(), "C_Order {} has a not-empty POReference", orderRecord);
final I_EDI_Desadv desadvRecord = retrieveOrCreateDesadv(orderRecord);
orderRecord.setEDI_Desadv_ID(desadvRecord.getEDI_Desadv_ID());
final List<I_C_OrderLine> orderLines = orderDAO.retrieveOrderLines(orderRecord, I_C_OrderLine.class);
for (final I_C_OrderLine orderLine : orderLines)
{
if (orderLine.getEDI_DesadvLine_ID() > 0)
{
continue; // is already assigned to a desadv line
}
if (orderLine.isPackagingMaterial())
{
continue; // packing materials from the OL don't belong into the desadv
}
final I_EDI_DesadvLine desadvLine = retrieveOrCreateDesadvLine(orderRecord, desadvRecord, orderLine);
Check.errorIf(
desadvLine.getM_Product_ID() != orderLine.getM_Product_ID(),
"EDI_DesadvLine {} of EDI_Desadv {} has M_Product_ID {} and C_OrderLine {} of C_Order {} has M_Product_ID {}, but both have POReference {} and Line {} ",
desadvLine, desadvRecord, desadvLine.getM_Product_ID(),
orderLine, orderRecord, orderLine.getM_Product_ID(),
orderRecord.getPOReference(), orderLine.getLine());
orderLine.setEDI_DesadvLine(desadvLine);
InterfaceWrapperHelper.save(orderLine);
}
updateFullfilmentPercent(desadvRecord);
saveRecord(desadvRecord);
return desadvRecord;
}
private I_EDI_DesadvLine retrieveOrCreateDesadvLine(
@NonNull final I_C_Order orderRecord,
@NonNull final I_EDI_Desadv desadvRecord,
@NonNull final I_C_OrderLine orderLineRecord)
{
final I_EDI_DesadvLine existingDesadvLine = desadvDAO.retrieveMatchingDesadvLinevOrNull(desadvRecord, orderLineRecord.getLine());
if (existingDesadvLine != null)
{
return existingDesadvLine; // done
}
final ProductId productId = ProductId.ofRepoId(orderLineRecord.getM_Product_ID());
final BPartnerId buyerBPartnerId = BPartnerId.ofRepoId(orderRecord.getC_BPartner_ID());
final org.compiere.model.I_C_BPartner buyerBPartner = bpartnerDAO.getById(buyerBPartnerId);
final I_EDI_DesadvLine newDesadvLine = InterfaceWrapperHelper.newInstance(I_EDI_DesadvLine.class, orderRecord);
newDesadvLine.setEDI_Desadv(desadvRecord);
newDesadvLine.setLine(orderLineRecord.getLine());
newDesadvLine.setOrderLine(orderLineRecord.getLine());
newDesadvLine.setOrderPOReference(orderRecord.getPOReference());
final BigDecimal sumOrderedInStockingUOM = desadvRecord.getSumOrderedInStockingUOM().add(orderLineRecord.getQtyOrdered());
desadvRecord.setSumOrderedInStockingUOM(sumOrderedInStockingUOM);
newDesadvLine.setC_UOM_Invoice_ID(orderLineRecord.getPrice_UOM_ID());
newDesadvLine.setQtyDeliveredInInvoiceUOM(ZERO);
// we'll need this when inoutLines are added, because then we need to add either the nominal quantity or the catch-quantity
newDesadvLine.setInvoicableQtyBasedOn(orderLineRecord.getInvoicableQtyBasedOn());
// this we'll need as well when inoutLines are added, in case there is a TU-UOM involved
newDesadvLine.setQtyItemCapacity(orderLineRecord.getQtyItemCapacity());
newDesadvLine.setQtyEntered(orderLineRecord.getQtyEntered());
newDesadvLine.setQtyDeliveredInUOM(ZERO);
newDesadvLine.setC_UOM_ID(orderLineRecord.getC_UOM_ID());
newDesadvLine.setPriceActual(orderLineRecord.getPriceActual());
newDesadvLine.setQtyOrdered(orderLineRecord.getQtyOrdered());
newDesadvLine.setQtyDeliveredInStockingUOM(ZERO);
newDesadvLine.setM_Product_ID(productId.getRepoId());
newDesadvLine.setProductDescription(orderLineRecord.getProductDescription());
final I_M_Product product = productDAO.getById(productId);
final OrgId orgId = OrgId.ofRepoId(product.getAD_Org_ID());
//
// set infos from C_BPartner_Product
final I_C_BPartner_Product bPartnerProduct = bPartnerProductDAO.retrieveBPartnerProductAssociation(buyerBPartner, product, orgId);
// don't throw an error for missing bPartnerProduct; it might prevent users from creating shipments
// instead, just don't set the values and let the user fix it in the DESADV window later on
// Check.assumeNotNull(bPartnerProduct, "there is a C_BPartner_Product for C_BPArtner {} and M_Product {}", inOut.getC_BPartner(), inOutLine.getM_Product());
if (bPartnerProduct != null)
{
newDesadvLine.setProductNo(bPartnerProduct.getProductNo());
newDesadvLine.setUPC_CU(bPartnerProduct.getUPC());
newDesadvLine.setEAN_CU(bPartnerProduct.getEAN_CU());
if (Check.isEmpty(newDesadvLine.getProductDescription(), true))
{
// fallback for product description
newDesadvLine.setProductDescription(bPartnerProduct.getProductDescription());
}
if (Check.isEmpty(newDesadvLine.getProductDescription(), true))
{
// fallback for product description
newDesadvLine.setProductDescription(bPartnerProduct.getProductName());
}
}
if (Check.isEmpty(newDesadvLine.getProductDescription(), true))
{
// fallback for product description
newDesadvLine.setProductDescription(product.getName());
}
//
// set infos from M_HU_PI_Item_Product
final I_M_HU_PI_Item_Product materialItemProduct = extractHUPIItemProduct(orderRecord, orderLineRecord);
if (materialItemProduct != null)
{
newDesadvLine.setGTIN(materialItemProduct.getGTIN());
newDesadvLine.setUPC_TU(materialItemProduct.getUPC());
newDesadvLine.setEAN_TU(materialItemProduct.getEAN_TU());
}
newDesadvLine.setIsSubsequentDeliveryPlanned(false); // the default
InterfaceWrapperHelper.save(newDesadvLine);
return newDesadvLine;
}
private I_M_HU_PI_Item_Product extractHUPIItemProduct(final I_C_Order order, final I_C_OrderLine orderLine)
{
final I_M_HU_PI_Item_Product materialItemProduct;
if (orderLine.getM_HU_PI_Item_Product_ID() > 0)
{
materialItemProduct = orderLine.getM_HU_PI_Item_Product();
}
else
{
final ProductId productId = ProductId.ofRepoId(orderLine.getM_Product_ID());
final BPartnerId buyerBPartnerId = BPartnerId.ofRepoId(order.getC_BPartner_ID());
final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(order.getAD_Org_ID()));
materialItemProduct = hupiItemProductDAO.retrieveMaterialItemProduct(
productId,
buyerBPartnerId,
TimeUtil.asZonedDateTime(order.getDateOrdered(), timeZone),
X_M_HU_PI_Version.HU_UNITTYPE_TransportUnit, true/* allowInfiniteCapacity */);
}
return materialItemProduct;
}
private I_EDI_Desadv retrieveOrCreateDesadv(@NonNull final I_C_Order order)
{
I_EDI_Desadv desadv = desadvDAO.retrieveMatchingDesadvOrNull(
order.getPOReference(),
InterfaceWrapperHelper.getContextAware(order));
if (desadv == null)
{
desadv = InterfaceWrapperHelper.newInstance(I_EDI_Desadv.class, order);
desadv.setPOReference(order.getPOReference());
desadv.setDeliveryViaRule(order.getDeliveryViaRule());
desadv.setC_BPartner_ID(order.getC_BPartner_ID());
desadv.setC_BPartner_Location_ID(order.getC_BPartner_Location_ID());
desadv.setDateOrdered(order.getDateOrdered());
desadv.setMovementDate(order.getDatePromised());
desadv.setC_Currency_ID(order.getC_Currency_ID());
// the DESADV recipient might need an explicitly set dropship/handover partner and location; even if it is the same as the buyer's one
desadv.setHandOver_Partner_ID(CoalesceUtil.firstGreaterThanZero(order.getHandOver_Partner_ID(), order.getC_BPartner_ID()));
desadv.setHandOver_Location_ID(CoalesceUtil.firstGreaterThanZero(order.getHandOver_Location_ID(), order.getC_BPartner_Location_ID()));
desadv.setDropShip_BPartner_ID(CoalesceUtil.firstGreaterThanZero(order.getDropShip_BPartner_ID(), order.getC_BPartner_ID()));
desadv.setDropShip_Location_ID(CoalesceUtil.firstGreaterThanZero(order.getDropShip_Location_ID(), order.getC_BPartner_Location_ID()));
desadv.setBill_Location_ID(BPartnerLocationAndCaptureId.toBPartnerLocationRepoId(orderBL.getBillToLocationId(order)));
// note: the minimal acceptable fulfillment is currently set by a model interceptor
InterfaceWrapperHelper.save(desadv);
}
return desadv;
}
@Nullable
@Override
public I_EDI_Desadv addToDesadvCreateForInOutIfNotExist(@NonNull final I_M_InOut inOut)
{
final I_EDI_Desadv desadv;
if (inOut.getC_Order_ID() > 0)
{
final I_C_Order order = InterfaceWrapperHelper.create(inOut.getC_Order(), I_C_Order.class);
if (order.getEDI_Desadv_ID() > 0)
{
desadv = order.getEDI_Desadv();
}
else
{
desadv = addToDesadvCreateForOrderIfNotExist(order);
InterfaceWrapperHelper.save(order);
}
}
else if (!Check.isEmpty(inOut.getPOReference(), true))
{
desadv = desadvDAO.retrieveMatchingDesadvOrNull(inOut.getPOReference(), InterfaceWrapperHelper.getContextAware(inOut));
}
else
{
desadv = null;
}
if (desadv == null)
{
return null;
}
inOut.setEDI_Desadv(desadv);
final BPartnerId recipientBPartnerId = BPartnerId.ofRepoId(inOut.getC_BPartner_ID());
final List<I_M_InOutLine> inOutLines = inOutDAO.retrieveLines(inOut, I_M_InOutLine.class);
for (final I_M_InOutLine inOutLine : inOutLines)
{
if (inOutLine.getC_OrderLine_ID() <= 0)
{
continue;
}
addInOutLine(inOutLine, recipientBPartnerId);
}
return desadv;
}
@VisibleForTesting
void addInOutLine(
@NonNull final I_M_InOutLine inOutLineRecord,
@NonNull final BPartnerId recipientBPartnerId)
{
final I_C_OrderLine orderLineRecord = InterfaceWrapperHelper.create(inOutLineRecord.getC_OrderLine(), I_C_OrderLine.class);
final I_EDI_DesadvLine desadvLineRecord = orderLineRecord.getEDI_DesadvLine();
final InvoicableQtyBasedOn invoicableQtyBasedOn = InvoicableQtyBasedOn.fromRecordString(desadvLineRecord.getInvoicableQtyBasedOn());
final StockQtyAndUOMQty inOutLineQty = extractInOutLineQty(inOutLineRecord, invoicableQtyBasedOn);
StockQtyAndUOMQty remainingQtyToAdd = inOutLineQty;
// note that if inOutLineRecord has catch-weight, then logically we can't have HUs
final List<I_M_HU> topLevelHUs = huAssignmentDAO.retrieveTopLevelHUsForModel(inOutLineRecord);
for (final I_M_HU topLevelHU : topLevelHUs)
{
final StockQtyAndUOMQty addedPackQty = addPackRecordToLineUsingHU(desadvLineRecord, inOutLineRecord, topLevelHU, recipientBPartnerId);
remainingQtyToAdd = StockQtyAndUOMQtys.subtract(remainingQtyToAdd, addedPackQty);
}
if (remainingQtyToAdd.getStockQty().signum() > 0)
{
addPackRecordsToLineUsingJustInOutLine(inOutLineRecord, orderLineRecord, desadvLineRecord, remainingQtyToAdd);
}
addOrSubtractInOutLineQty(desadvLineRecord, inOutLineQty, true/* add */);
InterfaceWrapperHelper.save(desadvLineRecord);
inOutLineRecord.setEDI_DesadvLine_ID(desadvLineRecord.getEDI_DesadvLine_ID());
InterfaceWrapperHelper.save(inOutLineRecord);
}
private StockQtyAndUOMQty extractInOutLineQty(
@NonNull final I_M_InOutLine inOutLineRecord,
@NonNull final InvoicableQtyBasedOn invoicableQtyBasedOn)
{
switch (invoicableQtyBasedOn)
{
case CatchWeight:
final StockQtyAndUOMQty stockQtyAndCatchQty = inOutBL.getStockQtyAndCatchQty(inOutLineRecord);
if (stockQtyAndCatchQty.getUOMQtyOpt().isPresent())
{
return stockQtyAndCatchQty;
}
// fallback if the given iol simply doesn't have a catch weight (which is a common case)
return inOutBL.getStockQtyAndQtyInUOM(inOutLineRecord);
case NominalWeight:
return inOutBL.getStockQtyAndQtyInUOM(inOutLineRecord);
default:
throw new AdempiereException("Unsupported invoicableQtyBasedOn=" + invoicableQtyBasedOn);
}
}
private void addPackRecordsToLineUsingJustInOutLine(
@NonNull final I_M_InOutLine inOutLineRecord,
@NonNull final I_C_OrderLine orderLineRecord,
@NonNull final I_EDI_DesadvLine desadvLineRecord,
@NonNull final StockQtyAndUOMQty qtyToAdd)
{
Check.assume(qtyToAdd.getStockQty().signum() > 0, "Parameter 'qtyToAdd' needs to be >0 for all this to make sense");
final ProductId productId = ProductId.ofRepoId(inOutLineRecord.getM_Product_ID());
final I_C_Order orderRecord = create(orderLineRecord.getC_Order(), I_C_Order.class);
final I_M_HU_PI_Item_Product tuPIItemProduct = extractHUPIItemProduct(orderRecord, orderLineRecord);
final BPartnerId bpartnerId = BPartnerId.ofRepoId(orderRecord.getC_BPartner_ID());
final I_M_HU_LUTU_Configuration lutuConfigurationInStockUOM = lutuConfigurationFactory.createLUTUConfiguration(
tuPIItemProduct,
productId,
qtyToAdd.getStockQty().getUomId(),
bpartnerId,
false/* noLUForVirtualTU */);
final StockQtyAndUOMQty maxQtyCUsPerLU;
final int requiredLUCount;
final boolean configCapacityUnspecified = lutuConfigurationInStockUOM.isInfiniteQtyTU() || lutuConfigurationInStockUOM.isInfiniteQtyCU();
if (configCapacityUnspecified)
{
maxQtyCUsPerLU = StockQtyAndUOMQtys.createConvert(
qtyToAdd.getStockQty(),
productId,
qtyToAdd.getUOMQtyNotNull().getUomId());
requiredLUCount = 1;
}
else
{
maxQtyCUsPerLU = StockQtyAndUOMQtys.createConvert(
lutuConfigurationInStockUOM.getQtyCU().multiply(lutuConfigurationInStockUOM.getQtyTU()),
productId,
qtyToAdd.getUOMQtyNotNull().getUomId());
requiredLUCount = lutuConfigurationFactory.calculateQtyLUForTotalQtyCUs(
lutuConfigurationInStockUOM,
qtyToAdd.getUOMQtyNotNull());
}
final Quantity qtyCUsPerTUInStockUOM;
if (lutuConfigurationInStockUOM.isInfiniteQtyCU())
{
qtyCUsPerTUInStockUOM = qtyToAdd.getStockQty();
}
else
{
qtyCUsPerTUInStockUOM = Quantitys.create(lutuConfigurationInStockUOM.getQtyCU(), qtyToAdd.getStockQty().getUomId());
}
StockQtyAndUOMQty remainingQty = qtyToAdd;
for (int i = 0; i < requiredLUCount; i++)
{
final I_EDI_DesadvLine_Pack packRecord = createNewPackRecord(desadvLineRecord);
packRecord.setQtyItemCapacity(lutuConfigurationInStockUOM.getQtyCU());
packRecord.setM_InOut_ID(inOutLineRecord.getM_InOut_ID());
packRecord.setM_InOutLine_ID(inOutLineRecord.getM_InOutLine_ID());
// BestBefore
final Optional<Timestamp> bestBeforeDate = extractBestBeforeDate(inOutLineRecord);
bestBeforeDate.ifPresent(packRecord::setBestBeforeDate);
// Lot
final Optional<String> lotNumber = extractLotNumber(inOutLineRecord);
lotNumber.ifPresent(packRecord::setLotNumber);
// SSCC18
final String sscc18 = computeSSCC18(OrgId.ofRepoId(inOutLineRecord.getAD_Org_ID()));
packRecord.setIPA_SSCC18(sscc18);
packRecord.setIsManual_IPA_SSCC18(true); // because the SSCC string is not coming from any M_HU
// PackagingCodes and PackagingGTINs
final int packagingCodeLU_ID = tuPIItemProduct.getM_HU_PackagingCode_LU_Fallback_ID();
packRecord.setM_HU_PackagingCode_LU_ID(packagingCodeLU_ID);
packRecord.setGTIN_LU_PackingMaterial(tuPIItemProduct.getGTIN_LU_PackingMaterial_Fallback());
final int packagingCodeTU_ID = tuPIItemProduct.getM_HU_PI_Item().getM_HU_PI_Version().getM_HU_PackagingCode_ID();
packRecord.setM_HU_PackagingCode_TU_ID(packagingCodeTU_ID);
final List<I_M_HU_PackingMaterial> huPackingMaterials = packingMaterialDAO.retrievePackingMaterials(tuPIItemProduct);
if (huPackingMaterials.size() == 1)
{
final I_C_BPartner_Product bPartnerProductRecord = partnerProductDAO
.retrieveBPartnerProductAssociation(Env.getCtx(),
bpartnerId,
ProductId.ofRepoId(huPackingMaterials.get(0).getM_Product_ID()),
OrgId.ofRepoId(desadvLineRecord.getAD_Org_ID()));
if (bPartnerProductRecord != null && isNotBlank(bPartnerProductRecord.getGTIN()))
{
packRecord.setGTIN_TU_PackingMaterial(bPartnerProductRecord.getGTIN());
}
}
else
{
logger.debug("M_HU_PI_Item_Product_ID={} has {} M_HU_PackingMaterials; -> skip setting GTIN_TU_PackingMaterial to EDI_DesadvLine_Pack_ID={}",
tuPIItemProduct.getM_HU_PI_Item_Product_ID(), huPackingMaterials.size(), packRecord.getEDI_DesadvLine_Pack_ID());
}
final StockQtyAndUOMQty qtyCUsPerCurrentLU = remainingQty.min(maxQtyCUsPerLU);
final Quantity currentQtyTU = qtyCUsPerCurrentLU.getStockQty().divide(qtyCUsPerTUInStockUOM.toBigDecimal(), 0, RoundingMode.UP);
packRecord.setQtyTU(currentQtyTU.toBigDecimal().intValue());
setQty(packRecord, productId, qtyCUsPerTUInStockUOM, qtyCUsPerCurrentLU);
saveRecord(packRecord);
// prepare next iteration within this for-look
remainingQty = StockQtyAndUOMQtys.subtract(remainingQty, qtyCUsPerCurrentLU);
}
}
private String computeSSCC18(@NonNull final OrgId orgId)
{
final SSCC18 sscc18 = sscc18CodeService.generate(orgId);
return sscc18.asString();
}
private StockQtyAndUOMQty addPackRecordToLineUsingHU(
@NonNull final I_EDI_DesadvLine desadvLineRecord,
@NonNull final I_M_InOutLine inOutLineRecord,
@NonNull final I_M_HU huRecord,
@NonNull final BPartnerId bPartnerId)
{
final ProductId productId = ProductId.ofRepoId(desadvLineRecord.getM_Product_ID());
final HU rootHU = huRepository
.getById(HuId.ofRepoId(huRecord.getM_HU_ID()))
.retainProduct(productId) // no need to blindly hope that the HU is homogenous
.orElse(null);
if (rootHU == null || !rootHU.getType().isLU())
{
final UomId desadvUomId = UomId.ofRepoId(desadvLineRecord.getC_UOM_ID());
return StockQtyAndUOMQtys.createZero(productId, desadvUomId); // we don't do HU-related stuffs if the HU is not a LU.
}
final I_EDI_DesadvLine_Pack packRecord = createNewPackRecord(desadvLineRecord);
packRecord.setM_InOut_ID(inOutLineRecord.getM_InOut_ID());
packRecord.setM_InOutLine_ID(inOutLineRecord.getM_InOutLine_ID());
packRecord.setM_HU_ID(huRecord.getM_HU_ID());
final Quantity qtyCUInStockUOM = rootHU.extractMedianCUQtyPerChildHU(productId);
packRecord.setQtyItemCapacity(qtyCUInStockUOM.toBigDecimal());
// get minimum best before of all HUs and sub-HUs
final Date bestBefore = rootHU.extractSingleAttributeValue(
attrSet -> attrSet.hasAttribute(AttributeConstants.ATTR_BestBeforeDate) ? attrSet.getValueAsDate(AttributeConstants.ATTR_BestBeforeDate) : null,
TimeUtil::min);
packRecord.setBestBeforeDate(TimeUtil.asTimestamp(bestBefore));
// Lot
final String lotNumber = rootHU.getAttributes().getValueAsString(AttributeConstants.ATTR_LotNumber);
if (!isEmpty(lotNumber, true))
{
packRecord.setLotNumber(lotNumber);
}
// SSCC18
final String sscc18 = rootHU.getAttributes().getValueAsString(HUAttributeConstants.ATTR_SSCC18_Value);
if (isEmpty(sscc18, true))
{
packRecord.setIsManual_IPA_SSCC18(true);
final String onTheFlySSCC18 = computeSSCC18ForHUId(rootHU.getOrgId(), rootHU.getId());
packRecord.setIPA_SSCC18(onTheFlySSCC18);
}
else
{
packRecord.setIPA_SSCC18(sscc18);
packRecord.setIsManual_IPA_SSCC18(false);
}
extractAndSetPackagingCodes(rootHU, packRecord);
extractAndSetPackagingGTINs(rootHU, bPartnerId, packRecord);
packRecord.setQtyTU(rootHU.getChildHUs().size());
// note that rootHU only contains children, quantities and weights for productId
final Quantity qtyInStockUOM = rootHU.getProductQtysInStockUOM().get(productId);
final Optional<Quantity> weight = rootHU.getWeightNet();
final StockQtyAndUOMQty quantity;
if (weight.isPresent())
{
quantity = StockQtyAndUOMQty.builder()
.productId(productId)
.stockQty(qtyInStockUOM)
.uomQty(weight.get())
.build();
}
else
{
quantity = StockQtyAndUOMQtys.createConvert(
qtyInStockUOM,
productId,
qtyInStockUOM.getUomId()); // don't try to convert to the pack's UOM! it might be a TU-uom
}
setQty(packRecord, productId, qtyCUInStockUOM, quantity);
saveRecord(packRecord);
return quantity;
}
private void extractAndSetPackagingCodes(
@NonNull final HU rootHU,
@NonNull final I_EDI_DesadvLine_Pack packRecord)
{
final Optional<PackagingCode> packagingCode = rootHU.getPackagingCode();
if (packagingCode.isPresent())
{
packRecord.setM_HU_PackagingCode_LU_ID(packagingCode.get().getId().getRepoId());
}
final PackagingCode tuPackagingCode = CollectionUtils.extractSingleElementOrDefault(
rootHU.getChildHUs(), // don't iterate all HUs; we just care for the level below our LU (aka TU level).
hu -> hu.getPackagingCode().orElse(PackagingCode.NONE), // don't use null because CollectionUtils runs with ImmutableList
PackagingCode.NONE);
if (!tuPackagingCode.isNone())
{
packRecord.setM_HU_PackagingCode_TU_ID(tuPackagingCode.getId().getRepoId());
}
}
private void extractAndSetPackagingGTINs(
@NonNull final HU rootHU,
@NonNull final BPartnerId bPartnerId,
@NonNull final I_EDI_DesadvLine_Pack packRecord)
{
final String packagingGTIN = rootHU.getPackagingGTINs().get(bPartnerId);
if (isNotBlank(packagingGTIN))
{
packRecord.setGTIN_LU_PackingMaterial(packagingGTIN);
}
final String tuPackagingGTIN = CollectionUtils.extractSingleElementOrDefault(
rootHU.getChildHUs(), // don't iterate all HUs; we just care for the level below our LU (aka TU level).
hu -> coalesce(hu.getPackagingGTINs().get(bPartnerId), ""),
"");
if (isNotBlank(tuPackagingGTIN))
{
packRecord.setGTIN_TU_PackingMaterial(tuPackagingGTIN);
}
}
private String computeSSCC18ForHUId(@NonNull final OrgId orgId, @NonNull final HuId huId)
{
final SSCC18 sscc18 = sscc18CodeService.generate(orgId, huId.getRepoId());
return sscc18.asString();
}
private I_EDI_DesadvLine_Pack createNewPackRecord(@NonNull final I_EDI_DesadvLine desadvLineRecord)
{
final I_EDI_DesadvLine_Pack ssccRecord = newInstance(I_EDI_DesadvLine_Pack.class);
ssccRecord.setEDI_DesadvLine_ID(desadvLineRecord.getEDI_DesadvLine_ID());
ssccRecord.setEDI_Desadv_ID(desadvLineRecord.getEDI_Desadv_ID());
ssccRecord.setC_UOM_ID(desadvLineRecord.getC_UOM_ID());
return ssccRecord;
}
private Optional<Timestamp> extractBestBeforeDate(@NonNull final I_M_InOutLine inOutLineRecord)
{
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(inOutLineRecord.getM_AttributeSetInstance_ID());
final ImmutableAttributeSet attributeSet = attributeDAO.getImmutableAttributeSetById(asiId);
if (attributeSet.hasAttribute(AttributeConstants.ATTR_BestBeforeDate))
{
final Date bestBeforeDate = attributeSet.getValueAsDate(AttributeConstants.ATTR_BestBeforeDate);
return Optional.of(TimeUtil.asTimestamp(bestBeforeDate));
}
return Optional.empty();
}
private Optional<String> extractLotNumber(@NonNull final I_M_InOutLine inOutLineRecord)
{
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(inOutLineRecord.getM_AttributeSetInstance_ID());
final ImmutableAttributeSet attributeSet = attributeDAO.getImmutableAttributeSetById(asiId);
if (attributeSet.hasAttribute(AttributeConstants.ATTR_LotNumber))
{
final String lotNumber = attributeSet.getValueAsString(AttributeConstants.ATTR_LotNumber);
return Optional.of(lotNumber);
}
return Optional.empty();
}
@Override
public void removeInOutFromDesadv(final I_M_InOut inOut)
{
if (inOut.getEDI_Desadv_ID() <= 0)
{
return;
}
final List<I_M_InOutLine> inOutLines = inOutDAO.retrieveLines(inOut, I_M_InOutLine.class);
for (final I_M_InOutLine inOutLine : inOutLines)
{
removeInOutLineFromDesadv(inOutLine);
}
inOut.setEDI_Desadv_ID(0);
InterfaceWrapperHelper.save(inOut);
}
@Override
public void removeInOutLineFromDesadv(@NonNull final I_M_InOutLine inOutLineRecord)
{
if (inOutLineRecord.getEDI_DesadvLine_ID() <= 0)
{
return;
}
final List<I_EDI_DesadvLine_Pack> packRecords = desadvDAO.retrieveDesadvLinePackRecords(inOutLineRecord);
for (final I_EDI_DesadvLine_Pack packRecord : packRecords)
{
delete(packRecord);
}
final I_EDI_DesadvLine desadvLineRecord = inOutLineRecord.getEDI_DesadvLine();
final StockQtyAndUOMQty inOutLineQty = extractInOutLineQty(
inOutLineRecord,
InvoicableQtyBasedOn.fromRecordString(desadvLineRecord.getInvoicableQtyBasedOn()));
addOrSubtractInOutLineQty(desadvLineRecord, inOutLineQty, false/* add=false, i.e. subtract */);
InterfaceWrapperHelper.save(desadvLineRecord);
inOutLineRecord.setEDI_DesadvLine_ID(0);
InterfaceWrapperHelper.save(inOutLineRecord);
}
@VisibleForTesting
void addOrSubtractInOutLineQty(
@NonNull final I_EDI_DesadvLine desadvLineRecord,
@NonNull final StockQtyAndUOMQty inOutLineQty,
final boolean add)
{
final StockQtyAndUOMQty inOutLineQtyEff = inOutLineQty.negateIfNot(add);
final Quantity inOutLineStockQty = inOutLineQtyEff.getStockQty();
final BigDecimal newMovementQty = desadvLineRecord.getQtyDeliveredInStockingUOM().add(inOutLineStockQty.toBigDecimal());
desadvLineRecord.setQtyDeliveredInStockingUOM(newMovementQty);
final Quantity desadvLineQtyDelivered = Quantitys.create(desadvLineRecord.getQtyDeliveredInUOM(), UomId.ofRepoId(desadvLineRecord.getC_UOM_ID()));
final Quantity newQtyDeliveredInUOM = addInOutLineQtyToDesadvLineQty(inOutLineQtyEff, desadvLineQtyDelivered, desadvLineRecord);
desadvLineRecord.setQtyDeliveredInUOM(newQtyDeliveredInUOM.toBigDecimal());
// convert the delivered qty (which *might* also be in catch-weight!) to the invoicing-UOM
final UomId invoiceUomId = UomId.ofRepoIdOrNull(desadvLineRecord.getC_UOM_Invoice_ID());
if (invoiceUomId != null)
{
final Quantity desadvLineQtyInInvoiceUOM = Quantitys.create(desadvLineRecord.getQtyDeliveredInInvoiceUOM(), UomId.ofRepoId(desadvLineRecord.getC_UOM_Invoice_ID()));
final Quantity newQtyDeliveredInInvoiceUOM = addInOutLineQtyToDesadvLineQty(inOutLineQtyEff, desadvLineQtyInInvoiceUOM, desadvLineRecord);
desadvLineRecord.setQtyDeliveredInInvoiceUOM(newQtyDeliveredInInvoiceUOM.toBigDecimal());
}
// update header record
final I_EDI_Desadv desadvRecord = desadvLineRecord.getEDI_Desadv();
final BigDecimal newSumDeliveredInStockingUOM = desadvRecord
.getSumDeliveredInStockingUOM()
.add(inOutLineStockQty.toBigDecimal());
desadvRecord.setSumDeliveredInStockingUOM(newSumDeliveredInStockingUOM);
updateFullfilmentPercent(desadvRecord);
saveRecord(desadvRecord);
}
private Quantity addInOutLineQtyToDesadvLineQty(
@NonNull final StockQtyAndUOMQty inOutLineQty,
@NonNull final Quantity desadvLineQtyToAugment,
@NonNull final I_EDI_DesadvLine desadvLineRecord)
{
final Quantity inOutLineStockQty = inOutLineQty.getStockQty();
final Quantity inOutLineLineQtyDelivered = inOutLineQty.getUOMQtyNotNull();
final Quantity augentQtyDeliveredInUOM;
final boolean desadvLineQtyIsUOMForTUS = uomDAO.isUOMForTUs(desadvLineQtyToAugment.getUomId());
final boolean inOutLineQtyIsUOMForTUS = uomDAO.isUOMForTUs(inOutLineLineQtyDelivered.getUomId());
if (desadvLineQtyIsUOMForTUS && !inOutLineQtyIsUOMForTUS)
{
// we need to take inOutLineStockQty and convert it to "TU-UOM" by using the itemCapacity
final BigDecimal cusPerTU = desadvLineRecord.getQtyItemCapacity();
if (cusPerTU.signum() <= 0)
{
throw new AdempiereException("desadvLineRecord with TU-UOM C_UOM_ID=" + desadvLineQtyToAugment.getUomId().getRepoId() + " needs to have a QtyItemCapacity in order to convert the quantity")
.appendParametersToMessage().setParameter("desadvLineRecord", desadvLineRecord);
}
augentQtyDeliveredInUOM = Quantitys.create(
inOutLineStockQty.toBigDecimal().divide(cusPerTU, RoundingMode.CEILING),
desadvLineQtyToAugment.getUomId());
}
else if (!desadvLineQtyIsUOMForTUS && inOutLineQtyIsUOMForTUS)
{
// we again need to take inOutLineStockQty and this time convert is to desadvLineQtyDelivered's UOM via uom-conversion
augentQtyDeliveredInUOM = inOutLineStockQty;
}
else
{
// if bot are TU or both are not, then uom-conversion will work fine
augentQtyDeliveredInUOM = inOutLineLineQtyDelivered;
}
final UOMConversionContext conversionCtx = UOMConversionContext.of(desadvLineRecord.getM_Product_ID());
final Quantity newQtyDeliveredInUOM = Quantitys
.add(conversionCtx,
desadvLineQtyToAugment,
augentQtyDeliveredInUOM);
return newQtyDeliveredInUOM;
}
/**
* Sets the given packRecord's <code>MovementQty</code> and <code>QtyDeliveredInUOM</code>.
*/
@VisibleForTesting
void setQty(
@NonNull final I_EDI_DesadvLine_Pack packRecord,
@NonNull final ProductId productId,
@NonNull final Quantity qtyCUInStockUOM,
@NonNull final StockQtyAndUOMQty qtyCUsPerLU)
{
final UomId packUomId = UomId.ofRepoId(packRecord.getC_UOM_ID());
final BigDecimal qtyCUPerTUinPackUOM;
final BigDecimal qtyCUsPerLUinPackUOM;
if (uomDAO.isUOMForTUs(packUomId))
{
qtyCUPerTUinPackUOM = ONE; // we count in TUs, also on the CU-level
qtyCUsPerLUinPackUOM = qtyCUsPerLU.getStockQty()
.toBigDecimal()
.divide(packRecord.getQtyItemCapacity(), 0/* result's scale */, RoundingMode.UP);
}
else
{
qtyCUPerTUinPackUOM = uomConversionBL
.convertQuantityTo(
qtyCUInStockUOM,
UOMConversionContext.of(productId),
packUomId)
.toBigDecimal();
qtyCUsPerLUinPackUOM = uomConversionBL
.convertQuantityTo(
qtyCUsPerLU.getUOMQtyNotNull(),
UOMConversionContext.of(productId),
packUomId)
.toBigDecimal();
}
packRecord.setMovementQty(qtyCUsPerLU.getStockQty().toBigDecimal());
packRecord.setQtyCU(qtyCUPerTUinPackUOM);
packRecord.setQtyCUsPerLU(qtyCUsPerLUinPackUOM);
}
@Override
public void removeOrderFromDesadv(@NonNull final I_C_Order order)
{
if (order.getEDI_Desadv_ID() <= 0)
{
return;
}
final I_EDI_Desadv desadv = order.getEDI_Desadv();
final List<I_C_OrderLine> orderLines = orderDAO.retrieveOrderLines(order, I_C_OrderLine.class);
for (final I_C_OrderLine orderLine : orderLines)
{
removeOrderLineFromDesadv(orderLine);
}
order.setEDI_Desadv_ID(0);
InterfaceWrapperHelper.save(order);
if (!desadvDAO.hasDesadvLines(desadv)
&& !desadvDAO.hasOrders(desadv)
/* && !desadvDAO.hasInOuts(desadv) delete, even if there are by some constellation inouts left */
)
{
InterfaceWrapperHelper.delete(desadv);
}
}
@Override
public void removeOrderLineFromDesadv(@NonNull final I_C_OrderLine orderLine)
{
if (orderLine.getEDI_DesadvLine_ID() <= 0)
{
return;
}
final I_EDI_DesadvLine desadvLine = orderLine.getEDI_DesadvLine();
final I_EDI_Desadv desadvRecord = desadvLine.getEDI_Desadv();
final BigDecimal sumOrderedInStockingUOM = desadvRecord.getSumOrderedInStockingUOM().subtract(orderLine.getQtyOrdered());
desadvRecord.setSumOrderedInStockingUOM(sumOrderedInStockingUOM);
updateFullfilmentPercent(desadvRecord);
saveRecord(desadvRecord);
if (desadvDAO.hasInOutLines(desadvLine))
{
// not supposed to happen because when we get here, there should be no iol at all, or it's inout should have been reversed and in that case, the iol was already detached by
// removeInOutLineFromDesadv.
}
orderLine.setEDI_DesadvLine_ID(0);
InterfaceWrapperHelper.save(orderLine);
if (!desadvDAO.hasOrderLines(desadvLine) && !desadvDAO.hasInOutLines(desadvLine))
{
InterfaceWrapperHelper.delete(desadvLine);
}
}
private void updateFullfilmentPercent(@NonNull final I_EDI_Desadv desadvRecord)
{
// If we have 99.9, then the result which the user sees shall be 99, not 100. That way it's much more clear to the user.
final RoundingMode roundTofloor = RoundingMode.FLOOR;
final Percent fullfilment = Percent.of(
desadvRecord.getSumDeliveredInStockingUOM(),
desadvRecord.getSumOrderedInStockingUOM(),
0/* precision */,
roundTofloor);
desadvRecord.setFulfillmentPercent(fullfilment.toBigDecimal());
}
@Override
public ReportResultData printSSCC18_Labels(
@NonNull final Properties ctx,
@NonNull final Collection<EDIDesadvLinePackId> desadvLinePack_IDs_ToPrint)
{
Check.assumeNotEmpty(desadvLinePack_IDs_ToPrint, "desadvLineSSCC_IDs_ToPrint not empty");
//
// Create the process info based on AD_Process and AD_PInstance
final ProcessExecutionResult result = ProcessInfo.builder()
.setCtx(ctx)
.setAD_ProcessByValue(AD_PROCESS_VALUE_EDI_DesadvLine_SSCC_Print)
//
// Parameter: REPORT_SQL_QUERY: provide a different report query which will select from our datasource instead of using the standard query (which is M_HU_ID based).
.addParameter(ReportConstants.REPORT_PARAM_SQL_QUERY, "select * from report.fresh_EDI_DesadvLine_SSCC_Label_Report"
+ " where AD_PInstance_ID=" + ReportConstants.REPORT_PARAM_SQL_QUERY_AD_PInstance_ID_Placeholder + " "
+ " order by EDI_DesadvLine_SSCC_ID")
//
// Execute the actual printing process
.buildAndPrepareExecution()
.onErrorThrowException()
// Create a selection with the EDI_DesadvLine_Pack_IDs that we need to print.
// The report will fetch it from selection.
.callBefore(pi -> DB.createT_Selection(pi.getPinstanceId(), desadvLinePack_IDs_ToPrint, ITrx.TRXNAME_ThreadInherited))
.executeSync()
.getResult();
return result.getReportData();
}
@Override
public void setMinimumPercentage(@NonNull final I_EDI_Desadv desadv)
{
final BigDecimal minimumPercentageAccepted = desadvDAO.retrieveMinimumSumPercentage();
desadv.setFulfillmentPercentMin(minimumPercentageAccepted);
}
@Override
public ImmutableList<ITranslatableString> createMsgsForDesadvsBelowMinimumFulfilment(@NonNull final ImmutableList<I_EDI_Desadv> desadvsRecords)
{
final ImmutableList.Builder<ITranslatableString> result = ImmutableList.builder();
final ImmutableListMultimap<BigDecimal, I_EDI_Desadv> minimum2DesadvRecords = Multimaps.index(desadvsRecords, I_EDI_Desadv::getFulfillmentPercentMin);
for (final BigDecimal minimumSumPercentage : minimum2DesadvRecords.keySet())
{
createSingleMsg(desadvsRecords, minimumSumPercentage).ifPresent(result::add);
}
return result.build();
}
private Optional<ITranslatableString> createSingleMsg(
@NonNull final List<I_EDI_Desadv> desadvsToSkip,
@NonNull final BigDecimal minimumSumPercentage)
{
final StringBuilder skippedDesadvsString = new StringBuilder();
for (final I_EDI_Desadv desadvRecord : desadvsToSkip)
{
if (desadvRecord.getFulfillmentPercent().compareTo(desadvRecord.getFulfillmentPercentMin()) <= 0)
{
skippedDesadvsString.append("#")
.append(desadvRecord.getDocumentNo())
.append(" - ")
.append(desadvRecord.getFulfillmentPercent())
.append("\n");
}
}
if (skippedDesadvsString.length() <= 0)
{
return Optional.empty(); // nothing to log
}
// log a message that includes all the skipped lines'documentNo and percentage
final ITranslatableString msg = Services.get(IMsgBL.class).getTranslatableMsgText(
MSG_EDI_DESADV_RefuseSending,
minimumSumPercentage, skippedDesadvsString.toString());
return Optional.of(msg);
}
}
| 16,035
|
7,830
|
<reponame>dmitrybaidaev/coturn
/*
* Copyright (C) 2011, 2012, 2013 Citrix Systems
* Copyright (C) 2014 <NAME>.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "../mainrelay.h"
#include "apputils.h"
#include "dbdriver.h"
#include "dbd_sqlite.h"
#include "dbd_pgsql.h"
#include "dbd_mysql.h"
#include "dbd_mongo.h"
#include "dbd_redis.h"
static void make_connection_key(void)
{
(void) pthread_key_create(&connection_key, NULL);
}
pthread_key_t connection_key;
pthread_once_t connection_key_once = PTHREAD_ONCE_INIT;
int convert_string_key_to_binary(char* keysource, hmackey_t key, size_t sz) {
char is[3];
size_t i;
unsigned int v;
is[2]=0;
for(i=0;i<sz;i++) {
is[0]=keysource[i*2];
is[1]=keysource[i*2+1];
sscanf(is,"%02x",&v);
key[i]=(unsigned char)v;
}
return 0;
}
persistent_users_db_t * get_persistent_users_db(void) {
return &(turn_params.default_users_db.persistent_users_db);
}
const turn_dbdriver_t * get_dbdriver()
{
if (turn_params.default_users_db.userdb_type == TURN_USERDB_TYPE_UNKNOWN)
return NULL;
(void) pthread_once(&connection_key_once, make_connection_key);
static const turn_dbdriver_t * _driver = NULL;
if (_driver == NULL) {
switch (turn_params.default_users_db.userdb_type){
#if !defined(TURN_NO_SQLITE)
case TURN_USERDB_TYPE_SQLITE:
_driver = get_sqlite_dbdriver();
break;
#endif
#if !defined(TURN_NO_PQ)
case TURN_USERDB_TYPE_PQ:
_driver = get_pgsql_dbdriver();
break;
#endif
#if !defined(TURN_NO_MYSQL)
case TURN_USERDB_TYPE_MYSQL:
_driver = get_mysql_dbdriver();
break;
#endif
#if !defined(TURN_NO_MONGO)
case TURN_USERDB_TYPE_MONGO:
_driver = get_mongo_dbdriver();
break;
#endif
#if !defined(TURN_NO_HIREDIS)
case TURN_USERDB_TYPE_REDIS:
_driver = get_redis_dbdriver();
break;
#endif
default:
break;
}
}
return _driver;
}
| 1,226
|
614
|
<filename>sample/src/main/java/com/androidwind/androidquick/demo/base/BaseFragment.java
package com.androidwind.androidquick.demo.base;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import com.androidwind.androidquick.demo.base.mvp.BaseContract;
import com.androidwind.androidquick.demo.features.function.permission.PermissionActivity;
import com.androidwind.androidquick.demo.ui.activity.FrameActivity;
import com.androidwind.androidquick.module.asynchronize.eventbus.EventCenter;
import com.androidwind.androidquick.ui.base.QuickActivity;
import com.androidwind.androidquick.ui.base.QuickFragment;
import androidx.annotation.NonNull;
/**
* @author ddnosh
* @website http://blog.csdn.net/ddnosh
*/
public abstract class BaseFragment extends QuickFragment implements BaseContract.BaseView{
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}
@Override
protected void onFirstUserVisible() {
}
@Override
protected void onUserVisible() {
}
@Override
protected void onUserInvisible() {
}
@Override
protected boolean isBindEventBus() {
return false;
}
@Override
protected boolean isApplyButterKnife() {
return true;
}
@Override
protected void onEventComing(EventCenter eventCenter) {
}
@Override
protected Intent getGoIntent(Class<?> clazz) {
if (BaseFragment.class.isAssignableFrom(clazz)) {
Intent intent = new Intent(getActivity(), FrameActivity.class);
intent.putExtra("fragmentName", clazz.getName());
return intent;
} else {
return super.getGoIntent(clazz);
}
}
public void performCodeWithPermission(@NonNull int dialogType,
final int requestCode, @NonNull String[] perms, @NonNull PermissionActivity.PermissionCallback callback) {
if (getActivity() != null && getActivity() instanceof QuickActivity) {
((BaseActivity) getActivity()).performCodeWithPermission(dialogType, requestCode, perms, callback);
}
}
}
| 807
|
637
|
import unittest
class TestFoo(unittest.TestCase):
x = 1
def test_ohnoez(self):
x = self
# fmt: off
assert x.x != (self
).x
# fmt: on
| 114
|
441
|
<filename>beetl-core/src/main/java/org/beetl/core/statement/IncDecExpression.java
/*
[The "BSD license"]
Copyright (c) 2011-2014 <NAME> (李家智)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.beetl.core.statement;
import org.beetl.core.Context;
import org.beetl.core.InferContext;
import org.beetl.core.misc.ALU;
/** ++i 或者 i++ 或者--i 或者i--
* @author joelli
*
*/
public class IncDecExpression extends Expression implements IVarIndex
{
boolean isInc, returnOrginal;
int index;
public IncDecExpression(boolean isInc, boolean returnOrginal, GrammarToken token)
{
super(token);
this.isInc = isInc;
this.returnOrginal = returnOrginal;
}
public final Object evaluate(Context ctx)
{
Object c = ctx.vars[index];
Object newValue = isInc ? ALU.plusOne(c, this) : ALU.minusOne(c, this);
if (isInc)
{
newValue = ALU.plusOne(c, this);
}
else
{
newValue = ALU.minusOne(c, this);
}
ctx.vars[index] = newValue;
return returnOrginal ? c : newValue;
}
@Override
public void infer(InferContext inferCtx)
{
this.type = inferCtx.types[this.index];
}
@Override
public void setVarIndex(int index)
{
this.index = index;
}
@Override
public int getVarIndex()
{
return index;
}
}
| 948
|
365
|
<filename>super-boot-user/src/main/java/org/superboot/dao/jpa/EmployeesDutiesDAO.java<gh_stars>100-1000
package org.superboot.dao.jpa;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Repository;
import org.superboot.base.BaseJpaDAO;
import org.superboot.entity.jpa.SuperbootEmployeesDuties;
/**
* <b> 人员职务DAO类 </b>
* <p>
* 功能描述:
* </p>
*
*/
@Repository
@CacheConfig(cacheNames = "employees")
public interface EmployeesDutiesDAO extends BaseJpaDAO<SuperbootEmployeesDuties> {
/**
* 按员工主键和职务主键查找
*
* @param pkEmployees 员工主键
* @param pkDuties 职务主键
* @return
*/
SuperbootEmployeesDuties findByPkEmployeesAndPkDutiesAndDr(long pkEmployees, long pkDuties, int dr);
}
| 360
|
2,591
|
<filename>liquibase-core/src/main/java/liquibase/hub/model/Project.java
package liquibase.hub.model;
import java.util.Date;
import java.util.UUID;
public class Project implements HubModel {
private UUID id;
private String name;
private Date createDate;
@Override
public UUID getId() {
return id;
}
public Project setId(UUID id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public Project setName(String name) {
this.name = name;
return this;
}
public Date getCreateDate() {
return createDate;
}
public Project setCreateDate(Date createDate) {
this.createDate = createDate;
return this;
}
@Override
public String toString() {
return "Project " + getId() + " (" + getName() + ")";
}
}
| 363
|
14,668
|
<filename>third_party/blink/renderer/core/dom/attr_test.cc
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/dom/attr.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
namespace blink {
class AttrTest : public testing::Test {
protected:
void SetUp() override;
Attr* CreateAttribute();
const AtomicString& Value() const { return value_; }
private:
Persistent<Document> document_;
AtomicString value_;
};
void AttrTest::SetUp() {
document_ = Document::CreateForTest();
value_ = "value";
}
Attr* AttrTest::CreateAttribute() {
return document_->createAttribute("name", ASSERT_NO_EXCEPTION);
}
TEST_F(AttrTest, InitialValueState) {
Attr* attr = CreateAttribute();
Node* node = attr;
EXPECT_EQ(g_empty_atom, attr->value());
EXPECT_EQ(g_empty_string, node->nodeValue());
EXPECT_EQ(g_empty_string, attr->textContent());
}
TEST_F(AttrTest, SetValue) {
Attr* attr = CreateAttribute();
Node* node = attr;
attr->setValue(Value(), ASSERT_NO_EXCEPTION);
EXPECT_EQ(Value(), attr->value());
EXPECT_EQ(Value(), node->nodeValue());
EXPECT_EQ(Value(), attr->textContent());
}
TEST_F(AttrTest, SetNodeValue) {
Attr* attr = CreateAttribute();
Node* node = attr;
node->setNodeValue(Value());
EXPECT_EQ(Value(), attr->value());
EXPECT_EQ(Value(), node->nodeValue());
EXPECT_EQ(Value(), attr->textContent());
}
TEST_F(AttrTest, SetTextContent) {
Attr* attr = CreateAttribute();
Node* node = attr;
attr->setTextContent(Value());
EXPECT_EQ(Value(), attr->value());
EXPECT_EQ(Value(), node->nodeValue());
EXPECT_EQ(Value(), attr->textContent());
}
} // namespace blink
| 710
|
471
|
<gh_stars>100-1000
package com.liulishuo.engzo.share;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.SearchCondition;
import android.support.test.uiautomator.UiObject2;
import android.support.test.uiautomator.UiObjectNotFoundException;
import com.liulishuo.engzo.BaseTestCase;
import static android.support.test.uiautomator.Until.findObject;
import static com.liulishuo.engzo.Constant.APP_PACKAGE_NAME;
import static com.liulishuo.engzo.Constant.MAX_TIMEOUT;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* @author Kale
* @date 2018/9/15
*/
public abstract class AbsShareTestCase extends BaseTestCase {
public abstract void shareCanceled_by_clickCancelButton();
public abstract void shareCanceled_by_pressBackButton();
public abstract void shareSuccess_by_clickSendButton() throws UiObjectNotFoundException;
public void assertShareIsSucceed() {
SearchCondition<UiObject2> infoTv = findObject(By.res(APP_PACKAGE_NAME, "result"));
assertThat(device.wait(infoTv, MAX_TIMEOUT).getText(), is(equalTo("分享成功")));
}
public void assertShareIsCanceled() {
SearchCondition<UiObject2> infoTv = findObject(By.res(APP_PACKAGE_NAME, "result"));
assertThat(device.wait(infoTv, MAX_TIMEOUT).getText(), is(equalTo("取消分享")));
}
}
| 522
|
2,674
|
// Copyright (c) 2018 Microsoft Corporation
// Licensed under the MIT license.
// Author: <NAME> <<EMAIL>>
#ifndef ZONED_BRIDGE_C_FUNCTIONS_HPP
#define ZONED_BRIDGE_C_FUNCTIONS_HPP
#include "ebm_native.h"
#include "bridge_c.h"
#include "zones.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
INTERNAL_IMPORT_EXPORT_INCLUDE ErrorEbmType MAKE_ZONED_C_FUNCTION_NAME(ApplyTraining)(
const LossWrapper * const pLossWrapper,
ApplyTrainingData * const pData
);
INTERNAL_IMPORT_EXPORT_INCLUDE ErrorEbmType MAKE_ZONED_C_FUNCTION_NAME(ApplyValidation)(
const LossWrapper * const pLossWrapper,
ApplyValidationData * const pData
);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // ZONED_BRIDGE_C_FUNCTIONS_HPP
| 294
|
675
|
#ifndef CLASS_NCINE_TEXTURELOADERRAW
#define CLASS_NCINE_TEXTURELOADERRAW
#include "ITextureLoader.h"
namespace ncine {
/// A texture loader used to specify a raw format when loading texels
class TextureLoaderRaw : public ITextureLoader
{
public:
TextureLoaderRaw(int width, int height, int mipMapCount, GLenum internalFormat);
};
}
#endif
| 111
|
1,615
|
/**
* Created by MomoLuaNative.
* Copyright (c) 2019, Momo Group. All rights reserved.
*
* This source code is licensed under the MIT.
* For the full copyright and license information,please view the LICENSE file in the root directory of this source tree.
*/
package com.immomo.luanative.hotreload.client.impl;
import com.immomo.luanative.hotreload.client.iClient;
import com.immomo.luanative.hotreload.client.iClientListener;
import com.immomo.luanative.hotreload.io.ReaderFactory;
import com.immomo.luanative.hotreload.io.WriterFactory;
import com.immomo.luanative.hotreload.io.iMessageListener;
import com.immomo.luanative.hotreload.io.iReader;
import com.immomo.luanative.hotreload.io.iWriter;
import com.immomo.luanative.hotreload.transport.iTransporter;
public class ClientImpl implements iClient {
private iReader reader = ReaderFactory.getInstance();
private iWriter writer = WriterFactory.getInstance();
private iTransporter transporter;
private iClientListener listener;
private boolean running = false;
public ClientImpl(iTransporter transporter, iClientListener listener) {
this.transporter = transporter;
this.listener = listener;
}
@Override
public boolean start() {
if (running) return true;
running = true;
if (this.transporter != null) {
this.transporter.start(this);
return true;
}
return false;
}
@Override
public void stop() {
if (!running) return;
running = false;
if (this.transporter != null) {
this.transporter.stop();
}
}
@Override
public boolean isRunning() {
return running;
}
@Override
public void read(byte[] data) {
reader.read(data);
}
@Override
public void onMessage(iMessageListener listener) {
reader.onMessage(listener);
}
@Override
public void writeData(byte[] data) {
writer.writeData(data);
}
@Override
public void writeLog(String log, String entryFilePath) {
writer.writeLog(log, entryFilePath);
}
@Override
public void writeError(String error, String entryFilePath) {
writer.writeError(error, entryFilePath);
}
@Override
public void writeDevice() {
writer.writeDevice();
}
@Override
public byte[] popData() {
return writer.popData();
}
@Override
public void onConnected() {
if (listener != null) {
listener.clientOnConnected(this);
}
}
@Override
public byte[] popSendData() {
return writer.popData();
}
@Override
public void didReceiveData(byte[] data) {
reader.read(data);
}
@Override
public void disconnecte(String error) {
if (listener != null) {
listener.clientDisconnectedWithError(this, error);
}
}
}
| 1,132
|
1,056
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.php.project.ui.wizards;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.nio.charset.Charset;
import javax.swing.JPanel;
import javax.swing.MutableComboBoxModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.netbeans.modules.php.api.PhpVersion;
import org.netbeans.modules.php.project.ui.LocalServer;
import org.netbeans.modules.php.project.ui.ProjectNameProvider;
import org.openide.WizardDescriptor;
import org.openide.util.ChangeSupport;
/**
* @author <NAME>
*/
public abstract class ConfigurableProjectPanel extends JPanel implements ProjectNameProvider, DocumentListener, ChangeListener, ActionListener {
private static final int STEP_INDEX = 0;
private final ChangeSupport changeSupport = new ChangeSupport(this);
protected final ProjectFolder projectFolderComponent;
public ConfigurableProjectPanel(ConfigureProjectPanel wizardPanel) {
projectFolderComponent = new ProjectFolder(this, wizardPanel);
projectFolderComponent.addProjectFolderListener(this);
setName(wizardPanel.getSteps()[STEP_INDEX]);
putClientProperty(WizardDescriptor.PROP_CONTENT_SELECTED_INDEX, STEP_INDEX);
// Step name (actually the whole list for reference).
putClientProperty(WizardDescriptor.PROP_CONTENT_DATA, wizardPanel.getSteps());
}
// abstract methods
public abstract void setProjectName(String projectName);
public abstract String getSourcesFolder();
public abstract LocalServer getSourcesLocation();
public abstract void selectSourcesLocation(LocalServer localServer);
public abstract MutableComboBoxModel<LocalServer> getLocalServerModel();
public abstract void setLocalServerModel(MutableComboBoxModel<LocalServer> localServers);
public abstract PhpVersion getPhpVersion();
public abstract void setPhpVersion(PhpVersion phpVersion);
public abstract Charset getEncoding();
public abstract void setEncoding(Charset encoding);
public abstract void setState(boolean enabled);
public abstract boolean getState();
public String getProjectFolder() {
return projectFolderComponent.getProjectFolder();
}
public void setProjectFolder(String projectFolder) {
projectFolderComponent.setProjectFolder(projectFolder);
}
public boolean isProjectFolderUsed() {
return projectFolderComponent.isProjectFolderUsed();
}
public void setProjectFolderUsed(boolean used) {
projectFolderComponent.setProjectFolderUsed(used);
}
public void addConfigureProjectListener(ChangeListener listener) {
changeSupport.addChangeListener(listener);
}
public void removeConfigureProjectListener(ChangeListener listener) {
changeSupport.removeChangeListener(listener);
}
// listeners
@Override
public void insertUpdate(DocumentEvent e) {
processUpdate();
}
@Override
public void removeUpdate(DocumentEvent e) {
processUpdate();
}
@Override
public void changedUpdate(DocumentEvent e) {
processUpdate();
}
private void processUpdate() {
changeSupport.fireChange();
}
@Override
public void stateChanged(ChangeEvent e) {
changeSupport.fireChange();
}
@Override
public void actionPerformed(ActionEvent e) {
changeSupport.fireChange();
}
}
| 1,313
|
30,023
|
{
"state": {
"wolflink__state": {
"1_x_warmwasser": "1 x DHW",
"abgasklappe": "Amortecedor de g\u00e1s de combust\u00e3o",
"absenkbetrieb": "Modo de recuo",
"absenkstop": "Parada de recuo",
"aktiviert": "Ativado",
"antilegionellenfunktion": "Fun\u00e7\u00e3o anti-legionela",
"at_abschaltung": "Desligamento OT",
"at_frostschutz": "Prote\u00e7\u00e3o contra geada OT",
"aus": "Desativado",
"auto": "Auto",
"auto_off_cool": "AutoOffCool",
"auto_on_cool": "AutoOnCool",
"automatik_aus": "Automatic OFF",
"automatik_ein": "Automatic ON",
"bereit_keine_ladung": "Pronto, n\u00e3o carregando",
"betrieb_ohne_brenner": "Trabalhando sem bico",
"cooling": "Resfriamento",
"deaktiviert": "Inativo",
"dhw_prior": "DHWPrior",
"eco": "Econ\u00f4mico",
"ein": "Habilitado",
"estrichtrocknung": "Secagem da mesa",
"externe_deaktivierung": "Desativa\u00e7\u00e3o externa",
"fernschalter_ein": "Controle remoto ativado",
"frost_heizkreis": "Congelamento do circuito de aquecimento",
"frost_warmwasser": "Geada DHW",
"frostschutz": "Prote\u00e7\u00e3o contra geada",
"gasdruck": "Press\u00e3o do g\u00e1s",
"glt_betrieb": "Modo BMS",
"gradienten_uberwachung": "Monitoramento de gradiente",
"heizbetrieb": "Modo de aquecimento",
"heizgerat_mit_speicher": "Boiler com cilindro",
"heizung": "Aquecimento",
"initialisierung": "Inicializa\u00e7\u00e3o",
"kalibration": "Calibra\u00e7\u00e3o",
"kalibration_heizbetrieb": "Calibra\u00e7\u00e3o do modo de aquecimento",
"kalibration_kombibetrieb": "Calibra\u00e7\u00e3o do modo combinado",
"kalibration_warmwasserbetrieb": "Calibra\u00e7\u00e3o DHW",
"kaskadenbetrieb": "Opera\u00e7\u00e3o em cascata",
"kombibetrieb": "Modo combinado",
"kombigerat": "Boiler combinado",
"kombigerat_mit_solareinbindung": "Boiler combinado com integra\u00e7\u00e3o solar",
"mindest_kombizeit": "Tempo m\u00ednimo combinado",
"nachlauf_heizkreispumpe": "Funcionamento da bomba do circuito de aquecimento",
"nachspulen": "P\u00f3s-lavagem",
"nur_heizgerat": "Apenas Boiler",
"parallelbetrieb": "Modo paralelo",
"partymodus": "Modo festa",
"perm_cooling": "PermCooling",
"permanent": "Permanente",
"permanentbetrieb": "Modo permanente",
"reduzierter_betrieb": "Modo limitado",
"rt_abschaltung": "Desligamento do RT",
"rt_frostschutz": "RT prote\u00e7\u00e3o contra congelamento",
"ruhekontakt": "Descansar contato",
"schornsteinfeger": "Teste de emiss\u00f5es",
"smart_grid": "SmartGrid",
"smart_home": "SmartHome",
"softstart": "In\u00edcio suave",
"solarbetrieb": "Modo solar",
"sparbetrieb": "Modo econ\u00f4mico",
"sparen": "Economia",
"spreizung_hoch": "dT muito largo",
"spreizung_kf": "Espalhe KF",
"stabilisierung": "Estabiliza\u00e7\u00e3o",
"standby": "Em espera",
"start": "Iniciar",
"storung": "Falha",
"taktsperre": "Anti-ciclo",
"telefonfernschalter": "Interruptor remoto do telefone",
"test": "Teste",
"tpw": "TPW",
"urlaubsmodus": "Modo de f\u00e9rias",
"ventilprufung": "Teste de v\u00e1lvula",
"vorspulen": "Enx\u00e1gue de entrada",
"warmwasser": "DHW",
"warmwasser_schnellstart": "in\u00edcio r\u00e1pido DHW",
"warmwasserbetrieb": "Modo DHW",
"warmwassernachlauf": "DHW funcionando",
"warmwasservorrang": "Prioridade de DHW",
"zunden": "Igni\u00e7\u00e3o"
}
}
}
| 2,435
|
360
|
<filename>src/include/postgres.h
/* -------------------------------------------------------------------------
*
* postgres.h
* Primary include file for PostgreSQL server .c files
*
* This should be the first file included by PostgreSQL backend modules.
* Client-side code should include postgres_fe.h instead.
*
*
* Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
* Portions Copyright (c) 1995, Regents of the University of California
* Portions Copyright (c) 2010-2012 Postgres-XC Development Group
*
* src/include/postgres.h
*
* -------------------------------------------------------------------------
*/
/*
* ----------------------------------------------------------------
* TABLE OF CONTENTS
*
* When adding stuff to this file, please try to put stuff
* into the relevant section, or add new sections as appropriate.
*
* section description
* ------- ------------------------------------------------
* 1) variable-length datatypes (TOAST support)
* 2) datum type + support macros
* 3) exception handling definitions
*
* NOTES
*
* In general, this file should contain declarations that are widely needed
* in the backend environment, but are of no interest outside the backend.
*
* Simple type definitions live in c.h, where they are shared with
* postgres_fe.h. We do that since those type definitions are needed by
* frontend modules that want to deal with binary data transmission to or
* from the backend. Type definitions in this file should be for
* representations that never escape the backend, such as Datum or
* TOASTed varlena objects.
*
* ----------------------------------------------------------------
*/
#ifndef POSTGRES_H
#define POSTGRES_H
#ifdef PC_LINT
#define THR_LOCAL
#endif
#include "c.h"
#include "utils/elog.h"
#include "utils/palloc.h"
#include "storage/spin.h"
#ifndef WIN32
#include <cxxabi.h>
#endif /* win-odbc */
#ifndef HDFS_FDW
#define HDFS_FDW "hdfs_fdw"
#endif
#ifndef HDFS
#define HDFS "hdfs"
#endif
#ifndef OBS
#define OBS "obs"
#endif
#ifndef DIST_FDW
#define DIST_FDW "dist_fdw"
#endif
#ifndef MYSQL_FDW
#define MYSQL_FDW "mysql_fdw"
#endif
#ifndef ORACLE_FDW
#define ORACLE_FDW "oracle_fdw"
#endif
#ifndef POSTGRES_FDW
#define POSTGRES_FDW "postgres_fdw"
#endif
#ifndef MOT_FDW
#define MOT_FDW "mot_fdw"
#endif
#ifndef MOT_FDW_SERVER
#define MOT_FDW_SERVER "mot_server"
#endif
#ifndef DFS_FDW
#define DFS_FDW "dfs_fdw"
#endif
#ifndef LOG_FDW
#define LOG_FDW "log_fdw"
#define LOG_SRV "log_srv"
#endif /* LOG_FDW */
#ifndef GC_FDW
#define GC_FDW "gc_fdw"
#endif
#include "securec.h"
#include "securec_check.h"
#define AUXILIARY_BACKENDS 20
/* the maximum number of autovacuum launcher thread */
#define AV_LAUNCHER_PROCS 2
#define STREAM_RESERVE_PROC_TIMES (16)
/* this struct is used to store connection info got from pool */
typedef struct {
/* hostname of the connection */
nameData host;
/* port of the connection */
int port;
} PoolConnInfo;
/* this enum type is used to mark om online operation. */
typedef enum { OM_ONLINE_EXPANSION, OM_ONLINE_NODE_REPLACE } OM_ONLINE_STATE;
extern void reload_configfile(void);
extern void reload_online_pooler(void);
extern OM_ONLINE_STATE get_om_online_state(void);
/* ----------------------------------------------------------------
* Section 1: variable-length datatypes (TOAST support)
* ----------------------------------------------------------------
*/
/*
* struct varatt_external is a "TOAST pointer", that is, the information
* needed to fetch a stored-out-of-line Datum. The data is compressed
* if and only if va_extsize < va_rawsize - VARHDRSZ. This struct must not
* contain any padding, because we sometimes compare pointers using memcmp.
*
* Note that this information is stored unaligned within actual tuples, so
* you need to memcpy from the tuple into a local struct variable before
* you can look at these fields! (The reason we use memcmp is to avoid
* having to do that just to detect equality of two TOAST pointers...)
*/
typedef struct varatt_external {
int32 va_rawsize; /* Original data size (includes header) */
int32 va_extsize; /* External saved size (doesn't) */
Oid va_valueid; /* Unique ID of value within TOAST table */
Oid va_toastrelid; /* RelID of TOAST table containing it */
} varatt_external;
/*
* Out-of-line Datum thats stored in memory in contrast to varatt_external
* pointers which points to data in an external toast relation.
*
* Note that just as varatt_external's this is stored unaligned within the
* tuple.
*/
typedef struct varatt_indirect {
struct varlena* pointer; /* Pointer to in-memory varlena */
} varatt_indirect;
/*
* Type of external toast datum stored. The peculiar value for VARTAG_ONDISK
* comes from the requirement for on-disk compatibility with the older
* definitions of varattrib_1b_e where v_tag was named va_len_1be...
*/
typedef enum vartag_external { VARTAG_INDIRECT = 1, VARTAG_BUCKET = 8, VARTAG_ONDISK = 18 } vartag_external;
#define VARTAG_SIZE(tag) \
((tag) == VARTAG_INDIRECT ? sizeof(varatt_indirect) : \
(tag) == VARTAG_ONDISK ? sizeof(varatt_external) : \
(tag) == VARTAG_BUCKET ? sizeof(varatt_external) + sizeof(int2) : \
TrapMacro(true, "unknown vartag"))
/*
* These structs describe the header of a varlena object that may have been
* TOASTed. Generally, don't reference these structs directly, but use the
* macros below.
*
* We use separate structs for the aligned and unaligned cases because the
* compiler might otherwise think it could generate code that assumes
* alignment while touching fields of a 1-byte-header varlena.
*/
typedef union {
struct /* Normal varlena (4-byte length) */
{
uint32 va_header;
char va_data[FLEXIBLE_ARRAY_MEMBER];
} va_4byte;
struct /* Compressed-in-line format */
{
uint32 va_header;
uint32 va_rawsize; /* Original data size (excludes header) */
char va_data[FLEXIBLE_ARRAY_MEMBER]; /* Compressed data */
} va_compressed;
} varattrib_4b;
typedef struct {
uint8 va_header;
char va_data[FLEXIBLE_ARRAY_MEMBER]; /* Data begins here */
} varattrib_1b;
#define TRY_LOCK_ACCOUNT 0
#define TRY_UNLOCK_ACCOUNT 1
#define MAX_USER_NUM 100
typedef struct accounttask {
Oid roleid;
int failedcount;
} AccountTask;
/* inline portion of a short varlena pointing to an external resource */
typedef struct {
uint8 va_header; /* Always 0x80 or 0x01 */
uint8 va_tag; /* Type of datum */
char va_data[FLEXIBLE_ARRAY_MEMBER]; /* Type-specific data */
} varattrib_1b_e;
#ifndef HAVE_DATABASE_TYPE
#define HAVE_DATABASE_TYPE
/*Type of database; increase for sql compatibility*/
typedef enum {
A_FORMAT = 0x0001,
B_FORMAT = 0x0002,
C_FORMAT = 0x0004,
PG_FORMAT = 0x0008
} DatabaseType;
#define IS_CMPT(cmpt, flag) (((uint32)cmpt & (uint32)(flag)) != 0)
#define DB_IS_CMPT(flag) IS_CMPT(u_sess->attr.attr_sql.sql_compatibility, (flag))
#endif /* HAVE_DATABASE_TYPE */
typedef enum { EXPLAIN_NORMAL, EXPLAIN_PRETTY, EXPLAIN_SUMMARY, EXPLAIN_RUN } ExplainStyle;
typedef enum { SKEW_OPT_OFF, SKEW_OPT_NORMAL, SKEW_OPT_LAZY } SkewStrategy;
typedef enum { RESOURCE_TRACK_NONE, RESOURCE_TRACK_QUERY, RESOURCE_TRACK_OPERATOR } ResourceTrackOption;
typedef enum {
CODEGEN_PARTIAL, /* allow to call c-function in codegen */
CODEGEN_PURE /* do not allow to call c-function in codegen */
} CodegenStrategy;
typedef enum {
MEMORY_TRACKING_NONE = 0, /* not to track the memory usage */
MEMORY_TRACKING_PEAKMEMORY,
MEMORY_TRACKING_NORMAL, /* just update the peak information internal */
MEMORY_TRACKING_EXECUTOR, /* to logging the memory information in executor */
MEMORY_TRACKING_FULLEXEC /* to logging the all memory context information in executor */
} MemoryTrackingStyle;
/*
* Bit layouts for varlena headers on big-endian machines:
*
* 00xxxxxx 4-byte length word, aligned, uncompressed data (up to 1G)
* 01xxxxxx 4-byte length word, aligned, *compressed* data (up to 1G)
* 10000000 1-byte length word, unaligned, TOAST pointer
* 1xxxxxxx 1-byte length word, unaligned, uncompressed data (up to 126b)
*
* Bit layouts for varlena headers on little-endian machines:
*
* xxxxxx00 4-byte length word, aligned, uncompressed data (up to 1G)
* xxxxxx10 4-byte length word, aligned, *compressed* data (up to 1G)
* 00000001 1-byte length word, unaligned, TOAST pointer
* xxxxxxx1 1-byte length word, unaligned, uncompressed data (up to 126b)
*
* The "xxx" bits are the length field (which includes itself in all cases).
* In the big-endian case we mask to extract the length, in the little-endian
* case we shift. Note that in both cases the flag bits are in the physically
* first byte. Also, it is not possible for a 1-byte length word to be zero;
* this lets us disambiguate alignment padding bytes from the start of an
* unaligned datum. (We now *require* pad bytes to be filled with zero!)
*/
/*
* Endian-dependent macros. These are considered internal --- use the
* external macros below instead of using these directly.
*
* Note: IS_1B is true for external toast records but VARSIZE_1B will return 0
* for such records. Hence you should usually check for IS_EXTERNAL before
* checking for IS_1B.
*/
#ifdef WORDS_BIGENDIAN
#define VARATT_IS_4B(PTR) ((((varattrib_1b*)(PTR))->va_header & 0x80) == 0x00)
#define VARATT_IS_4B_U(PTR) ((((varattrib_1b*)(PTR))->va_header & 0xC0) == 0x00)
#define VARATT_IS_4B_C(PTR) ((((varattrib_1b*)(PTR))->va_header & 0xC0) == 0x40)
#define VARATT_IS_1B(PTR) ((((varattrib_1b*)(PTR))->va_header & 0x80) == 0x80)
#define VARATT_IS_1B_E(PTR) ((((varattrib_1b*)(PTR))->va_header) == 0x80)
#define VARATT_NOT_PAD_BYTE(PTR) (*((uint8*)(PTR)) != 0)
/* VARSIZE_4B() should only be used on known-aligned data */
#define VARSIZE_4B(PTR) (((varattrib_4b*)(PTR))->va_4byte.va_header & 0x3FFFFFFF)
#define VARSIZE_1B(PTR) (((varattrib_1b*)(PTR))->va_header & 0x7F)
#define VARSIZE_1B_E(PTR) (((varattrib_1b_e*)(PTR))->va_len_1be)
#define SET_VARSIZE_4B(PTR, len) (((varattrib_4b*)(PTR))->va_4byte.va_header = (len)&0x3FFFFFFF)
#define SET_VARSIZE_4B_C(PTR, len) (((varattrib_4b*)(PTR))->va_4byte.va_header = ((len)&0x3FFFFFFF) | 0x40000000)
#define SET_VARSIZE_1B(PTR, len) (((varattrib_1b*)(PTR))->va_header = (len) | 0x80)
#define SET_VARTAG_1B_E(PTR, tag) (((varattrib_1b_e*)(PTR))->va_header = 0x80, ((varattrib_1b_e*)(PTR))->va_tag = (tag))
#else /* !WORDS_BIGENDIAN */
#define VARATT_IS_4B(PTR) ((((varattrib_1b*)(PTR))->va_header & 0x01) == 0x00)
#define VARATT_IS_4B_U(PTR) ((((varattrib_1b*)(PTR))->va_header & 0x03) == 0x00)
#define VARATT_IS_4B_C(PTR) ((((varattrib_1b*)(PTR))->va_header & 0x03) == 0x02)
#define VARATT_IS_1B(PTR) ((((varattrib_1b*)(PTR))->va_header & 0x01) == 0x01)
#define VARATT_IS_1B_E(PTR) ((((varattrib_1b*)(PTR))->va_header) == 0x01)
#define VARATT_NOT_PAD_BYTE(PTR) (*((uint8*)(PTR)) != 0)
/* VARSIZE_4B() should only be used on known-aligned data */
#define VARSIZE_4B(PTR) ((((varattrib_4b*)(PTR))->va_4byte.va_header >> 2) & 0x3FFFFFFF)
#define VARSIZE_1B(PTR) ((((varattrib_1b*)(PTR))->va_header >> 1) & 0x7F)
#define VARTAG_1B_E(PTR) (((varattrib_1b_e*)(PTR))->va_tag)
#define SET_VARSIZE_4B(PTR, len) (((varattrib_4b*)(PTR))->va_4byte.va_header = (((uint32)(len)) << 2))
#define SET_VARSIZE_4B_C(PTR, len) (((varattrib_4b*)(PTR))->va_4byte.va_header = (((uint32)(len)) << 2) | 0x02)
#define SET_VARSIZE_1B(PTR, len) (((varattrib_1b*)(PTR))->va_header = (((uint8)(len)) << 1) | 0x01)
#define SET_VARTAG_1B_E(PTR, tag) (((varattrib_1b_e*)(PTR))->va_header = 0x01, ((varattrib_1b_e*)(PTR))->va_tag = (tag))
#endif /* WORDS_BIGENDIAN */
#define VARHDRSZ_SHORT offsetof(varattrib_1b, va_data)
#define VARATT_SHORT_MAX 0x7F
#define VARATT_CAN_MAKE_SHORT(PTR) \
(VARATT_IS_4B_U(PTR) && (VARSIZE(PTR) - VARHDRSZ + VARHDRSZ_SHORT) <= VARATT_SHORT_MAX)
#define VARATT_CONVERTED_SHORT_SIZE(PTR) (VARSIZE(PTR) - VARHDRSZ + VARHDRSZ_SHORT)
#define VARHDRSZ_EXTERNAL offsetof(varattrib_1b_e, va_data)
#define VARDATA_4B(PTR) (((varattrib_4b*)(PTR))->va_4byte.va_data)
#define VARDATA_4B_C(PTR) (((varattrib_4b*)(PTR))->va_compressed.va_data)
#define VARDATA_1B(PTR) (((varattrib_1b*)(PTR))->va_data)
#define VARDATA_1B_E(PTR) (((varattrib_1b_e*)(PTR))->va_data)
#define VARRAWSIZE_4B_C(PTR) (((varattrib_4b*)(PTR))->va_compressed.va_rawsize)
/* Externally visible macros */
/*
* VARDATA, VARSIZE, and SET_VARSIZE are the recommended API for most code
* for varlena datatypes. Note that they only work on untoasted,
* 4-byte-header Datums!
*
* Code that wants to use 1-byte-header values without detoasting should
* use VARSIZE_ANY/VARSIZE_ANY_EXHDR/VARDATA_ANY. The other macros here
* should usually be used only by tuple assembly/disassembly code and
* code that specifically wants to work with still-toasted Datums.
*
* WARNING: It is only safe to use VARDATA_ANY() -- typically with
* PG_DETOAST_DATUM_PACKED() -- if you really don't care about the alignment.
* Either because you're working with something like text where the alignment
* doesn't matter or because you're not going to access its constituent parts
* and just use things like memcpy on it anyways.
*/
#define VARDATA(PTR) VARDATA_4B(PTR)
#define VARSIZE(PTR) VARSIZE_4B(PTR)
#define VARSIZE_SHORT(PTR) VARSIZE_1B(PTR)
#define VARDATA_SHORT(PTR) VARDATA_1B(PTR)
#define VARTAG_EXTERNAL(PTR) VARTAG_1B_E(PTR)
#define VARSIZE_EXTERNAL(PTR) (VARHDRSZ_EXTERNAL + VARTAG_SIZE(VARTAG_EXTERNAL(PTR)))
#define VARDATA_EXTERNAL(PTR) VARDATA_1B_E(PTR)
#define VARATT_IS_COMPRESSED(PTR) VARATT_IS_4B_C(PTR)
#define VARATT_IS_EXTERNAL(PTR) VARATT_IS_1B_E(PTR)
#define VARATT_IS_EXTERNAL_ONDISK(PTR) (VARATT_IS_EXTERNAL(PTR) && VARTAG_EXTERNAL(PTR) == VARTAG_ONDISK)
#define VARATT_IS_EXTERNAL_INDIRECT(PTR) (VARATT_IS_EXTERNAL(PTR) && VARTAG_EXTERNAL(PTR) == VARTAG_INDIRECT)
#define VARATT_IS_EXTERNAL_BUCKET(PTR) \
(VARATT_IS_EXTERNAL(PTR) && VARTAG_EXTERNAL(PTR) == VARTAG_BUCKET)
#define VARATT_IS_EXTERNAL_ONDISK_B(PTR) \
(VARATT_IS_EXTERNAL_ONDISK(PTR) || VARATT_IS_EXTERNAL_BUCKET(PTR))
#define VARATT_IS_SHORT(PTR) VARATT_IS_1B(PTR)
#define VARATT_IS_EXTENDED(PTR) (!VARATT_IS_4B_U(PTR))
#define SET_VARSIZE(PTR, len) SET_VARSIZE_4B(PTR, len)
#define SET_VARSIZE_SHORT(PTR, len) SET_VARSIZE_1B(PTR, len)
#define SET_VARSIZE_COMPRESSED(PTR, len) SET_VARSIZE_4B_C(PTR, len)
#define SET_VARTAG_EXTERNAL(PTR, tag) SET_VARTAG_1B_E(PTR, tag)
#define VARSIZE_ANY(PTR) \
(VARATT_IS_1B_E(PTR) ? VARSIZE_EXTERNAL(PTR) : (VARATT_IS_1B(PTR) ? VARSIZE_1B(PTR) : VARSIZE_4B(PTR)))
#define VARSIZE_ANY_EXHDR(PTR) \
(VARATT_IS_1B_E(PTR) ? VARSIZE_EXTERNAL(PTR) - VARHDRSZ_EXTERNAL \
: (VARATT_IS_1B(PTR) ? VARSIZE_1B(PTR) - VARHDRSZ_SHORT : VARSIZE_4B(PTR) - VARHDRSZ))
/* caution: this will not work on an external or compressed-in-line Datum */
/* caution: this will return a possibly unaligned pointer */
#define VARDATA_ANY(PTR) (VARATT_IS_1B(PTR) ? VARDATA_1B(PTR) : VARDATA_4B(PTR))
/* ----------------------------------------------------------------
* Section 2: datum type + support macros
* ----------------------------------------------------------------
*/
/*
* Port Notes:
* openGauss makes the following assumptions about datatype sizes:
*
* sizeof(Datum) == sizeof(void *) == 4 or 8
* sizeof(char) == 1
* sizeof(short) == 2
*
* When a type narrower than Datum is stored in a Datum, we place it in the
* low-order bits and are careful that the DatumGetXXX macro for it discards
* the unused high-order bits (as opposed to, say, assuming they are zero).
* This is needed to support old-style user-defined functions, since depending
* on architecture and compiler, the return value of a function returning char
* or short may contain garbage when called as if it returned Datum.
*/
typedef uintptr_t Datum;
#define SIZEOF_DATUM SIZEOF_VOID_P
typedef Datum* DatumPtr;
#define GET_1_BYTE(datum) (((Datum)(datum)) & 0x000000ff)
#define GET_2_BYTES(datum) (((Datum)(datum)) & 0x0000ffff)
#define GET_4_BYTES(datum) (((Datum)(datum)) & 0xffffffff)
#if SIZEOF_DATUM == 8
#define GET_8_BYTES(datum) ((Datum)(datum))
#endif
#define SET_1_BYTE(value) (((Datum)(value)) & 0x000000ff)
#define SET_2_BYTES(value) (((Datum)(value)) & 0x0000ffff)
#define SET_4_BYTES(value) (((Datum)(value)) & 0xffffffff)
#if SIZEOF_DATUM == 8
#define SET_8_BYTES(value) ((Datum)(value))
#endif
/*
* DatumGetBool
* Returns boolean value of a datum.
*
* Note: any nonzero value will be considered TRUE, but we ignore bits to
* the left of the width of bool, per comment above.
*/
#define DatumGetBool(X) ((bool)(((bool)(X)) != 0))
/*
* BoolGetDatum
* Returns datum representation for a boolean.
*
* Note: any nonzero value will be considered TRUE.
*/
#ifndef BoolGetDatum
#define BoolGetDatum(X) ((Datum)((X) ? 1 : 0))
#endif
/*
* DatumGetChar
* Returns character value of a datum.
*/
#define DatumGetChar(X) ((char)GET_1_BYTE(X))
/*
* CharGetDatum
* Returns datum representation for a character.
*/
#define CharGetDatum(X) ((Datum)SET_1_BYTE((unsigned char)(X)))
/*
* Int8GetDatum
* Returns datum representation for an 8-bit integer.
*/
#define Int8GetDatum(X) ((Datum)SET_1_BYTE((uint8)X))
/*
* DatumGetInt8
* Returns 8-bit integer value of a datum.
*/
#define DatumGetInt8(X) ((int8)GET_1_BYTE(X))
/*
* DatumGetUInt8
* Returns 8-bit unsigned integer value of a datum.
*/
#define DatumGetUInt8(X) ((uint8)GET_1_BYTE(X))
/*
* UInt8GetDatum
* Returns datum representation for an 8-bit unsigned integer.
*/
#define UInt8GetDatum(X) ((Datum)SET_1_BYTE((uint8)(X)))
/*
* DatumGetInt16
* Returns 16-bit integer value of a datum.
*/
#define DatumGetInt16(X) ((int16)GET_2_BYTES(X))
/*
* Int16GetDatum
* Returns datum representation for a 16-bit integer.
*/
#define Int16GetDatum(X) ((Datum)SET_2_BYTES((uint16)(X)))
/*
* DatumGetUInt16
* Returns 16-bit unsigned integer value of a datum.
*/
#define DatumGetUInt16(X) ((uint16)GET_2_BYTES(X))
/*
* UInt16GetDatum
* Returns datum representation for a 16-bit unsigned integer.
*/
#define UInt16GetDatum(X) ((Datum)SET_2_BYTES(X))
/*
* DatumGetInt32
* Returns 32-bit integer value of a datum.
*/
#define DatumGetInt32(X) ((int32)GET_4_BYTES(X))
/*
* Int32GetDatum
* Returns datum representation for a 32-bit integer.
*/
#define Int32GetDatum(X) ((Datum)SET_4_BYTES((uint32)(X)))
/*
* DatumGetUInt32
* Returns 32-bit unsigned integer value of a datum.
*/
#define DatumGetUInt32(X) ((uint32)GET_4_BYTES(X))
/*
* UInt32GetDatum
* Returns datum representation for a 32-bit unsigned integer.
*/
#define UInt32GetDatum(X) ((Datum)SET_4_BYTES(X))
/*
* DatumGetObjectId
* Returns object identifier value of a datum.
*/
#define DatumGetObjectId(X) ((Oid)GET_4_BYTES(X))
/*
* ObjectIdGetDatum
* Returns datum representation for an object identifier.
*/
#define ObjectIdGetDatum(X) ((Datum)SET_4_BYTES(X))
/*
* DatumGetTransactionId
* Returns transaction identifier value of a datum.
*/
#define DatumGetTransactionId(X) (DatumGetUInt64(X))
#define DatumGetShortTransactionId(X) ((ShortTransactionId)GET_4_BYTES(X))
/*
* TransactionIdGetDatum
* Returns datum representation for a transaction identifier.
*/
#define TransactionIdGetDatum(X) (UInt64GetDatum(X))
#define ShortTransactionIdGetDatum(X) ((Datum)SET_4_BYTES((X)))
/*
* DatumGetCommandId
* Returns command identifier value of a datum.
*/
#define DatumGetCommandId(X) ((CommandId)GET_4_BYTES(X))
/*
* CommandIdGetDatum
* Returns datum representation for a command identifier.
*/
#define CommandIdGetDatum(X) ((Datum)SET_4_BYTES(X))
/*
* DatumGetPointer
* Returns pointer value of a datum.
*/
#define DatumGetPointer(X) ((Pointer)(X))
/*
* PointerGetDatum
* Returns datum representation for a pointer.
*/
#ifndef PointerGetDatum
#define PointerGetDatum(X) ((Datum)(X))
#endif
/*
* DatumGetCString
* Returns C string (null-terminated string) value of a datum.
*
* Note: C string is not a full-fledged openGauss type at present,
* but type input functions use this conversion for their inputs.
*/
#define DatumGetCString(X) ((char*)DatumGetPointer(X))
/*
* CStringGetDatum
* Returns datum representation for a C string (null-terminated string).
*
* Note: C string is not a full-fledged openGauss type at present,
* but type output functions use this conversion for their outputs.
* Note: CString is pass-by-reference; caller must ensure the pointed-to
* value has adequate lifetime.
*/
#define CStringGetDatum(X) PointerGetDatum(X)
/*
* DatumGetName
* Returns name value of a datum.
*/
#define DatumGetName(X) ((Name)DatumGetPointer(X))
/*
* NameGetDatum
* Returns datum representation for a name.
*
* Note: Name is pass-by-reference; caller must ensure the pointed-to
* value has adequate lifetime.
*/
#define NameGetDatum(X) PointerGetDatum(X)
/*
* DatumGetInt64
* Returns 64-bit integer value of a datum.
*
* Note: this macro hides whether int64 is pass by value or by reference.
*/
#ifdef USE_FLOAT8_BYVAL
#define DatumGetInt64(X) ((int64)GET_8_BYTES(X))
#else
#define DatumGetInt64(X) (*((int64*)DatumGetPointer(X)))
#endif
#define BatchMaxSize 1000
/*
* Int64GetDatum
* Returns datum representation for a 64-bit integer.
*
* Note: if int64 is pass by reference, this function returns a reference
* to palloc'd space.
*/
#ifdef USE_FLOAT8_BYVAL
#define Int64GetDatum(X) ((Datum)SET_8_BYTES(X))
#else
extern Datum Int64GetDatum(int64 X);
#endif
/*
* DatumGetUInt64
* Returns 64-bit unsigned integer value of a datum.
*
* Note: this macro hides whether int64 is pass by value or by reference.
*/
#ifdef USE_FLOAT8_BYVAL
#define DatumGetUInt64(X) ((uint64)GET_8_BYTES(X))
#else
#define DatumGetUInt64(X) (*((uint64*)DatumGetPointer(X)))
#endif
/*
* UInt64GetDatum
* Returns datum representation for a 64-bit unsigned integer.
*
* Note: if int64 is pass by reference, this function returns a reference
* to palloc'd space.
*/
#ifdef USE_FLOAT8_BYVAL
#define UInt64GetDatum(X) ((Datum)SET_8_BYTES(X))
#else
#define UInt64GetDatum(X) Int64GetDatum((int64)(X))
#endif
/*
* DatumGetFloat4
* Returns 4-byte floating point value of a datum.
*
* Note: this macro hides whether float4 is pass by value or by reference.
*/
#ifdef USE_FLOAT4_BYVAL
extern float4 DatumGetFloat4(Datum X);
#else
#define DatumGetFloat4(X) (*((float4*)DatumGetPointer(X)))
#endif
/*
* Float4GetDatum
* Returns datum representation for a 4-byte floating point number.
*
* Note: if float4 is pass by reference, this function returns a reference
* to palloc'd space.
*/
extern Datum Float4GetDatum(float4 X);
/*
* DatumGetFloat8
* Returns 8-byte floating point value of a datum.
*
* Note: this macro hides whether float8 is pass by value or by reference.
*/
#ifdef USE_FLOAT8_BYVAL
extern float8 DatumGetFloat8(Datum X);
#else
#define DatumGetFloat8(X) (*((float8*)DatumGetPointer(X)))
#endif
/*
* Float8GetDatum
* Returns datum representation for an 8-byte floating point number.
*
* Note: if float8 is pass by reference, this function returns a reference
* to palloc'd space.
*/
extern Datum Float8GetDatum(float8 X);
/*
* Int64GetDatumFast
* Float8GetDatumFast
* Float4GetDatumFast
*
* These macros are intended to allow writing code that does not depend on
* whether int64, float8, float4 are pass-by-reference types, while not
* sacrificing performance when they are. The argument must be a variable
* that will exist and have the same value for as long as the Datum is needed.
* In the pass-by-ref case, the address of the variable is taken to use as
* the Datum. In the pass-by-val case, these will be the same as the non-Fast
* macros.
*/
#ifdef USE_FLOAT8_BYVAL
#define Int64GetDatumFast(X) Int64GetDatum(X)
#define Float8GetDatumFast(X) Float8GetDatum(X)
#else
#define Int64GetDatumFast(X) PointerGetDatum(&(X))
#define Float8GetDatumFast(X) PointerGetDatum(&(X))
#endif
#ifdef USE_FLOAT4_BYVAL
#define Float4GetDatumFast(X) Float4GetDatum(X)
#else
#define Float4GetDatumFast(X) PointerGetDatum(&(X))
#endif
#ifdef HAVE_INT64_TIMESTAMP
#define TimeGetDatum(X) Int64GetDatum(X)
#else
#define TimeGetDatum(X) Float8GetDatum(X)
#endif
/* ----------------------------------------------------------------
* Section 3: exception handling definitions
* Assert, Trap, etc macros
* ----------------------------------------------------------------
*/
#ifdef WIN32
extern THR_LOCAL bool assert_enabled;
#else
extern THR_LOCAL PGDLLIMPORT bool assert_enabled;
#endif
/*
* USE_ASSERT_CHECKING, if defined, turns on all the assertions.
* - plai 9/5/90
*
* It should _NOT_ be defined in releases or in benchmark copies
*/
/*
* Trap
* Generates an exception if the given condition is true.
*/
#define Trap(condition, errorType) \
do { \
if ((assert_enabled) && (condition)) \
ExceptionalCondition(CppAsString(condition), (errorType), __FILE__, __LINE__); \
} while (0)
/*
* TrapMacro is the same as Trap but it's intended for use in macros:
*
* #define foo(x) (AssertMacro(x != 0), bar(x))
*
* Isn't CPP fun?
*/
#define TrapMacro(condition, errorType) \
((bool)((!assert_enabled) || !(condition) || \
(ExceptionalCondition(CppAsString(condition), (errorType), __FILE__, __LINE__), 0)))
#ifdef Assert
#undef Assert
#endif
#ifdef PC_LINT
#define Assert(condition) \
do { \
if (!(bool)(condition)) \
exit(1); \
} while (0)
#ifndef AssertMacro
#define AssertMacro Assert
#endif
#define AssertArg Assert
#define DBG_ASSERT Assert
#define AssertState Assert
#else
#ifndef USE_ASSERT_CHECKING
#define Assert(condition)
#ifndef AssertMacro
#define AssertMacro(condition) ((void)true)
#endif /* AssertMacro */
#define AssertArg(condition)
#define DBG_ASSERT(condition)
#define AssertState(condition)
#elif defined(FRONTEND)
#include <assert.h>
#define Assert(p) assert(p)
#ifndef AssertMacro
#define AssertMacro(p) ((void)assert(p))
#endif
#define AssertArg(condition) assert(condition)
#define DBG_ASSERT(condition)
#define AssertState(condition) assert(condition)
#define AssertPointerAlignment(ptr, bndr) ((void)true)
#else /* USE_ASSERT_CHECKING && !FRONTEND */
#define Assert(condition) Trap(!(condition), "FailedAssertion")
#ifndef AssertMacro
#define AssertMacro(condition) ((void)TrapMacro(!(condition), "FailedAssertion"))
#endif /* AssertMacro */
#define AssertArg(condition) Trap(!(condition), "BadArgument")
#define AssertState(condition) Trap(!(condition), "BadState")
#define DBG_ASSERT Assert
#endif /* USE_ASSERT_CHECKING */
#endif /* PC_LINT */
typedef enum {
ENV_OK,
ENV_ERR_LENGTH,
ENV_ERR_NULL,
ENV_ERR_DANGER_CHARACTER
} EnvCheckResult;
extern void ExceptionalCondition(const char *conditionName, const char *errorType, const char *fileName,
int lineNumber);
extern void ConnFree(void* conn);
extern THR_LOCAL bool IsInitdb;
extern size_t mmap_threshold;
/* Set the pooler reload flag when signaled by SIGUSR1 */
void HandlePoolerReload(void);
void HandleMemoryContextDump(void);
void HandleExecutorFlag(void);
extern void start_xact_command(void);
extern void finish_xact_command(void);
extern void exec_init_poolhandles(void);
extern void InitVecFuncMap(void);
/* load ir file count for each process */
extern long codegenIRloadProcessCount;
extern pthread_mutex_t nodeDefCopyLock;
/* Job worker Process, execute procedure */
extern void execute_simple_query(const char* query_string);
/* check the value from environment variablethe to prevent command injection. */
extern void check_backend_env(const char* input_env_value);
extern EnvCheckResult check_backend_env_sigsafe(const char* input_env_value);
extern bool backend_env_valid(const char* input_env_value, const char* stamp);
extern void CleanSystemCaches(bool is_in_read_command);
/*Audit user logout*/
extern void audit_processlogout_unified();
extern void audit_processlogout(int code, Datum arg);
/* free the pointer malloced by cJSON_internal_malloc.*/
extern void cJSON_internal_free(void* pointer);
extern void InitThreadLocalWhenSessionExit();
extern void RemoveTempNamespace();
#define CacheIsProcNameArgNsp(cache) ((cache)->id == PROCNAMEARGSNSP)
#define CacheIsProcOid(cache) ((cache)->id == PROCOID)
#define IsBootingPgProc(rel) IsProcRelation(rel)
#define BootUsingBuiltinFunc true
extern int errdetail_abort(void);
void log_disconnections(int code, Datum arg);
void ResetInterruptCxt();
#define MSG_A_REPEAT_NUM_MAX 1024
#define OVERRIDE_STACK_LENGTH_MAX 1024
#ifdef ENABLE_UT
#include "lib/stringinfo.h"
extern void exec_describe_statement_message(const char* stmt_name);
extern void exec_get_ddl_params(StringInfo input_message);
#endif
#endif /* POSTGRES_H */
| 11,246
|
538
|
package com.wangjie.androidbucket.services.network.interceptor;
import com.wangjie.androidbucket.services.network.HippoRequest;
import com.wangjie.androidbucket.services.network.exception.HippoException;
/**
* @author <NAME>
* @version V1.0
* @Description
* @Createdate 14-9-24 18:08
*/
public interface Interceptor<T extends HippoRequest> {
boolean getInterruptRule(T request);
void dispatch(T request) throws HippoException;
}
| 145
|
852
|
## --
## Start with pre-defined skeleton process
## --
from PhysicsTools.PatAlgos.patTemplate_cfg import *
## ... and modify it according to the needs:
process.source.fileNames = [ '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/06ADBD4E-0E96-E011-A2FE-003048F1C836.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/06F5A72B-E195-E011-A988-001D09F231C9.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/08B4EC25-1396-E011-A4CA-003048D2C174.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/186E812D-0C96-E011-8D83-003048F11CF0.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/18FBAA04-E395-E011-AD96-001D09F24664.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/1C954EEF-1A96-E011-A306-0030487C6A66.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/2084822A-1396-E011-BCC7-003048D2BDD8.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/32C97086-1296-E011-8588-003048F11C5C.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/4620F471-1096-E011-9D47-0030487CD6D8.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/462E5C46-E495-E011-AB68-001D09F252E9.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/4A0AC5B1-DF95-E011-93C7-001D09F25041.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/5655A998-E595-E011-BA75-001D09F23D1D.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/56DA4E81-DC95-E011-835D-0030487A1990.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/5AB9C521-2D96-E011-8648-003048F117B6.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/6422B81F-D995-E011-BA28-003048F1C832.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/74B30E2A-E195-E011-A2A2-001D09F29538.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/7A81AEEF-1A96-E011-A1F6-0030487A18F2.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/8288E509-E395-E011-93F2-001D09F2960F.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/867A73F4-E295-E011-8598-003048F11CF0.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/86B21B4E-1C96-E011-9549-003048F024DE.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/8E25CC65-1096-E011-ADBB-003048F1BF68.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/9A59783C-E495-E011-A8B3-001D09F24600.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/9C51D93B-E495-E011-AA78-0030487CD184.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/9E75657D-DC95-E011-A8FF-001D09F290BF.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/A2B4BF06-E395-E011-8C8B-003048CFB40C.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/AE5CAA73-DC95-E011-BC78-003048F24A04.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/B40C9D36-0C96-E011-9584-003048D2C0F0.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/B48976EF-1A96-E011-96CD-0030487A195C.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/BCDFC3B7-ED95-E011-94F8-0030487CD7E0.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/BE64844F-0E96-E011-8B0E-003048F1C58C.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/C06E873D-E495-E011-8FF1-0019B9F72BAA.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/DE1F0652-0E96-E011-A96C-003048F11C58.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/E0030F46-0896-E011-95AC-003048F117B4.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/E2BD34C9-E995-E011-9B50-00304879EDEA.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/E4C1DE51-1596-E011-8B15-003048673374.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/EAA9643C-E495-E011-9D68-001D09F23A34.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/F61CA81C-0A96-E011-958B-003048D2C01E.root'
, '/store/data/Run2011A/SingleMu/AOD/PromptReco-v4/000/166/841/F6421032-0C96-E011-977B-003048F1C420.root'
]
process.source.lumisToProcess = cms.untracked.VLuminosityBlockRange( '166841:1-166841:845'
, '166841:851-166841:876'
, '166841:882-166841:977'
, '166841:984-166841:984'
, '166841:988-166841:992'
, '166841:998-166841:1015'
)
# use the correct conditions
process.GlobalTag.globaltag = autoCond[ 'com10' ]
# use a sufficient number of events
process.maxEvents.input = 1000
# have a proper output file name
process.out.fileName = 'patTuple_triggerOnly_data.root'
## ---
## Define the path as empty skeleton
## ---
process.p = cms.Path(
)
### ===========
### PAT trigger
### ===========
## --
## Switch on
## --
from PhysicsTools.PatAlgos.tools.trigTools import switchOnTrigger
switchOnTrigger( process, sequence = 'p' ) # overwrite sequence default "patDefaultSequence", since it is not used in any path
## --
## Modify configuration according to your needs
## --
# add L1 algorithms' collection
process.patTrigger.addL1Algos = cms.bool( True ) # default: 'False'
# add L1 objects collection-wise (latest collection)
process.patTrigger.l1ExtraMu = cms.InputTag( 'l1extraParticles', '' )
process.patTrigger.l1ExtraNoIsoEG = cms.InputTag( 'l1extraParticles', 'NonIsolated' )
process.patTrigger.l1ExtraIsoEG = cms.InputTag( 'l1extraParticles', 'Isolated' )
process.patTrigger.l1ExtraCenJet = cms.InputTag( 'l1extraParticles', 'Central' )
process.patTrigger.l1ExtraForJet = cms.InputTag( 'l1extraParticles', 'Forward' )
process.patTrigger.l1ExtraTauJet = cms.InputTag( 'l1extraParticles', 'Tau' )
process.patTrigger.l1ExtraETM = cms.InputTag( 'l1extraParticles', 'MET' )
process.patTrigger.l1ExtraHTM = cms.InputTag( 'l1extraParticles', 'MHT' )
# save references to original L1 objects
process.patTrigger.saveL1Refs = cms.bool( True ) # default: 'False'
# exclude HLT copies of L1 objects
process.patTrigger.exludeCollections = cms.vstring( "hltL1extraParticles*" )
# update event content to save
switchOnTrigger( process, sequence = 'p' ) # called once more to update the event content according to the changed parameters!!!
| 4,423
|
1,056
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.i18n.jelly;
import org.netbeans.jemmy.operators.*;
import org.netbeans.jellytools.*;
import org.netbeans.jellytools.properties.PropertySheetOperator;
/** Class implementing all necessary methods for handling "Internationalize [TestFrame]" TopFrameTypeImpl.
*
* @author eh103527
* @version 1.0
*/
public class InternationalizeOperator extends NbDialogOperator {
/** Creates new InternationalizeTestFrameFrameOperator that can handle it.
*/
public InternationalizeOperator() {
super(Bundle.getStringTrimmed("org.netbeans.modules.i18n.Bundle", "CTL_I18nDialogTitle"));
}
private JLabelOperator _lblBundleName;
private JTextFieldOperator _txtBundleName;
private JButtonOperator _btBrowse;
private JButtonOperator _btNew;
private JLabelOperator _lblComment;
private JTextAreaOperator _txtComment;
private JButtonOperator _btMetalScrollButton;
private JButtonOperator _btMetalScrollButton2;
private JLabelOperator _lblKey;
private JLabelOperator _lblValue;
private JTextAreaOperator _txtValue;
private JButtonOperator _btMetalScrollButton3;
private JButtonOperator _btMetalScrollButton4;
private JComboBoxOperator _cboKey;
private JTextFieldOperator _txtReplaceString;
private JLabelOperator _lblReplaceString;
private JButtonOperator _btFormat;
private JButtonOperator _btArguments;
private JButtonOperator _btReplace;
private JButtonOperator _btSkip;
private JButtonOperator _btInfo;
private JButtonOperator _btClose;
private JButtonOperator _btHelp;
//******************************
// Subcomponents definition part
//******************************
/** Tries to find "Bundle Name:" JLabel in this dialog.
* @return JLabelOperator
*/
public JLabelOperator lblBundleName() {
if (_lblBundleName==null) {
_lblBundleName = new JLabelOperator(this, Bundle.getStringTrimmed("org.netbeans.modules.i18n.Bundle", "LBL_BundleName"));
}
return _lblBundleName;
}
/** Tries to find null JTextField in this dialog.
* @return JTextFieldOperator
*/
public JTextFieldOperator txtBundleName() {
if (_txtBundleName==null) {
_txtBundleName = new JTextFieldOperator(this);
}
return _txtBundleName;
}
/** Tries to find "Browse..." JButton in this dialog.
* @return JButtonOperator
*/
public JButtonOperator btBrowse() {
if (_btBrowse==null) {
_btBrowse = new JButtonOperator(this, Bundle.getStringTrimmed("org.netbeans.modules.i18n.Bundle", "CTL_BrowseButton"));
}
return _btBrowse;
}
/** Tries to find "New..." JButton in this dialog.
* @return JButtonOperator
*/
public JButtonOperator btNew() {
if (_btNew==null) {
_btNew = new JButtonOperator(this, Bundle.getStringTrimmed("org.netbeans.modules.i18n.Bundle", "CTL_NewButton"));
}
return _btNew;
}
/** Tries to find "Comment:" JLabel in this dialog.
* @return JLabelOperator
*/
public JLabelOperator lblComment() {
if (_lblComment==null) {
_lblComment = new JLabelOperator(this, Bundle.getStringTrimmed("org.netbeans.modules.i18n.Bundle", "LBL_Comment"));
}
return _lblComment;
}
/** Tries to find null JTextArea in this dialog.
* @return JTextAreaOperator
*/
public JTextAreaOperator txtComment() {
if (_txtComment==null) {
_txtComment = new JTextAreaOperator(this);
}
return _txtComment;
}
/** Tries to find null MetalScrollButton in this dialog.
* @return JButtonOperator
*/
public JButtonOperator btMetalScrollButton() {
if (_btMetalScrollButton==null) {
_btMetalScrollButton = new JButtonOperator(this, 2);
}
return _btMetalScrollButton;
}
/** Tries to find null MetalScrollButton in this dialog.
* @return JButtonOperator
*/
public JButtonOperator btMetalScrollButton2() {
if (_btMetalScrollButton2==null) {
_btMetalScrollButton2 = new JButtonOperator(this, 3);
}
return _btMetalScrollButton2;
}
/** Tries to find "Key:" JLabel in this dialog.
* @return JLabelOperator
*/
public JLabelOperator lblKey() {
if (_lblKey==null) {
_lblKey = new JLabelOperator(this, Bundle.getStringTrimmed("org.netbeans.modules.i18n.Bundle", "LBL_Key"));
}
return _lblKey;
}
/** Tries to find "Value:" JLabel in this dialog.
* @return JLabelOperator
*/
public JLabelOperator lblValue() {
if (_lblValue==null) {
_lblValue = new JLabelOperator(this, Bundle.getStringTrimmed("org.netbeans.modules.i18n.Bundle", "LBL_Value"));
}
return _lblValue;
}
/** Tries to find null JTextArea in this dialog.
* @return JTextAreaOperator
*/
public JTextAreaOperator txtValue() {
if (_txtValue==null) {
_txtValue = new JTextAreaOperator(this, 1);
}
return _txtValue;
}
/** Tries to find null MetalScrollButton in this dialog.
* @return JButtonOperator
*/
public JButtonOperator btMetalScrollButton3() {
if (_btMetalScrollButton3==null) {
_btMetalScrollButton3 = new JButtonOperator(this, 4);
}
return _btMetalScrollButton3;
}
/** Tries to find null MetalScrollButton in this dialog.
* @return JButtonOperator
*/
public JButtonOperator btMetalScrollButton4() {
if (_btMetalScrollButton4==null) {
_btMetalScrollButton4 = new JButtonOperator(this, 5);
}
return _btMetalScrollButton4;
}
/** Tries to find null JComboBox in this dialog.
* @return JComboBoxOperator
*/
public JComboBoxOperator cboKey() {
if (_cboKey==null) {
_cboKey = new JComboBoxOperator(this);
}
return _cboKey;
}
/** Tries to find null JTextField in this dialog.
* @return JTextFieldOperator
*/
public JTextFieldOperator txtReplaceString() {
if (_txtReplaceString==null) {
_txtReplaceString = new JTextFieldOperator(this, 2);
}
return _txtReplaceString;
}
/** Tries to find "Replace String:" JLabel in this dialog.
* @return JLabelOperator
*/
public JLabelOperator lblReplaceString() {
if (_lblReplaceString==null) {
_lblReplaceString = new JLabelOperator(this, Bundle.getStringTrimmed("org.netbeans.modules.i18n.Bundle", "LBL_ReplaceFormat"));
}
return _lblReplaceString;
}
/** Tries to find "Format..." JButton in this dialog.
* @return JButtonOperator
*/
public JButtonOperator btFormat() {
if (_btFormat==null) {
_btFormat = new JButtonOperator(this, Bundle.getStringTrimmed("org.netbeans.modules.i18n.Bundle", "CTL_Format"));
}
return _btFormat;
}
/** Tries to find "Arguments..." JButton in this dialog.
* @return JButtonOperator
*/
public JButtonOperator btArguments() {
if (_btArguments==null) {
_btArguments = new JButtonOperator(this, Bundle.getStringTrimmed("org.netbeans.modules.i18n.Bundle", "LBL_Arguments"));
}
return _btArguments;
}
/** Tries to find "Replace" JButton in this dialog.
* @return JButtonOperator
*/
public JButtonOperator btReplace() {
if (_btReplace==null) {
_btReplace = new JButtonOperator(this, Bundle.getStringTrimmed("org.netbeans.modules.i18n.Bundle", "CTL_ReplaceButton"));
}
return _btReplace;
}
/** Tries to find "Skip" JButton in this dialog.
* @return JButtonOperator
*/
public JButtonOperator btSkip() {
if (_btSkip==null) {
_btSkip = new JButtonOperator(this, Bundle.getStringTrimmed("org.netbeans.modules.i18n.Bundle", "CTL_ReplaceButton"));
}
return _btSkip;
}
/** Tries to find "Info" JButton in this dialog.
* @return JButtonOperator
*/
public JButtonOperator btInfo() {
if (_btInfo==null) {
_btInfo = new JButtonOperator(this, Bundle.getStringTrimmed("org.netbeans.modules.i18n.Bundle", "CTL_InfoButton"));
}
return _btInfo;
}
/** Tries to find "Close" JButton in this dialog.
* @return JButtonOperator
*/
public JButtonOperator btClose() {
if (_btClose==null) {
_btClose = new JButtonOperator(this, Bundle.getStringTrimmed("org.netbeans.modules.i18n.Bundle", "CTL_CloseButton"));
}
return _btClose;
}
/** Tries to find "Help" JButton in this dialog.
* @return JButtonOperator
*/
public JButtonOperator btHelp() {
if (_btHelp==null) {
_btHelp = new JButtonOperator(this, Bundle.getStringTrimmed("org.netbeans.modules.i18n.Bundle", "CTL_HelpButton"));
}
return _btHelp;
}
//****************************************
// Low-level functionality definition part
//****************************************
/** gets text for txtBundleName
* @return String text
*/
public String getBundleName() {
return txtBundleName().getText();
}
/** sets text for txtBundleName
* @param text String text
*/
public void setBundleName(String text) {
txtBundleName().setText(text);
}
/** types text for txtBundleName
* @param text String text
*/
public void typeBundleName(String text) {
txtBundleName().typeText(text);
}
/** clicks on "Browse..." JButton
*/
public void browse() {
btBrowse().push();
}
/** clicks on "New..." JButton
*/
public void clickNew() {
btNew().push();
}
/** gets text for txtComment
* @return String text
*/
public String getComment() {
return txtComment().getText();
}
/** sets text for txtComment
* @param text String text
*/
public void setComment(String text) {
txtComment().setText(text);
}
/** types text for txtComment
* @param text String text
*/
public void typeComment(String text) {
txtComment().typeText(text);
}
/** clicks on null MetalScrollButton
*/
public void metalScrollButton() {
btMetalScrollButton().push();
}
/** clicks on null MetalScrollButton
*/
public void metalScrollButton2() {
btMetalScrollButton2().push();
}
/** gets text for txtValue
* @return String text
*/
public String getValue() {
return txtValue().getText();
}
/** sets text for txtValue
* @param text String text
*/
public void setValue(String text) {
txtValue().setText(text);
}
/** types text for txtValue
* @param text String text
*/
public void typeValue(String text) {
txtValue().typeText(text);
}
/** clicks on null MetalScrollButton
*/
public void metalScrollButton3() {
btMetalScrollButton3().push();
}
/** clicks on null MetalScrollButton
*/
public void metalScrollButton4() {
btMetalScrollButton4().push();
}
/** returns selected item for cboKey
* @return String item
*/
public String getSelectedKey() {
return cboKey().getSelectedItem().toString();
}
/** selects item for cboKey
* @param item String item
*/
public void selectKey(String item) {
cboKey().selectItem(item);
}
/** types text for cboKey
* @param text String text
*/
public void typeKey(String text) {
cboKey().typeText(text);
}
/** gets text for txtReplaceString
* @return String text
*/
public String getReplaceString() {
return txtReplaceString().getText();
}
/** sets text for txtReplaceString
* @param text String text
*/
public void setReplaceString(String text) {
txtReplaceString().setText(text);
}
/** types text for txtReplaceString
* @param text String text
*/
public void typeReplaceString(String text) {
txtReplaceString().typeText(text);
}
/** clicks on "Format..." JButton
*/
public void format() {
btFormat().push();
}
/** clicks on "Arguments..." JButton
*/
public void arguments() {
btArguments().push();
}
/** clicks on "Replace" JButton
*/
public void replace() {
btReplace().push();
}
/** clicks on "Skip" JButton
*/
public void skip() {
btSkip().push();
}
/** clicks on "Info" JButton
*/
public void info() {
btInfo().push();
}
/** clicks on "Close" JButton
*/
public void close() {
btClose().push();
}
/** clicks on "Help" JButton
*/
public void help() {
btHelp().push();
}
//*****************************************
// High-level functionality definition part
//*****************************************
/** Performs verification of InternationalizeTestFrameFrameOperator by accessing all its components.
*/
public void verify() {
lblBundleName();
txtBundleName();
btBrowse();
btNew();
lblComment();
txtComment();
btMetalScrollButton();
btMetalScrollButton2();
lblKey();
lblValue();
txtValue();
btMetalScrollButton3();
btMetalScrollButton4();
cboKey();
txtReplaceString();
lblReplaceString();
btFormat();
btArguments();
btReplace();
btSkip();
btInfo();
btClose();
btHelp();
}
public void createNewBundle(String name) {
btNew().pushNoBlock();
NewBundleOperator nbo=new NewBundleOperator();
}
/** Performs simple test of InternationalizeTestFrameFrameOperator
* @param args the command line arguments
*/
public static void main(String args[]) {
new InternationalizeOperator().verify();
System.out.println("InternationalizeOperator verification finished.");
}
}
| 6,457
|
879
|
package org.zstack.header.identity;
import org.zstack.header.search.APISearchReply;
public class APISearchUserReply extends APISearchReply {
public static APISearchUserReply __example__() {
APISearchUserReply reply = new APISearchUserReply();
return reply;
}
}
| 104
|
368
|
/*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* 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 io.charlescd.villager.infrastructure.integration.registry.authentication;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSCredentialsProviderChain;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.EC2ContainerCredentialsProviderWrapper;
import com.amazonaws.auth.EnvironmentVariableCredentialsProvider;
import com.amazonaws.auth.SystemPropertiesCredentialsProvider;
import com.amazonaws.auth.WebIdentityTokenCredentialsProvider;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.ecr.AmazonECR;
import com.amazonaws.services.ecr.AmazonECRClientBuilder;
import com.amazonaws.services.ecr.model.GetAuthorizationTokenRequest;
import com.amazonaws.services.ecr.model.GetAuthorizationTokenResult;
import java.util.LinkedList;
import java.util.List;
public class AWSCustomProviderChainAuthenticator extends AbstractBasicAuthenticator {
private String region;
private List<AWSCredentialsProvider> providerChain = new LinkedList<>();
public AWSCustomProviderChainAuthenticator(String region) {
this.region = region;
providerChain.add(new EnvironmentVariableCredentialsProvider());
providerChain.add(new SystemPropertiesCredentialsProvider());
providerChain.add(new WebIdentityTokenCredentialsProvider());
providerChain.add(new ProfileCredentialsProvider());
providerChain.add(new EC2ContainerCredentialsProviderWrapper());
}
public void addProviderAsPrimary(AWSCredentialsProvider provider) {
providerChain.add(0, provider);
}
private AWSCredentials getCredentials() {
return new AWSCredentialsProviderChain(providerChain).getCredentials();
}
public GetAuthorizationTokenResult getAuthorizationToken(AmazonECR amazonECR) {
return amazonECR.getAuthorizationToken(new GetAuthorizationTokenRequest());
}
@Override
public String loadBasicAuthorization() {
AWSCredentials awsCredentials = getCredentials();
AmazonECRClientBuilder amazonECRBuilder = AmazonECRClientBuilder.standard()
.withRegion(this.region)
.withCredentials(new AWSStaticCredentialsProvider(awsCredentials));
AmazonECR amazonECR = amazonECRBuilder.build();
var authorizationToken = getAuthorizationToken(amazonECR);
return String.format("Basic %s", authorizationToken.getAuthorizationData().get(0).getAuthorizationToken());
}
}
| 984
|
2,406
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <ngraph/opsets/opset6.hpp>
#include <node_context.hpp>
namespace ngraph {
namespace frontend {
namespace pdpd {
namespace op {
NamedOutputs softmax(const NodeContext& node) {
auto data = node.get_ng_input("X");
auto axis = node.get_attribute<int32_t>("axis");
if (axis < 0) {
PDPD_OP_VALIDATION_CHECK(node, data.get_partial_shape().rank().is_static(), "Softmax rank must be static");
auto data_rank = data.get_partial_shape().rank().get_length();
axis = data_rank + axis;
}
return node.default_single_output_mapping({std::make_shared<ngraph::opset6::Softmax>(data, axis)}, {"Out"});
}
} // namespace op
} // namespace pdpd
} // namespace frontend
} // namespace ngraph
| 308
|
3,151
|
package com.rarchives.ripme.ripper.rippers;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.rarchives.ripme.ripper.AbstractHTMLRipper;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.rarchives.ripme.ripper.DownloadThreadPool;
import com.rarchives.ripme.utils.Http;
public class NfsfwRipper extends AbstractHTMLRipper {
private static final String DOMAIN = "nfsfw.com",
HOST = "nfsfw";
private int index = 0;
private String currentDir = "";
private List<String> subalbumURLs = new ArrayList<>();
private Pattern subalbumURLPattern = Pattern.compile(
"https?://[wm.]*nfsfw.com/gallery/v/[^/]+/(.+)$"
);
// cached first page
private Document fstPage;
// threads pool for downloading images from image pages
private DownloadThreadPool nfsfwThreadPool;
public NfsfwRipper(URL url) throws IOException {
super(url);
nfsfwThreadPool = new DownloadThreadPool("NFSFW");
}
@Override
protected String getDomain() {
return DOMAIN;
}
@Override
public String getHost() {
return HOST;
}
@Override
protected Document getFirstPage() throws IOException {
// cache the first page
this.fstPage = Http.url(url).get();
return fstPage;
}
@Override
public Document getNextPage(Document page) throws IOException {
String nextURL = null;
Elements a = page.select("a.next");
if (!a.isEmpty()){
// Get next page of current album
nextURL = "http://nfsfw.com" + a.first().attr("href");
} else if (!subalbumURLs.isEmpty()){
// Get next sub-album
nextURL = subalbumURLs.remove(0);
LOGGER.info("Detected subalbum URL at:" + nextURL);
Matcher m = subalbumURLPattern.matcher(nextURL);
if (m.matches()) {
// Set the new save directory and save images with a new index
this.currentDir = m.group(1);
this.index = 0;
} else {
LOGGER.error("Invalid sub-album URL: " + nextURL);
nextURL = null;
}
}
// Wait
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
LOGGER.error("Interrupted while waiting to load next page", e);
}
if (nextURL == null){
throw new IOException("No more pages");
} else {
return Http.url(nextURL).get();
}
}
@Override
protected List<String> getURLsFromPage(Document page) {
List<String> imagePageURLs = getImagePageURLs(page);
// Check if any sub-albums are present on this page
List<String> subalbumURLs = getSubalbumURLs(page);
this.subalbumURLs.addAll(subalbumURLs);
return imagePageURLs;
}
@Override
protected void downloadURL(URL url, int index) {
// if we are now downloading a sub-album, all images in it
// should be indexed starting from 0
if (!this.currentDir.equals("")){
index = ++this.index;
}
NfsfwImageThread t = new NfsfwImageThread(url, currentDir, index);
nfsfwThreadPool.addThread(t);
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
// always start on the first page of an album
// (strip the options after the '?')
String u = url.toExternalForm();
if (u.contains("?")) {
u = u.substring(0, u.indexOf("?"));
return new URL(u);
} else {
return url;
}
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p; Matcher m;
p = Pattern.compile("https?://[wm.]*nfsfw.com/gallery/v/(.*)$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
String group = m.group(1);
if (group.endsWith("/")) {
group = group.substring(0, group.length() - 1);
}
return group.replaceAll("/", "__");
}
throw new MalformedURLException(
"Expected nfsfw.com gallery format: "
+ "nfsfw.com/v/albumname"
+ " Got: " + url);
}
@Override
public DownloadThreadPool getThreadPool() {
return nfsfwThreadPool;
}
@Override
public boolean hasQueueSupport() {
return true;
}
@Override
public boolean pageContainsAlbums(URL url) {
List<String> imageURLs = getImagePageURLs(fstPage);
List<String> subalbumURLs = getSubalbumURLs(fstPage);
return imageURLs.isEmpty() && !subalbumURLs.isEmpty();
}
@Override
public List<String> getAlbumsToQueue(Document doc) {
return getSubalbumURLs(doc);
}
// helper methods
private List<String> getImagePageURLs(Document page){
// get image pages
// NOTE: It might be possible to get the (non-thumbnail) image URL
// without going to its page first as there seems to be a pattern
// between the thumb and actual image URLs, but that is outside the
// scope of the current issue being solved.
List<String> imagePageURLs = new ArrayList<>();
for (Element thumb : page.select("td.giItemCell > div > a")) {
String imagePage = "http://nfsfw.com" + thumb.attr("href");
imagePageURLs.add(imagePage);
}
return imagePageURLs;
}
private List<String> getSubalbumURLs(Document page){
// Check if sub-albums are present on this page
List<String> subalbumURLs = new ArrayList<>();
for (Element suba : page.select("td.IMG > a")) {
String subURL = "http://nfsfw.com" + suba.attr("href");
subalbumURLs.add(subURL);
}
return subalbumURLs;
}
/**
* Helper class to find and download images found on "image" pages
*/
private class NfsfwImageThread extends Thread {
private URL url;
private String subdir;
private int index;
NfsfwImageThread(URL url, String subdir, int index) {
super();
this.url = url;
this.subdir = subdir;
this.index = index;
}
@Override
public void run() {
try {
Document doc = Http.url(this.url)
.referrer(this.url)
.get();
Elements images = doc.select(".gbBlock img");
if (images.isEmpty()) {
LOGGER.error("Failed to find image at " + this.url);
return;
}
String file = images.first().attr("src");
if (file.startsWith("/")) {
file = "http://nfsfw.com" + file;
}
addURLToDownload(new URL(file), getPrefix(index), this.subdir);
} catch (IOException e) {
LOGGER.error("[!] Exception while loading/parsing " + this.url, e);
}
}
}
}
| 3,381
|
3,631
|
<filename>kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/SimpleType.java
/*
* Copyright 2019 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.dmn.feel.lang;
/**
* A simple type definition interface, i.e., a type that does not contain fields
*/
public interface SimpleType extends Type {
public static final String LIST = "list";
public static final String CONTEXT = "context";
public static final String FUNCTION = "function";
public static final String BOOLEAN = "boolean";
public static final String YEARS_AND_MONTHS_DURATION = "years and months duration";
public static final String DAYS_AND_TIME_DURATION = "days and time duration";
public static final String DATE_AND_TIME = "date and time";
public static final String TIME = "time";
public static final String DATE = "date";
public static final String STRING = "string";
public static final String NUMBER = "number";
public static final String ANY = "Any";
}
| 447
|
343
|
/* $Id$ $Revision$ */
/* vim:set shiftwidth=4 ts=8: */
/*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************/
#include "vis.h"
#ifdef DMALLOC
#include "dmalloc.h"
#endif
static COORD unseen = (double) INT_MAX;
/* shortestPath:
* Given a VxV weighted adjacency matrix, compute the shortest
* path vector from root to target. The returned vector (dad) encodes the
* shorted path from target to the root. That path is given by
* i, dad[i], dad[dad[i]], ..., root
* We have dad[root] = -1.
*
* Based on Dijkstra's algorithm (Sedgewick, 2nd. ed., p. 466).
*
* This implementation only uses the lower left triangle of the
* adjacency matrix, i.e., the values a[i][j] where i >= j.
*/
int *shortestPath(int root, int target, int V, array2 wadj)
{
int *dad;
COORD *vl;
COORD *val;
int min;
int k, t;
/* allocate arrays */
dad = (int *) malloc(V * sizeof(int));
vl = (COORD *) malloc((V + 1) * sizeof(COORD)); /* One extra for sentinel */
val = vl + 1;
/* initialize arrays */
for (k = 0; k < V; k++) {
dad[k] = -1;
val[k] = -unseen;
}
val[-1] = -(unseen + (COORD) 1); /* Set sentinel */
min = root;
/* use (min >= 0) to fill entire tree */
while (min != target) {
k = min;
val[k] *= -1;
min = -1;
if (val[k] == unseen)
val[k] = 0;
for (t = 0; t < V; t++) {
if (val[t] < 0) {
COORD newpri;
COORD wkt;
/* Use lower triangle */
if (k >= t)
wkt = wadj[k][t];
else
wkt = wadj[t][k];
newpri = -(val[k] + wkt);
if ((wkt != 0) && (val[t] < newpri)) {
val[t] = newpri;
dad[t] = k;
}
if (val[t] > val[min])
min = t;
}
}
}
free(vl);
return dad;
}
/* makePath:
* Given two points p and q in two polygons pp and qp of a vconfig_t conf,
* and the visibility vectors of p and q relative to conf,
* compute the shortest path from p to q.
* If dad is the returned array and V is the number of polygon vertices in
* conf, then the path is V(==q), dad[V], dad[dad[V]], ..., V+1(==p).
* NB: This is the only path that is guaranteed to be valid.
* We have dad[V+1] = -1.
*
*/
int *makePath(Ppoint_t p, int pp, COORD * pvis,
Ppoint_t q, int qp, COORD * qvis, vconfig_t * conf)
{
int V = conf->N;
if (directVis(p, pp, q, qp, conf)) {
int *dad = (int *) malloc(sizeof(int) * (V + 2));
dad[V] = V + 1;
dad[V + 1] = -1;
return dad;
} else {
array2 wadj = conf->vis;
wadj[V] = qvis;
wadj[V + 1] = pvis;
return (shortestPath(V + 1, V, V + 2, wadj));
}
}
| 1,195
|
2,209
|
#!/usr/bin/env python
# Copyright 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
from __future__ import print_function
"""
process.py - Runtime library for launching processes and manipulating file
descriptors.
"""
import errno
import fcntl
import os
import sys
from osh.meta import runtime
from core import util
from osh.meta import Id
redirect_e = runtime.redirect_e
process_state_e = runtime.process_state_e
e_die = util.e_die
log = util.log
class _FdFrame(object):
def __init__(self):
self.saved = []
self.need_close = []
self.need_wait = []
def Forget(self):
"""For exec 1>&2."""
del self.saved[:] # like list.clear() in Python 3.3
del self.need_close[:]
del self.need_wait[:]
def __repr__(self):
return '<_FdFrame %s %s>' % (self.saved, self.need_close)
class FdState(object):
"""This is for the current process, as opposed to child processes.
For example, you can do 'myfunc > out.txt' without forking.
"""
def __init__(self, next_fd=10):
self.next_fd = next_fd # where to start saving descriptors
self.cur_frame = _FdFrame() # for the top level
self.stack = [self.cur_frame]
def Open(self, path):
"""Opens a path for read, but moves it out of the reserved 3-9 fd range.
Returns:
A Python file object. The caller is responsible for Close().
Raises:
OSError if the path can't be found.
"""
fd = os.open(path, os.O_RDONLY, 0666)
new_fd = self.next_fd
os.dup2(fd, new_fd)
self.next_fd += 1
os.close(fd)
return os.fdopen(new_fd)
def _PushDup(self, fd1, fd2):
"""
Save fd2 and dup fd1 onto fd2.
"""
#log('---- _PushDup %s %s', fd1, fd2)
need_restore = True
try:
#log('DUPFD %s %s', fd2, self.next_fd)
fcntl.fcntl(fd2, fcntl.F_DUPFD, self.next_fd)
except IOError as e:
# Example program that causes this error: exec 4>&1. Descriptor 4 isn't
# open.
# This seems to be ignored in dash too in savefd()?
if e.errno == errno.EBADF:
#log('ERROR %s', e)
need_restore = False
else:
raise
else:
os.close(fd2)
fcntl.fcntl(self.next_fd, fcntl.F_SETFD, fcntl.FD_CLOEXEC)
#log('==== dup %s %s\n' % (fd1, fd2))
try:
os.dup2(fd1, fd2)
except OSError as e:
# bash/dash give this error too, e.g. for 'echo hi 1>&3'
util.error('%d: %s', fd1, os.strerror(e.errno))
# Restore and return error
os.dup2(self.next_fd, fd2)
os.close(self.next_fd)
# Undo it
return False
if need_restore:
self.cur_frame.saved.append((self.next_fd, fd2))
self.next_fd += 1
return True
def _PushClose(self, fd):
self.cur_frame.need_close.append(fd)
def _PushWait(self, proc, waiter):
self.cur_frame.need_wait.append((proc, waiter))
def _ApplyRedirect(self, r, waiter):
ok = True
if r.tag == redirect_e.PathRedirect:
if r.op_id == Id.Redir_Great: # >
# NOTE: This is different than >| because it respects noclobber, but
# that option is almost never used. See test/wild.sh.
mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
elif r.op_id == Id.Redir_Clobber: # >|
mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
elif r.op_id == Id.Redir_DGreat: # >>
mode = os.O_CREAT | os.O_WRONLY | os.O_APPEND
elif r.op_id == Id.Redir_Less: # <
mode = os.O_RDONLY
else:
raise NotImplementedError(r.op_id)
# NOTE: 0666 is affected by umask, all shells use it.
try:
target_fd = os.open(r.filename, mode, 0666)
except OSError as e:
util.error("Can't open %r: %s", r.filename, os.strerror(e.errno))
return False
if not self._PushDup(target_fd, r.fd):
ok = False
os.close(target_fd) # We already made a copy of it.
# I don't think we need to close(0) because it will be restored from its
# saved position (10), which closes it.
#self._PushClose(r.fd)
elif r.tag == redirect_e.DescRedirect: # e.g. echo hi 1>&2
if r.op_id == Id.Redir_GreatAnd: # 1>&2
if not self._PushDup(r.target_fd, r.fd):
ok = False
elif r.op_id == Id.Redir_LessAnd: # 0<&5
# The only difference between >& and <& is the default file
# descriptor argument.
if not self._PushDup(r.target_fd, r.fd):
ok = False
else:
raise NotImplementedError
elif r.tag == redirect_e.HereRedirect:
# NOTE: Do these descriptors have to be moved out of the range 0-9?
read_fd, write_fd = os.pipe()
if not self._PushDup(read_fd, r.fd): # stdin is now the pipe
ok = False
# We can't close like we do in the filename case above? The writer can
# get a "broken pipe".
self._PushClose(read_fd)
thunk = _HereDocWriterThunk(write_fd, r.body)
# TODO: Use PIPE_SIZE to save a process in the case of small here docs,
# which are the common case. (dash does this.)
start_process = True
#start_process = False
if start_process:
here_proc = Process(thunk)
# NOTE: we could close the read pipe here, but it doesn't really
# matter because we control the code.
# here_proc.StateChange()
pid = here_proc.Start()
# no-op callback
waiter.Register(pid, here_proc.WhenDone)
#log('Started %s as %d', here_proc, pid)
self._PushWait(here_proc, waiter)
# Now that we've started the child, close it in the parent.
os.close(write_fd)
else:
os.write(write_fd, r.body)
os.close(write_fd)
return ok
def Push(self, redirects, waiter):
#log('> fd_state.Push %s', redirects)
new_frame = _FdFrame()
self.stack.append(new_frame)
self.cur_frame = new_frame
for r in redirects:
#log('apply %s', r)
if not self._ApplyRedirect(r, waiter):
return False # for bad descriptor
#log('done applying %d redirects', len(redirects))
return True
def MakePermanent(self):
self.cur_frame.Forget()
def Pop(self):
frame = self.stack.pop()
#log('< Pop %s', frame)
for saved, orig in reversed(frame.saved):
try:
os.dup2(saved, orig)
except OSError as e:
log('dup2(%d, %d) error: %s', saved, orig, e)
#log('fd state:')
#os.system('ls -l /proc/%s/fd' % os.getpid())
raise
os.close(saved)
#log('dup2 %s %s', saved, orig)
self.next_fd -= 1 # Count down
for fd in frame.need_close:
#log('Close %d', fd)
try:
os.close(fd)
except OSError as e:
log('Error closing descriptor %d: %s', fd, e)
raise
# Wait for here doc processes to finish.
for proc, waiter in frame.need_wait:
unused_status = proc.WaitUntilDone(waiter)
class ChildStateChange(object):
def Apply(self):
raise NotImplementedError
class StdinFromPipe(ChildStateChange):
def __init__(self, pipe_read_fd, w):
self.r = pipe_read_fd
self.w = w
def __repr__(self):
return '<StdinFromPipe %d %d>' % (self.r, self.w)
def Apply(self):
os.dup2(self.r, 0)
os.close(self.r) # close after dup
os.close(self.w) # we're reading from the pipe, not writing
#log('child CLOSE w %d pid=%d', self.w, os.getpid())
class StdoutToPipe(ChildStateChange):
def __init__(self, r, pipe_write_fd):
self.r = r
self.w = pipe_write_fd
def __repr__(self):
return '<StdoutToPipe %d %d>' % (self.r, self.w)
def Apply(self):
os.dup2(self.w, 1)
os.close(self.w) # close after dup
os.close(self.r) # we're writing to the pipe, not reading
#log('child CLOSE r %d pid=%d', self.r, os.getpid())
class Thunk(object):
"""Abstract base class for things runnable in another process."""
def Run(self):
"""Returns a status code."""
raise NotImplementedError
def ExecExternalProgram(argv, environ):
"""
"""
# TODO: If there is an error, like the file isn't executable, then we should
# exit, and the parent will reap it. Should it capture stderr?
try:
os.execvpe(argv[0], argv, environ)
except OSError as e:
log('Unexpected error in execvpe(%r, %r, ...): %s', argv[0], argv, e)
# Command not found means 127. TODO: Are there other cases?
sys.exit(127)
# no return
class ExternalThunk(object):
"""An external executable."""
def __init__(self, argv, environ):
self.argv = argv
self.environ = environ
def Run(self):
"""
An ExternalThunk is run in parent for the exec builtin.
"""
ExecExternalProgram(self.argv, self.environ)
class SubProgramThunk(object):
"""A subprogram that can be executed in another process."""
def __init__(self, ex, node, disable_errexit=False):
self.ex = ex
self.node = node
self.disable_errexit = disable_errexit # for bash errexit compatibility
def Run(self):
# NOTE: may NOT return due to exec().
if self.disable_errexit:
self.ex.exec_opts.errexit.Disable()
status = self.ex.Execute(self.node, fork_external=False)
sys.exit(status) # Must exit!
class _HereDocWriterThunk(Thunk):
"""Write a here doc to one end of a pipe.
May be be executed in either a child process or the main shell process.
"""
def __init__(self, w, body_str):
self.w = w
self.body_str = body_str
def Run(self):
"""
do_exit: For small pipelines
"""
#log('Writing %r', self.body_str)
os.write(self.w, self.body_str)
#log('Wrote %r', self.body_str)
os.close(self.w)
#log('Closed %d', self.w)
sys.exit(0) # Could this fail?
class Job(object):
def __init__(self):
self.state = process_state_e.Init
def State(self):
return self.state
def WaitUntilDone(self, waiter):
"""
Returns:
An int for a process
A list of ints for a pipeline
"""
raise NotImplementedError
class Process(Job):
"""A process to run.
TODO: Should we make it clear that this is a FOREGROUND process? A
background process is wrapped in a "job". It is unevaluated.
It provides an API to manipulate file descriptor state in parent and child.
"""
def __init__(self, thunk, job_state=None):
"""
Args:
thunk: Thunk instance
job_state: notify upon completion
"""
Job.__init__(self)
assert not isinstance(thunk, list), thunk
self.thunk = thunk
self.job_state = job_state
# For pipelines
self.state_changes = []
self.close_r = -1
self.close_w = -1
self.pid = -1
self.status = -1
def __repr__(self):
return '<Process %s>' % self.thunk
def AddStateChange(self, s):
self.state_changes.append(s)
def AddPipeToClose(self, r, w):
self.close_r = r
self.close_w = w
def ClosePipe(self):
if self.close_r != -1:
os.close(self.close_r)
os.close(self.close_w)
def Start(self):
"""Start this process with fork(), haandling redirects."""
pid = os.fork()
if pid < 0:
# When does this happen?
raise RuntimeError('Fatal error in os.fork()')
elif pid == 0: # child
for st in self.state_changes:
st.Apply()
self.thunk.Run()
# Never returns
#log('STARTED process %s, pid = %d', self, pid)
# Invariant, after the process is started, it stores its PID.
self.pid = pid
return pid
def WaitUntilDone(self, waiter):
while True:
#log('WAITING')
if not waiter.Wait():
break
if self.state == process_state_e.Done:
break
return self.status
def WhenDone(self, pid, status):
#log('WhenDone %d %d', pid, status)
assert pid == self.pid, 'Expected %d, got %d' % (self.pid, pid)
self.status = status
self.state = process_state_e.Done
if self.job_state:
self.job_state.WhenDone(pid)
def Run(self, waiter):
"""Run this process synchronously."""
self.Start()
# NOTE: No race condition between start and Register, because the shell is
# single-threaded and nothing else can call Wait() before we do!
waiter.Register(self.pid, self.WhenDone)
# TODO: Can collect garbage here, and record timing stats. The process
# will likely take longer than the GC? Although I guess some processes can
# only take 1ms, whereas garbage collection can take longer.
# Maybe you can have a separate GC thread, and only start it after 100ms,
# and then cancel when done?
return self.WaitUntilDone(waiter)
class Pipeline(Job):
"""A pipeline of processes to run.
Cases we handle:
foo | bar
$(foo | bar)
foo | bar | read v
"""
def __init__(self, job_state=None):
Job.__init__(self)
self.job_state = job_state
self.procs = []
self.pids = [] # pids in order
self.pipe_status = [] # status in order
self.status = -1 # for 'wait' jobs
def __repr__(self):
return '<Pipeline %s>' % ' '.join(repr(p) for p in self.procs)
def Add(self, p):
"""Append a process to the pipeline.
NOTE: Are its descriptors already set up?
"""
if len(self.procs) == 0:
self.procs.append(p)
return
r, w = os.pipe()
prev = self.procs[-1]
#prev.AddRedirect(WritePipeRedirect(w))
#p.AddRedirect(ReadPipeRedirect(r))
prev.AddStateChange(StdoutToPipe(r, w))
p.AddStateChange(StdinFromPipe(r, w))
p.AddPipeToClose(r, w)
self.procs.append(p)
def Start(self, waiter):
for i, proc in enumerate(self.procs):
pid = proc.Start()
self.pids.append(pid)
self.pipe_status.append(-1) # uninitialized
waiter.Register(pid, self.WhenDone)
# NOTE: This has to be done after every fork() call. Otherwise processes
# will have descriptors from non-adjacent pipes.
proc.ClosePipe()
return self.pids[-1] # the last PID is the job ID
def WaitUntilDone(self, waiter):
while True:
#log('WAIT pipeline')
if not waiter.Wait():
break
if self.state == process_state_e.Done:
#log('Pipeline DONE')
break
return self.pipe_status
def Run(self, waiter):
"""Run this pipeline synchronously."""
self.Start(waiter)
return self.WaitUntilDone(waiter)
def WhenDone(self, pid, status):
#log('Pipeline WhenDone %d %d', pid, status)
i = self.pids.index(pid)
assert i != -1, 'Unexpected PID %d' % pid
self.pipe_status[i] = status
if all(status != -1 for status in self.pipe_status):
self.status = self.pipe_status[-1] # last one
self.state = process_state_e.Done
if self.job_state:
self.job_state.WhenDone(self.pipe_status[-1])
class JobState(object):
"""Global list of jobs, used by a few builtins."""
def __init__(self):
# pid -> Job instance
# A pipeline that is backgrounded is always run in a SubProgramThunk? So
# you can wait for it once?
self.jobs = {}
def Register(self, pid, job):
""" Used by 'sleep 1 &' """
self.jobs[pid] = job
def List(self):
"""Used by the 'jobs' builtin."""
# NOTE: A job is a background process.
#
# echo hi | wc -l -- this starts two processes. Wait for TWO
# echo hi | wc -l & -- this starts a process which starts two processes
# Wait for ONE.
#self.callbacks[pid]
for pid, job in self.jobs.iteritems():
print(pid, job.State(), job)
def IsDone(self, jid):
"""Test if a specific job is done."""
if jid not in self.jobs:
return False, False
job = self.jobs[jid]
return True, job.State() == process_state_e.Done
def AllDone(self):
"""Test if all jobs are done. Used by 'wait' builtin."""
for job in self.jobs.itervalues():
if job.State() != process_state_e.Done:
return False
return True
def WhenDone(self, pid):
"""Process and Pipeline can call this."""
log('JobState WhenDone %d', pid)
# TODO: Update the list
class Waiter(object):
"""A capability to wait for processes.
This must be a singleton (and is because Executor is a singleton).
Invariants:
- Every child process is registered once
- Every child process is waited for
Canonical example of why we need a GLBOAL waiter:
{ sleep 3; echo 'done 3'; } &
{ sleep 4; echo 'done 4'; } &
# ... do arbitrary stuff ...
{ sleep 1; exit 1; } | { sleep 2; exit 2; }
Now when you do wait() after starting the pipeline, you might get a pipeline
process OR a background process! So you have to distinguish between them.
NOTE: strace reveals that all shells call wait4(-1), which waits for ANY
process. os.wait() ends up calling that too. This is the only way to
support the processes we need.
"""
def __init__(self):
self.callbacks = {} # pid -> callback
self.last_status = 127 # wait -n error code
def Register(self, pid, callback):
self.callbacks[pid] = callback
def Wait(self):
# This is a list of async jobs
try:
pid, status = os.wait()
except OSError as e:
if e.errno == errno.ECHILD:
#log('WAIT ECHILD')
return False # nothing to wait for caller should stop
else:
# What else can go wrong?
raise
#log('WAIT got %s %s', pid, status)
# TODO: change status in more cases.
if os.WIFSIGNALED(status):
pass
elif os.WIFEXITED(status):
status = os.WEXITSTATUS(status)
#log('exit status: %s', status)
# This could happen via coding error. But this may legitimately happen
# if a grandchild outlives the child (its parent). Then it is reparented
# under this process, so we might receive notification of its exit, even
# though we didn't start it. We can't have any knowledge of such
# processes, so print a warning.
if pid not in self.callbacks:
util.warn("PID %d stopped, but osh didn't start it", pid)
return True # caller should keep waiting
callback = self.callbacks.pop(pid)
callback(pid, status)
self.last_status = status # for wait -n
return True # caller should keep waiting
| 7,457
|
1,212
|
// raw filename "\".txt:
// Content-Disposition: form-data; name="file"; filename="\"\\".txt"
static int parse_content_disposition(strarg_t const x, str_t **const name, str_t **const filename) {
sscanf(x, "");
}
static size_t scan_quoted(char const *const v) {
size_t i = 0;
if('"' != v[i++]) return 0;
for(;; i++) {
if('\0' == v[i]) break;
if('"' == v[i]) break;
if('\\' == v[i] && '"' == v[i+1]) i++;
}
return i;
}
static char *copy_quoted(char const *const v, size_t const vlen) {
char *const r = malloc(vlen);
if(!r) return NULL;
size_t i;
if('"' == v[i]) i++;
for(;;) {
if('\0' == v[i]) break;
if(
}
}
static size_t quoted(char const *const src, char *const dst, size_t const max) {
size_t s = 0;
size_t d = 0;
if('"' != src[s++]) return 0;
for(;;) {
if('\0' == src[s]) break;
if('"' == src[s]) break;
if('\\' != src[s]) { dst[d++] = *s++; continue; }
if('"' == src[s+1]) { dst[d++] = '"'; continue; }
dst[d++] = '\\';
}
dst[d++] = '\0';
return s;
}
void MIMEOptionsParse(char const *const opts, char *values[], char const *const fields[], size_t const count) {
for(size_t i = 0; i < count; i++) assert(!values[i]);
size_t x = 0;
for(;;) {
if(';' != opts[x++]) break;
while(isspace(opts[x])) x++;
char const *const f = opts+x;
while('=' != opts[x] && ';' != opts[x] && '\0' != opts[x]) x++;
size_t const flen = opts+x - f;
if('=' == opts[x]) x++;
char const *v;
size_t vlen;
if('"' == opts[x]) {
size_t y = 0;
for(;;) {
}
} else {
v = opts+x;
while(';' != opts[x] && '\0' != opts[x]) x++;
vlen = opts+x - v;
}
for(size_t i = 0; i < count; i++) {
if(!substr(fields[i], f, flen)) continue;
if(values[i]) break;
if(vlen) values[i] = strndup(v, vlen);
else values[i] = strdup("true");
break;
}
}
}
void MIMEOptionsCleanup(char **const values, size_t const count) {
for(size_t i = 0; i < count; ++i) {
free(values[i]); values[i] = NULL;
}
}
| 954
|
1,025
|
<gh_stars>1000+
package com.baidu.unbiz.fluentvalidator.demo.service.impl;
import java.util.List;
import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.springframework.stereotype.Service;
import com.baidu.unbiz.fluentvalidator.annotation.FluentValid;
import com.baidu.unbiz.fluentvalidator.demo.dto.Car;
import com.baidu.unbiz.fluentvalidator.demo.dto.Garage;
import com.baidu.unbiz.fluentvalidator.demo.rpc.ManufacturerService;
import com.baidu.unbiz.fluentvalidator.demo.service.GarageService2;
import com.baidu.unbiz.fluentvalidator.demo.validator.NotEmptyValidator;
/**
* 使用拦截器做验证
*
* @author zhangxu
*/
@Service
public class GarageServiceImpl2 implements GarageService2 {
@Override
public List<Car> addCars(@FluentValid(NotEmptyValidator.class) List<Car> cars) {
System.out.println(cars);
return cars;
}
@Override
public List<Car> addCarsThrowException(@FluentValid List<Car> cars) {
System.out.println(cars);
return cars;
}
@Override
public Car addCar(@FluentValid Car car) {
System.out.println(car);
return car;
}
@Override
public Garage buildGarage(@FluentValid Garage garage) {
System.out.println(garage);
return garage;
}
}
| 549
|
2,498
|
# Copyright 2020 The ChubaoFS Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
# -*- coding: utf-8 -*-
import env
import requests
from base import S3TestCase, get_env_s3_client, random_string, random_bytes, compute_md5
PUT_ORIGIN = "www.*.com"
OTHER_ORIGIN = "*.com"
ALLOWED_HEADERS = ["*"]
ALLOWED_METHODS = ['PUT', 'POST', 'GET']
ALLOWED_ORIGINS = [PUT_ORIGIN]
EXPOSE_HEADERS = ['*']
MAX_AGE_SECONDS = 123
CORS_CONFIG = {
'CORSRules': [
{
'AllowedHeaders': ALLOWED_HEADERS,
'AllowedMethods': ALLOWED_METHODS,
'AllowedOrigins': ALLOWED_ORIGINS,
'ExposeHeaders': EXPOSE_HEADERS,
'MaxAgeSeconds': MAX_AGE_SECONDS
},
]
}
BUCKET_URL = '{endpoint}/{bucket_name}'.format(endpoint=env.ENDPOINT, bucket_name=env.BUCKET)
class CorsTest(S3TestCase):
s3 = None
def __init__(self, case):
super(CorsTest, self).__init__(case)
self.s3 = get_env_s3_client()
def test_cors_set(self):
# Get bucket CORS configuration
self.assert_get_bucket_cors_result(
result=self.s3.get_bucket_cors(Bucket=env.BUCKET))
# Put bucket CORS configuration
self.assert_result_status_code(
result=self.s3.put_bucket_cors(Bucket=env.BUCKET, CORSConfiguration=CORS_CONFIG))
# Get bucket CORS configuration
self.assert_get_bucket_cors_result(
result=self.s3.get_bucket_cors(Bucket=env.BUCKET), cors_config=CORS_CONFIG)
# Delete bucket CORS configuration
self.assert_result_status_code(
result=self.s3.delete_bucket_cors(Bucket=env.BUCKET), status_code=204)
# Get bucket CORS configuration
self.assert_get_bucket_cors_result(
result=self.s3.get_bucket_cors(Bucket=env.BUCKET))
def test_cors_request(self):
# Put bucket cors
self.assert_result_status_code(
result=self.s3.put_bucket_cors(Bucket=env.BUCKET, CORSConfiguration=CORS_CONFIG))
# Send allowed cors request
self.assert_cors_request_result(
result=requests.get(url=BUCKET_URL, headers={'Origin': PUT_ORIGIN, 'Access-Control-Request-Method': 'GET'}),
response_code=403,
response_origin=PUT_ORIGIN,
response_method='GET')
# Send not-allowed cors request
self.assert_cors_request_result(
result=requests.get(url=BUCKET_URL, headers={'Origin': OTHER_ORIGIN, 'Access-Control-Request-Method': 'GET'}),
response_code=403,
response_origin=None,
response_method=None)
# Send no cors request
self.assert_cors_request_result(
result=requests.get(url=BUCKET_URL),
response_code=403,
response_origin=None,
response_method=None)
# Delete bucket cors
self.assert_result_status_code(
result=self.s3.delete_bucket_cors(Bucket=env.BUCKET), status_code=204)
# Send cors request
self.assert_cors_request_result(
result=requests.get(url=BUCKET_URL, headers={'Origin': PUT_ORIGIN, 'Access-Control-Request-Method': 'GET'}),
response_code=403,
response_origin=None,
response_method=None)
def test_cors_options(self):
# Put object
key = 'test-options-object'
size = 1024 * 256
body = random_bytes(size)
expect_md5 = compute_md5(body)
self.assert_put_object_result(
result=self.s3.put_object(Bucket=env.BUCKET, Key=key, Body=body),
etag=expect_md5)
# Put bucket cors
self.assert_result_status_code(
result=self.s3.put_bucket_cors(Bucket=env.BUCKET, CORSConfiguration=CORS_CONFIG))
options_url = '{bucket_url}/{key}'.format(bucket_url=BUCKET_URL, key=key)
# Send options requests
self.assert_cors_request_result(
result=requests.options(url=options_url,
headers={'Origin': PUT_ORIGIN, 'Access-Control-Request-Method': 'GET'}),
response_code=200,
response_origin=PUT_ORIGIN,
response_method='GET')
# Delete bucket cors
self.assert_result_status_code(
result=self.s3.delete_bucket_cors(Bucket=env.BUCKET), status_code=204)
# Send options requests
self.assert_cors_request_result(
result=requests.options(url=options_url,
headers={'Origin': PUT_ORIGIN, 'Access-Control-Request-Method': 'GET'}),
response_code=200,
response_origin=None,
response_method=None)
# Delete object
self.assert_delete_object_result(
result=self.s3.delete_object(Bucket=env.BUCKET, Key=key))
| 2,451
|
3,008
|
/// @ref core
/// @file glm/common.hpp
#pragma once
#include "detail/func_common.hpp"
| 37
|
2,989
|
<reponame>tb-soft/databus
package com.linkedin.databus2.core.filter;
/*
*
* Copyright 2013 LinkedIn Corp. 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.
*
*/
import org.codehaus.jackson.map.ObjectMapper;
import com.linkedin.databus.core.util.ConfigBuilder;
import com.linkedin.databus.core.util.InvalidConfigException;
/**
* @author bvaradar
*/
public class KeyRangeFilterConfig
extends KeyFilterConfig
{
private long rangeSize;
private IDConfig rangeIds;
protected static ObjectMapper _mapper;
public KeyRangeFilterConfig()
{
}
public KeyRangeFilterConfig(StaticConfig config)
{
super();
rangeSize = config.getSize();
rangeIds = config.getIdConfig();
}
public long getRangeSize() {
return rangeSize;
}
public void setRangeSize(long rangeSize) {
this.rangeSize = rangeSize;
}
public IDConfig getRangeIds() {
return rangeIds;
}
public void setRangeIds(IDConfig rangeIds) {
this.rangeIds = rangeIds;
}
@Override
public String toString() {
return "KeyRangeFilterConfig [rangeSize=" + rangeSize + ", rangeIds="
+ rangeIds + "]";
}
public static class StaticConfig
{
private long size;
private IDConfig idConfig;
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public IDConfig getIdConfig() {
return idConfig;
}
public void setIdConfig(IDConfig idConfig) {
this.idConfig = idConfig;
}
public StaticConfig(long size, IDConfig idConfig)
throws InvalidConfigException
{
super();
this.size = size;
this.idConfig = idConfig;
}
@Override
public String toString() {
return "KeyRangeFilterConfig.StaticConfig [size=" + size + ", idConfig=" + idConfig
+ "]";
}
}
public static class Config
implements ConfigBuilder<StaticConfig>
{
private long size;
private String partitions;
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public String getPartitions() {
return partitions;
}
public void setPartitions(String partitions) {
this.partitions = partitions;
}
@Override
public StaticConfig build()
throws InvalidConfigException
{
if ( size <= 0)
throw new InvalidConfigException("Range size (" + size + ") must be greater than 0");
StaticConfig sConf = null;
try
{
sConf = new StaticConfig(size, IDConfig.fromString(partitions));
} catch (Exception ex) {
throw new InvalidConfigException(ex);
}
return sConf;
}
}
}
| 1,065
|
652
|
<reponame>yangguanghei/iOS-Component-Pro
//
// WLPickerView.h
// WLPickerView
//
// Created by 刘光强 on 2018/5/18.
// Copyright © 2018年 quangqiang. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "WLTooBarView.h"
@interface WLPickerView : UIPickerView
@property (nonatomic, assign) NSInteger showTag;
@property (nonatomic, strong) WLTooBarView *toolBar;
@property (nonatomic, strong) UIView *containerView;
- (void)showMOFSPickerViewWithDataArray:(NSArray<NSString *> *)array commitBlock:(void(^)(NSString *string))commitBlock cancelBlock:(void(^)(void))cancelBlock;
- (void)showMOFSPickerViewWithCustomDataArray:(NSArray<NSString *> *)array keyMapper:(NSString *)keyMapper commitBlock:(void(^)(id model))commitBlock cancelBlock:(void(^)(void))cancelBlock;
@end
@interface NSString (WLPickerView)
@property (nonatomic, copy) NSString *mofs_key;
@property (nonatomic, assign) NSInteger mofs_int_key;
@end
| 330
|
706
|
<reponame>thesinepainter/similarity
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Core TensorFlow types."""
import dataclasses
from typing import Any, Callable, Mapping, Sequence, Optional, Union
import numpy as np
import tensorflow as tf
from tensorflow import Tensor
class PandasDataFrame(object):
"""Symbolic pandas frame
Pandas type are too loose you get an Any. We want a DataFrame
"""
pass
class BoolTensor(Tensor):
"""Bool tensor """
class FloatTensor(Tensor):
"""Float tensor """
class IntTensor(Tensor):
"""Integer tensor"""
class Symbol(Tensor):
"""Symbolic "graph" Tensor.
These objects represent the output of an op definition and do not carry a
value.
"""
pass
class Value(Tensor):
"""Tensor that can be associated with a value (aka "eager tensor").
These objects represent the (usually future) output of executing an op
immediately.
"""
def numpy(self):
pass
EqFunc = Callable[[Any, Any], bool]
def _optional_eq(a: Any, b: Any, eq_fun: EqFunc) -> bool:
"""__eq__ for Optional[Any] types."""
if a is None:
return b is None
elif b is None:
return False
return eq_fun(a, b)
def _basic_eq(a: Any, b: Any) -> bool:
eq: bool = a == b
return eq
def _ndarray_eq(a: np.ndarray, b: np.ndarray) -> bool:
eq: bool = np.allclose(a, b, rtol=0, atol=0, equal_nan=True)
return eq
def _tf_eq(a: Tensor, b: Tensor) -> bool:
eq: bool = tf.math.reduce_all(tf.math.equal(a, b))
return eq
@dataclasses.dataclass
class Lookup:
"""Metadata associated with a query match.
Attributes:
rank: Rank of the match with respect to the query distance.
distance: The distance from the match to the query.
label: The label associated with the match. Default None.
embedding: The embedded match vector. Default None.
data: The original Tensor representation of the match result.
Default None.
"""
rank: int
distance: float
label: Optional[int] = dataclasses.field(default=None)
embedding: Optional[np.ndarray] = dataclasses.field(default=None)
data: Optional[Tensor] = dataclasses.field(default=None)
def __eq__(self, other) -> bool:
if other.__class__ is not self.__class__:
return False
if self.rank != other.rank:
return False
if self.distance != other.distance:
return False
if not _optional_eq(self.label, other.label, _basic_eq):
return False
if not _optional_eq(self.embedding, other.embedding, _ndarray_eq):
return False
if not _optional_eq(self.data, other.data, _tf_eq):
return False
return True
@dataclasses.dataclass
class CalibrationResults:
"""Cutpoints and thresholds associated with a calibration.
Attributes:
cutpoints: A Dict mapping the cutpoint name to a Dict containing the
ClassificationMetric values associated with a particular distance
threshold, e.g., 'optimal' : {'acc': 0.90, 'f1': 0.92}.
thresholds: A Dict mapping ClassificationMetric names to a list
containing the metric's value computed at each of the distance
thresholds, e.g., {'f1': [0.99, 0.80], 'distance': [0.0, 1.0]}.
"""
cutpoints: Mapping[str, Mapping[str, Union[str, float, int]]]
thresholds: Mapping[str, Sequence[Union[float, int]]]
| 1,472
|
678
|
<reponame>bzxy/cydia<gh_stars>100-1000
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/WebCore.framework/WebCore
*/
#import <WebCore/XXUnknownSuperclass.h>
#import <WebCore/WebCore-Structs.h>
@interface WebScriptObjectPrivate : XXUnknownSuperclass {
@private
JSObject *imp; // 4 = 0x4
RootObject *rootObject; // 8 = 0x8
RootObject *originRootObject; // 12 = 0xc
BOOL isCreatedByDOMWrapper; // 16 = 0x10
}
@end
| 177
|
5,169
|
<filename>Specs/7/e/1/DoricMedia/0.1.0/DoricMedia.podspec.json
{
"name": "DoricMedia",
"version": "0.1.0",
"summary": "doric official media library.",
"description": "A powerful media framework & library built for doric.",
"homepage": "https://github.com/doric-pub/doriclib-media",
"license": {
"type": "Apache-2.0",
"file": "LICENSE"
},
"authors": {
"jingpeng": "<EMAIL>"
},
"source": {
"git": "https://github.com/doric-pub/doriclib-media.git",
"tag": "0.1.0"
},
"platforms": {
"ios": "10.0"
},
"source_files": "iOS/DoricMedia/Classes/**/*",
"xcconfig": {
"VALID_ARCHS": "armv7s arm64 x86_64"
},
"public_header_files": "iOS/DoricMedia/Classes/**/*.h",
"vendored_frameworks": "iOS/MediaPlayerFramework.framework",
"dependencies": {
"DoricCore": [
]
}
}
| 362
|
324
|
#include <collision_avoidance_pick_and_place/pick_and_place.h>
/* CREATE PLACE MOVES
Goal:
- Set the pose of the tcp at the box place pose
- Create tcp poses for the place motion (approach, release, retreat).
- Find transform of the wrist in tcp coordinates
- Convert tcp pick poses to wrist poses.
* MoveIt's kinematics require the target position to be specified relative to
one of the kinematic links of the manipulator arm (as defined in the SRDF)
Hints:
- You can manipulate the "world_to_tcp_tf" transform through the "setOrigin" and "setRotation".
- Use the "create_manipulation_poses" function to create the tcp poses between each place move
- Use the "transform_from_tcp_to_wrist" function to populate the "wrist_place_poses" array.
*/
std::vector<geometry_msgs::Pose> collision_avoidance_pick_and_place::PickAndPlace::create_place_moves()
{
ROS_ERROR_STREAM("create_place_moves is not implemented yet. Aborting."); exit(1);
// task variables
tf::Transform world_to_tcp_tf;
tf::StampedTransform tcp_to_wrist_tf;
std::vector<geometry_msgs::Pose> tcp_place_poses, wrist_place_poses;
/* Fill Code:
* Objective:
* - Find the desired tcp pose at box place
* Hints:
* - Use the "setOrigin" method to set the position of "world_to_tcp_tf"
* using cfg.BOX_PLACE_TF.
* - cfg.BOX_PLACE_TF is a tf::Transform object so it provides a getOrigin() method.
*/
/* ======== ENTER CODE HERE ======== */
/* Fill Code:
* Goal:
* - Reorient the tool so that the tcp points towards the box.
* Hints:
* - Use the "setRotation" to set the orientation of "world_to_tcp_tf".
* - The quaternion value "tf::Quaternion(0.707, 0.707, 0, 0)" will point
* the tcp's direction towards the box.
*/
/* ======== ENTER CODE HERE ======== */
/* Fill Code:
* Goal:
* - Create place poses for tcp. *
* Hints:
* - Use the "create_manipulation_poses" and save results to "tcp_place_poses".
* - Look in the "cfg" object to find the corresponding retreat and approach distance
* values.
*/
/* ======== ENTER CODE HERE ======== */
/* Fill Code:
* Goal:
* - Find transform from tcp to wrist.
* Hints:
* - Use the "lookupTransform" method in the transform listener.
* */
transform_listener_ptr->waitForTransform(cfg.TCP_LINK_NAME, cfg.WRIST_LINK_NAME, ros::Time(0.0f), ros::Duration(3.0f));
/* ======== ENTER CODE HERE ======== */
/* Fill Code:
* Goal:
* - Transform list of place poses from the tcp to the wrist coordinate frame.
* Hints:
* - Use the "transform_from_tcp_to_wrist" function and save results into
* "wrist_place_poses".
* - The "tcp_to_wrist_tf" is the transform that will help convert "tcp_place_poses"
* into "wrist_place_poses".
*/
/* ======== ENTER CODE HERE ======== */
// printing results
ROS_INFO_STREAM("tcp position at place: " << "[" << world_to_tcp_tf.getOrigin().getX() << ", " << world_to_tcp_tf.getOrigin().getY() << ", " << world_to_tcp_tf.getOrigin().getZ() << "]");
ROS_INFO_STREAM("wrist position at place: "<<wrist_place_poses[1].position);
return wrist_place_poses;
}
| 1,123
|
370
|
#define DINT
#include <../Source/umfpack_col_to_triplet.c>
| 25
|
486
|
<reponame>Mivik/jflex
package edu.tum.cup2.generator.exceptions;
import edu.tum.cup2.grammar.AuxiliaryLHS4SemanticShiftAction;
import edu.tum.cup2.grammar.SpecialTerminals;
import edu.tum.cup2.grammar.Terminal;
import edu.tum.cup2.parser.actions.Reduce;
import edu.tum.cup2.parser.actions.Shift;
/**
* Exception for a shift/reduce conflict.
*
* @author <NAME>
*/
public class ShiftReduceConflict extends GeneratorException
{
/** */
private static final long serialVersionUID = -3750877152502657460L;
private final Shift shift;
private final Reduce reduce;
private final Terminal terminal;
private String word;
public ShiftReduceConflict(Shift shift, Reduce reduce, Terminal terminal)
{
this.shift = shift;
this.reduce = reduce;
this.terminal = terminal;
word = null;
}
public void setWord(String word)
{
this.word = word;
}
public Shift getShift()
{
return shift;
}
public Reduce getReduce()
{
return reduce;
}
public Terminal getTerminal()
{
return terminal;
}
@Override
public String getMessage()
{
String sText = shift.getProduction().toString(shift.getPosition() - 1);
String rText = null;
if (reduce.getProduction().getLHS() instanceof AuxiliaryLHS4SemanticShiftAction)
rText = ((AuxiliaryLHS4SemanticShiftAction) reduce.getProduction().getLHS()).originatedFrom;
else
rText = reduce.getProduction().toString(reduce.getProduction().getRHS().size());
return "Shift/reduce conflict under terminal \""
+ terminal
+ "\" between:\n"
+ " "
+ sText
+ "\n"
+ " and\n"
+ " "
+ rText
+ "\n"
+ (word == null ? "" : " A minimal example input : " + word + " [conflict]"
+ (getTerminal() == SpecialTerminals.WholeRow ? "" : (" " + getTerminal())) + " ...");
}
}
| 779
|
6,304
|
<reponame>stayf/skia
"""
This file assembles a toolchain for Linux using the Clang Compiler and musl.
It currently makes use of musl and not glibc because the pre-compiled libraries from the latter
have absolute paths baked in and this makes linking difficult. The pre-compiled musl library
does not have this restriction and is much easier to statically link in as a result.
As inputs, it takes external URLs from which to download the clang binaries/libraries/includes
as well as the musl headers and pre-compiled binaries. Those files are downloaded and put
into one folder, with a little bit of re-arrangement so clang can find files (like the C runtime).
"""
def _download_and_extract_deb(ctx, deb, sha256, prefix, output = ""):
"""Downloads a debian file and extracts the data into the provided output directory"""
# https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#download
download_info = ctx.download(
url = deb,
output = "deb.ar",
sha256 = sha256,
)
# https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#execute
# This uses the extracted llvm-ar that comes with clang.
ctx.execute(["bin/llvm-ar", "x", "deb.ar"])
# https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#extract
extract_info = ctx.extract(
archive = "data.tar.xz",
output = output,
stripPrefix = prefix,
)
# Clean up
ctx.delete("deb.ar")
ctx.delete("data.tar.xz")
ctx.delete("control.tar.xz")
def _build_cpp_toolchain_impl(ctx):
# Download the clang toolchain (the extraction can take a while)
# https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#download
download_info = ctx.download_and_extract(
url = ctx.attr.clang_url,
output = "",
stripPrefix = ctx.attr.clang_prefix,
sha256 = ctx.attr.clang_sha256,
)
# This puts the musl include files in ${PWD}/usr/include/x86_64-linux-musl
# and the runtime files and lib.a files in ${PWD}/usr/lib/x86_64-linux-musl
_download_and_extract_deb(
ctx,
ctx.attr.musl_dev_url,
ctx.attr.musl_dev_sha256,
".",
)
# kjlubick@ cannot figure out how to get clang to look in ${PWD}/usr/lib/x86_64-linux-musl
# for the crt1.o files, so we'll move them to ${PWD}/usr/lib/ where clang *is* looking.
for file in ["crt1.o", "crtn.o", "Scrt1.o", "crti.o", "rcrt1.o"]:
ctx.execute(["cp", "usr/lib/x86_64-linux-musl/" + file, "usr/lib/"])
# Create a BUILD.bazel file that makes all the files in this subfolder
# available for use in rules, i.e. in the toolchain declaration.
# https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#file
ctx.file(
"BUILD.bazel",
content = """
filegroup(
name = "all_files",
srcs = glob([
"**",
]),
visibility = ["//visibility:public"]
)
""",
executable = False,
)
build_cpp_toolchain = repository_rule(
implementation = _build_cpp_toolchain_impl,
attrs = {
"clang_url": attr.string(mandatory = True),
"clang_sha256": attr.string(mandatory = True),
"clang_prefix": attr.string(mandatory = True),
"musl_dev_url": attr.string(mandatory = True),
"musl_dev_sha256": attr.string(mandatory = True),
},
doc = "",
)
| 1,370
|
1,311
|
import picamera
with picamera.PiCamera() as camera:
camera.resolution = (1024, 768)
camera.framerate = 30
camera.start_recording('highres.h264')
camera.start_recording('lowres.h264', splitter_port=2, resize=(320, 240))
camera.wait_recording(30)
camera.stop_recording(splitter_port=2)
camera.stop_recording()
| 128
|
312
|
<filename>solutions/LinksAndHandlebarsTemplate/src/webparts/featuredContentWebPart/FeaturedContentWebPart.manifest.json
{
"$schema": "https://dev.office.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "6e7296cf-4ba1-4c8e-8d21-41fe5f23900b",
"alias": "FeaturedContentWebPart",
"componentType": "WebPart",
"version": "*",
"manifestVersion": 2,
"supportedHosts": [
"SharePointWebPart"
],
"hiddenFromToolbox": true,
"preconfiguredEntries": [
{
"groupId": "6e7296cf-4ba1-4c8e-8d21-41fe5f23900b",
"group": {
"default": "Hub Web Parts"
},
"title": {
"default": "Hub Featured Content"
},
"description": {
"default": "This web part is used to display featured content links"
},
"officeFabricIconFontName": "Tiles",
"properties": {
"title": "",
"layoutMode": 0,
"featuredContentItems": [],
"usesListMode": false,
"advancedCamlQuery": "",
"advancedCamlData": ""
}
}
]
}
| 471
|
1,006
|
<gh_stars>1000+
/****************************************************************************
* arch/arm/src/kinetis/hardware/kinetis_sim.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
#ifndef __ARCH_ARM_SRC_KINETIS_HARDWARE_KINETIS_SIM_H
#define __ARCH_ARM_SRC_KINETIS_HARDWARE_KINETIS_SIM_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include "chip.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Register Offsets *********************************************************/
#define KINETIS_SIM_SOPT1_OFFSET 0x0000 /* System Options Register 1 */
#if defined (KINETIS_SIM_HAS_SOPT1CFG)
# define KINETIS_SIM_SOPT1CFG_OFFSET 0x0004 /* SOPT1 Configuration Register */
#endif
#if defined(KINETIS_SIM_HAS_USBPHYCTL)
# define KINETIS_SIM_USBPHYCTL_OFFSET 0x0008 /* USB PHY Control Register */
#endif
#if defined(KINETIS_SIM_HAS_SOPT2)
# define KINETIS_SIM_SOPT2_OFFSET 0x0004 /* System Options Register 2 */
#endif
#define KINETIS_SIM_SOPT4_OFFSET 0x000c /* System Options Register 4 */
#define KINETIS_SIM_SOPT5_OFFSET 0x0010 /* System Options Register 5 */
#define KINETIS_SIM_SOPT6_OFFSET 0x0014 /* System Options Register 6 */
#define KINETIS_SIM_SOPT7_OFFSET 0x0018 /* System Options Register 7 */
#if defined(KINETIS_SIM_HAS_SOPT8)
# define KINETIS_SIM_SOPT8_OFFSET 0x001c /* System Options Register 8 */
#endif
#if defined(KINETIS_SIM_HAS_SOPT9)
# define KINETIS_SIM_SOPT9_OFFSET 0x0020 /* System Options Register 9 */
#endif
#define KINETIS_SIM_SDID_OFFSET 0x0024 /* System Device Identification Register */
#define KINETIS_SIM_SCGC1_OFFSET 0x0028 /* System Clock Gating Control Register 1 */
#define KINETIS_SIM_SCGC2_OFFSET 0x002c /* System Clock Gating Control Register 2 */
#define KINETIS_SIM_SCGC3_OFFSET 0x0030 /* System Clock Gating Control Register 3 */
#define KINETIS_SIM_SCGC4_OFFSET 0x0034 /* System Clock Gating Control Register 4 */
#define KINETIS_SIM_SCGC5_OFFSET 0x0038 /* System Clock Gating Control Register 5 */
#define KINETIS_SIM_SCGC6_OFFSET 0x003c /* System Clock Gating Control Register 6 */
#define KINETIS_SIM_SCGC7_OFFSET 0x0040 /* System Clock Gating Control Register 7 */
#define KINETIS_SIM_CLKDIV1_OFFSET 0x0044 /* System Clock Divider Register 1 */
#define KINETIS_SIM_CLKDIV2_OFFSET 0x0048 /* System Clock Divider Register 2 */
#define KINETIS_SIM_FCFG1_OFFSET 0x004c /* Flash Configuration Register 1 */
#define KINETIS_SIM_FCFG2_OFFSET 0x0050 /* Flash Configuration Register 2 */
#define KINETIS_SIM_UIDH_OFFSET 0x0054 /* Unique Identification Register High */
#define KINETIS_SIM_UIDMH_OFFSET 0x0058 /* Unique Identification Register Mid-High */
#define KINETIS_SIM_UIDML_OFFSET 0x005c /* Unique Identification Register Mid Low */
#define KINETIS_SIM_UIDL_OFFSET 0x0060 /* Unique Identification Register Low */
#if defined(KINETIS_SIM_HAS_CLKDIV3)
# define KINETIS_SIM_CLKDIV3_OFFSET 0x0064 /* System Clock Divider Register 3 */
#endif
#if defined(KINETIS_SIM_HAS_CLKDIV4)
# define KINETIS_SIM_CLKDIV4_OFFSET 0x0068 /* System Clock Divider Register 4 */
#endif
/* Register Addresses *******************************************************/
/* NOTE:
* The SIM_SOPT1, SIM_SOPT1CFG and SIM_USBPHYCTL registers are located at a
* different base address than the other SIM registers.
*/
#define KINETIS_SIM_SOPT1 (KINETIS_SIMLP_BASE+KINETIS_SIM_SOPT1_OFFSET)
#if defined(KINETIS_SIM_HAS_SOPT1CFG)
# define KINETIS_SIM_SOPT1CFG (KINETIS_SIMLP_BASE+KINETIS_SIM_SOPT1CFG_OFFSET)
#endif
#if defined(KINETIS_SIM_HAS_USBPHYCTL)
# define KINETIS_SIM_USBPHYCTL (KINETIS_SIMLP_BASE+KINETIS_SIM_USBPHYCTL_OFFSET)
#endif
#if defined(KINETIS_SIM_HAS_SOPT2)
# define KINETIS_SIM_SOPT2 (KINETIS_SIM_BASE+KINETIS_SIM_SOPT2_OFFSET)
#endif
#define KINETIS_SIM_SOPT4 (KINETIS_SIM_BASE+KINETIS_SIM_SOPT4_OFFSET)
#define KINETIS_SIM_SOPT5 (KINETIS_SIM_BASE+KINETIS_SIM_SOPT5_OFFSET)
#define KINETIS_SIM_SOPT6 (KINETIS_SIM_BASE+KINETIS_SIM_SOPT6_OFFSET)
#define KINETIS_SIM_SOPT7 (KINETIS_SIM_BASE+KINETIS_SIM_SOPT7_OFFSET)
#if defined(KINETIS_SIM_HAS_SOPT8)
# define KINETIS_SIM_SOPT8 (KINETIS_SIM_BASE+KINETIS_SIM_SOPT8_OFFSET)
#endif
#if defined(KINETIS_SIM_HAS_SOPT9)
# define KINETIS_SIM_SOPT9 (KINETIS_SIM_BASE+KINETIS_SIM_SOPT8_OFFSET)
#endif
#define KINETIS_SIM_SDID (KINETIS_SIM_BASE+KINETIS_SIM_SDID_OFFSET)
#define KINETIS_SIM_SCGC1 (KINETIS_SIM_BASE+KINETIS_SIM_SCGC1_OFFSET)
#define KINETIS_SIM_SCGC2 (KINETIS_SIM_BASE+KINETIS_SIM_SCGC2_OFFSET)
#define KINETIS_SIM_SCGC3 (KINETIS_SIM_BASE+KINETIS_SIM_SCGC3_OFFSET)
#define KINETIS_SIM_SCGC4 (KINETIS_SIM_BASE+KINETIS_SIM_SCGC4_OFFSET)
#define KINETIS_SIM_SCGC5 (KINETIS_SIM_BASE+KINETIS_SIM_SCGC5_OFFSET)
#define KINETIS_SIM_SCGC6 (KINETIS_SIM_BASE+KINETIS_SIM_SCGC6_OFFSET)
#define KINETIS_SIM_SCGC7 (KINETIS_SIM_BASE+KINETIS_SIM_SCGC7_OFFSET)
#define KINETIS_SIM_CLKDIV1 (KINETIS_SIM_BASE+KINETIS_SIM_CLKDIV1_OFFSET)
#define KINETIS_SIM_CLKDIV2 (KINETIS_SIM_BASE+KINETIS_SIM_CLKDIV2_OFFSET)
#define KINETIS_SIM_FCFG1 (KINETIS_SIM_BASE+KINETIS_SIM_FCFG1_OFFSET)
#define KINETIS_SIM_FCFG2 (KINETIS_SIM_BASE+KINETIS_SIM_FCFG2_OFFSET)
#define KINETIS_SIM_UIDH (KINETIS_SIM_BASE+KINETIS_SIM_UIDH_OFFSET)
#define KINETIS_SIM_UIDMH (KINETIS_SIM_BASE+KINETIS_SIM_UIDMH_OFFSET)
#define KINETIS_SIM_UIDML (KINETIS_SIM_BASE+KINETIS_SIM_UIDML_OFFSET)
#define KINETIS_SIM_UIDL (KINETIS_SIM_BASE+KINETIS_SIM_UIDL_OFFSET)
#if defined(KINETIS_SIM_HAS_CLKDIV3)
# define KINETIS_SIM_CLKDIV3 (KINETIS_SIM_BASE+KINETIS_SIM_CLKDIV3_OFFSET)
#endif
#if defined(KINETIS_SIM_HAS_CLKDIV4)
# define KINETIS_SIM_CLKDIV4 (KINETIS_SIM_BASE+KINETIS_SIM_CLKDIV4_OFFSET)
#endif
/* Register Bit Definitions *************************************************/
/* System Options Register 1 */
/* Bits 0-11:
* Reserved
*/
#if defined(KINETIS_SIM_HAS_SOPT1_RAMSIZE)
# define SIM_SOPT1_RAMSIZE_SHIFT (12) /* Bits 12-15: RAM size */
# define SIM_SOPT1_RAMSIZE_MASK (15 << SIM_SOPT1_RAMSIZE_SHIFT)
# define SIM_SOPT1_RAMSIZE_32KB (5 << SIM_SOPT1_RAMSIZE_SHIFT) /* 32 KBytes */
# define SIM_SOPT1_RAMSIZE_64KB (7 << SIM_SOPT1_RAMSIZE_SHIFT) /* 64 KBytes */
# define SIM_SOPT1_RAMSIZE_96KB (8 << SIM_SOPT1_RAMSIZE_SHIFT) /* 96 KBytes */
# define SIM_SOPT1_RAMSIZE_128KB (9 << SIM_SOPT1_RAMSIZE_SHIFT) /* 128 KBytes */
# define SIM_SOPT1_RAMSIZE_256KB (10 << SIM_SOPT1_RAMSIZE_SHIFT) /* 256 KBytes */
#endif
/* Bits 16-18:
* Reserved
*/
#if defined(KINETIS_SIM_HAS_SOPT1_OSC32KSEL)
# define SIM_SOPT1_OSC32KSEL_SHIFT (20-KINETIS_SIM_HAS_SOPT1_OSC32KSEL_BITS) /* Bit 19 or 18: 32K oscillator clock select */
# define SIM_SOPT1_OSC32KSEL_MASK (KINETIS_SIM_SOPT1_OSC32KSEL_MASK << SIM_SOPT1_OSC32KSEL_SHIFT)
# define SIM_SOPT1_OSC32KSEL(n) ((((n) & KINETIS_SIM_SOPT1_OSC32KSEL_MASK)) << SIM_SOPT1_OSC32KSEL_SHIFT)
# if KINETIS_SIM_HAS_SOPT1_OSC32KSEL_BITS == 1
# define SIM_SOPT1_OSC32KSEL_OSC32KCLK (((0 & KINETIS_SIM_SOPT1_OSC32KSEL_MASK)) << SIM_SOPT1_OSC32KSEL_SHIFT)
# define SIM_SOPT1_OSC32KSEL_RTC (((1 & KINETIS_SIM_SOPT1_OSC32KSEL_MASK)) << SIM_SOPT1_OSC32KSEL_SHIFT)
# endif
# if KINETIS_SIM_HAS_SOPT1_OSC32KSEL_BITS == 2
# define SIM_SOPT1_OSC32KSEL_OSC32KCLK (((0 & KINETIS_SIM_SOPT1_OSC32KSEL_MASK)) << SIM_SOPT1_OSC32KSEL_SHIFT)
# define SIM_SOPT1_OSC32KSEL_RTC (((2 & KINETIS_SIM_SOPT1_OSC32KSEL_MASK)) << SIM_SOPT1_OSC32KSEL_SHIFT)
# define SIM_SOPT1_OSC32KSEL_LPO1KZ (((3 & KINETIS_SIM_SOPT1_OSC32KSEL_MASK)) << SIM_SOPT1_OSC32KSEL_SHIFT)
# endif
#endif
/* Bits 20-28:
* Reserved
*/
#if defined(KINETIS_SIM_HAS_SOPT1_USBVSTBY)
/* Bits 24-28:
* Reserved
*/
# define SIM_SOPT1_USBVSTBY (1 << 29) /* Bit 29: USB voltage regulator in standby mode during VLPR and VLPW modes */
#endif
#if defined(KINETIS_SIM_HAS_SOPT1_USBSSTBY)
# define SIM_SOPT1_USBSTBY (1 << 30) /* Bit 30: USB voltage regulator in standby mode */
#endif
#if defined(KINETIS_SIM_HAS_SOPT1_USBREGEN)
# define SIM_SOPT1_USBREGEN (1 << 31) /* Bit 31: USB voltage regulator enable */
#endif
/* SOPT1 Configuration Register */
#if defined(KINETIS_SIM_HAS_SOPT1CFG)
/* Bits 0-22:
* Reserved
*/
# if defined(KINETIS_SIM_HAS_SOPT1CFG_URWE)
# define SIM_SOPT1CFG_URWE (1 << 24) /* Bit 24: USB voltage regulator enable write enable */
# endif
# if defined(KINETIS_SIM_HAS_SOPT1CFG_USSWE)
# define SIM_SOPT1CFG_USSWE (1 << 25) /* Bit 25: USB voltage regulator VLP standby write enable */
# endif
# if defined(KINETIS_SIM_HAS_SOPT1CFG_UVSWE)
# define SIM_SOPT1CFG_UVSWE (1 << 26) /* Bit 26: USB voltage regulator stop standby write enable */
# endif
/* Bits 27-31: Reserved */
#endif
/* USB PHY Control Register */
#if defined(KINETIS_SIM_HAS_USBPHYCTL)
/* Bits 0-7:
* Reserved
*/
# if defined(KINETIS_SIM_HAS_USBPHYCTL_USBVREGSEL)
# define SIM_USBPHYCTL_USBVREGSEL (1 << 8) /* Bit 8: Selects the default input voltage source */
# endif
# if defined(KINETIS_SIM_HAS_USBPHYCTL_USBVREGPD)
# define SIM_USBPHYCTL_USBVREGPD (1 << 9) /* Bit 9: Enables the pulldown on the output of the USB Regulator */
# endif
/* Bits 10-19: Reserved */
# if defined(KINETIS_SIM_HAS_USBPHYCTL_USB3VOUTTRG)
# define SIM_USBPHYCTL_USB3VOUTTRG_SHIFT (20) /* Bit 20-22: USB 3.3V Output Target */
# define SIM_USBPHYCTL_USB3VOUTTRG_MASK (7 << SIM_USBPHYCTL_USB3VOUTTRG_SHIFT)
# define SIM_USBPHYCTL_USB3VOUTTRG_2V733 (0 << SIM_USBPHYCTL_USB3VOUTTRG_SHIFT) /* 2.733V */
# define SIM_USBPHYCTL_USB3VOUTTRG_3V020 (1 << SIM_USBPHYCTL_USB3VOUTTRG_SHIFT) /* 3.020V */
# define SIM_USBPHYCTL_USB3VOUTTRG_3V074 (2 << SIM_USBPHYCTL_USB3VOUTTRG_SHIFT) /* 3.074V */
# define SIM_USBPHYCTL_USB3VOUTTRG_3V130 (3 << SIM_USBPHYCTL_USB3VOUTTRG_SHIFT) /* 3.130V */
# define SIM_USBPHYCTL_USB3VOUTTRG_3V188 (4 << SIM_USBPHYCTL_USB3VOUTTRG_SHIFT) /* 3.188V */
# define SIM_USBPHYCTL_USB3VOUTTRG_3V248 (5 << SIM_USBPHYCTL_USB3VOUTTRG_SHIFT) /* 3.248V */
# define SIM_USBPHYCTL_USB3VOUTTRG_3V310 (6 << SIM_USBPHYCTL_USB3VOUTTRG_SHIFT) /* 3.310V (default) */
# define SIM_USBPHYCTL_USB3VOUTTRG_3V662 (7 << SIM_USBPHYCTL_USB3VOUTTRG_SHIFT) /* 3.662V (For Freescale use only, not for customer use) */
# endif
# if defined(KINETIS_SIM_HAS_USBPHYCTL_USBDISILIM)
# define SIM_USBPHYCTL_USBDISILIM (1 << 23) /* Bit 23: USB Disable Inrush Current Limit */
# endif
/* Bits 24-31: Reserved */
#endif
/* System Options Register 2 */
#if defined(KINETIS_SIM_HAS_SOPT2)
# if defined(KINETIS_SIM_HAS_SOPT2_MCGCLKSEL)
# define SIM_SOPT2_MCGCLKSEL (1 << 0) /* Bit 0: MCG clock select */
# endif
# if defined(KINETIS_SIM_HAS_SOPT2_USBSLSRC)
# define SIM_SOPT2_USBSLSRC (1 << 0) /* Bit 0: USB Slow Clock Source */
# endif
# if defined(KINETIS_SIM_HAS_SOPT2_USBREGEN)
# define SIM_SOPT2_USBREGEN (1 << 1) /* Bit 1: USB PHY PLL Regulator Enable */
# endif
/* Bits 2-3: Reserved */
# if defined(KINETIS_SIM_HAS_SOPT2_USBHSRC)
# define SIM_SOPT2_USBSHSRC_SHIFT (2) /* Bit 2-3: USB HS clock source select */
# define SIM_SOPT2_USBSHSRC_MASK (3 << SIM_SOPT2_USBSHSRC_SHIFT)
# define SIM_SOPT2_USBSHSRC_BUSCLK (0 << SIM_SOPT2_USBSHSRC_SHIFT)
# define SIM_SOPT2_USBSHSRC_MCGPLL0CLK (1 << SIM_SOPT2_USBSHSRC_SHIFT)
# define SIM_SOPT2_USBSHSRC_MCGPLL1CLK (2 << SIM_SOPT2_USBSHSRC_SHIFT)
# define SIM_SOPT2_USBSHSRC_OSC0ERCLK (3 << SIM_SOPT2_USBSHSRC_SHIFT)
# endif
# if defined(KINETIS_SIM_HAS_SOPT2_RTCCLKOUTSEL)
# define SIM_SOPT2_RTCCLKOUTSEL (1 << 4) /* Bit 4: RTC clock out select */
# endif
# if defined(KINETIS_SIM_HAS_SOPT2_CLKOUTSEL)
# define SIM_SOPT2_CLKOUTSEL_SHIFT (5) /* Bits 5-7: CLKOUT select */
# define SIM_SOPT2_CLKOUTSEL_MASK (7 << SIM_SOPT2_CLKOUTSEL_SHIFT)
# define SIM_SOPT2_CLKOUTSEL_FBCLKOUT (0 << SIM_SOPT2_CLKOUTSEL_SHIFT)
# define SIM_SOPT2_CLKOUTSEL_FLSHCLK (2 << SIM_SOPT2_CLKOUTSEL_SHIFT)
# define SIM_SOPT2_CLKOUTSEL_LPO1KHZ (3 << SIM_SOPT2_CLKOUTSEL_SHIFT)
# define SIM_SOPT2_CLKOUTSEL_MCGIRCLK (4 << SIM_SOPT2_CLKOUTSEL_SHIFT)
# define SIM_SOPT2_CLKOUTSEL_RTC32768KHZ (5 << SIM_SOPT2_CLKOUTSEL_SHIFT)
# define SIM_SOPT2_CLKOUTSEL_OSCERCLK0 (6 << SIM_SOPT2_CLKOUTSEL_SHIFT)
# define SIM_SOPT2_CLKOUTSEL_IRC48MHZ (7 << SIM_SOPT2_CLKOUTSEL_SHIFT)
# endif
# if defined(KINETIS_SIM_HAS_SOPT2_FBSL)
# define SIM_SOPT2_FBSL_SHIFT (8) /* Bits 8-9: FlexBus security level */
# define SIM_SOPT2_FBSL_MASK (3 << SIM_SOPT2_FBSL_SHIFT)
# define SIM_SOPT2_FBSL_NONE (0 << SIM_SOPT2_FBSL_SHIFT) /* All off-chip accesses disallowed */
# define SIM_SOPT2_FBSL_DATA (2 << SIM_SOPT2_FBSL_SHIFT) /* Off-chip data accesses are allowed */
# define SIM_SOPT2_FBSL_ALL (3 << SIM_SOPT2_FBSL_SHIFT) /* All Off-chip accesses allowed */
# endif
/* Bit 10: Reserved */
# if defined(KINETIS_SIM_HAS_SOPT2_CMTUARTPAD)
# define SIM_SOPT2_CMTUARTPAD (1 << 11) /* Bit 11: CMT/UART pad drive strength */
# endif
# if defined(KINETIS_SIM_HAS_SOPT2_PTD7PAD)
# define SIM_SOPT2_PTD7PAD (1 << 11) /* Bit 11: PTD7P pad drive strength */
# endif
# if defined(KINETIS_SIM_HAS_SOPT2_TRACECLKSEL)
# define SIM_SOPT2_TRACECLKSEL (1 << 12) /* Bit 12: Debug trace clock select */
# endif
/* Bits 13-15: Reserved */
# if defined(KINETIS_SIM_HAS_SOPT2_PLLFLLSEL)
# define SIM_SOPT2_PLLFLLSEL_SHIFT (16) /* Bits 16-[17]: PLL/FLL clock select */
# define SIM_SOPT2_PLLFLLSEL_MASK (KINETIS_SIM_SOPT2_PLLFLLSEL_MASK << SIM_SOPT2_PLLFLLSEL_SHIFT)
# define SIM_SOPT2_PLLFLLSEL(n) (((n) & KINETIS_SIM_SOPT2_PLLFLLSEL_MASK) << SIM_SOPT2_PLLFLLSEL_SHIFT)
# define SIM_SOPT2_PLLFLLSEL_MCGFLLCLK ((0 & KINETIS_SIM_SOPT2_PLLFLLSEL_MASK) << SIM_SOPT2_PLLFLLSEL_SHIFT)
# define SIM_SOPT2_PLLFLLSEL_MCGPLLCLK ((1 & KINETIS_SIM_SOPT2_PLLFLLSEL_MASK) << SIM_SOPT2_PLLFLLSEL_SHIFT)
# if KINETIS_SIM_HAS_SOPT2_PLLFLLSEL_BITS > 1
# define SIM_SOPT2_PLLFLLSEL_USB1PFD ((2 & KINETIS_SIM_SOPT2_PLLFLLSEL_MASK) << SIM_SOPT2_PLLFLLSEL_SHIFT)
# define SIM_SOPT2_PLLFLLSEL_IRC48MHZ ((3 & KINETIS_SIM_SOPT2_PLLFLLSEL_MASK) << SIM_SOPT2_PLLFLLSEL_SHIFT)
# endif
# endif
/* Bit 17: Reserved */
# if defined(KINETIS_SIM_HAS_SOPT2_USBSRC)
# define SIM_SOPT2_USBSRC (1 << 18) /* Bit 18: USB clock source select */
# endif
/* Bit 19: Reserved */
# if defined(KINETIS_SIM_HAS_SOPT2_RMIISRC)
# define SIM_SOPT2_RMIISRC_SHIFT (19) /* Bit 19: RMII clock source select */
# define SIM_SOPT2_RMIISRC_EXTAL (0 << SIM_SOPT2_RMIISRC_SHIFT) /* EXTAL clock */
# define SIM_SOPT2_RMIISRC_EXTBYP (1 << SIM_SOPT2_RMIISRC_SHIFT) /* External bypass clock (ENET_1588_CLKIN) */
# endif
# if defined(KINETIS_SIM_HAS_SOPT2_TIMESRC)
# define SIM_SOPT2_TIMESRC_SHIFT (20) /* Bit 20-21: IEEE 1588 timestamp clock source select */
# define SIM_SOPT2_TIMESRC_MASK (3 << SIM_SOPT2_TIMESRC_SHIFT)
# define SIM_SOPT2_TIMESRC_CORE (0 << SIM_SOPT2_TIMESRC_SHIFT) /* Core/system clock */
# define SIM_SOPT2_TIMESRC_PLLSEL (1 << SIM_SOPT2_TIMESRC_SHIFT) /* MCGFLLCLK,MCGPLLCLK,IRC48M,USB1 PFD
* clock as selected by SOPT2[PLLFLLSEL] */
# define SIM_SOPT2_TIMESRC_OSCERCLK (2 << SIM_SOPT2_TIMESRC_SHIFT) /* OSCERCLK clock */
# define SIM_SOPT2_TIMESRC_EXTBYP (3 << SIM_SOPT2_TIMESRC_SHIFT) /* External bypass clock (ENET_1588_CLKIN) */
# endif
# if defined(KINETIS_SIM_HAS_SOPT2_FLEXIOSRC)
# define SIM_SOPT2_FLEXIOSRC_SHIFT (22) /* Bits 22-23: FlexIO Module Clock Source Select */
# define SIM_SOPT2_FLEXIOSRC_MASK (3 << SIM_SOPT2_FLEXIOSRC_SHIFT)
# define SIM_SOPT2_FLEXIOSRC_CORE (0 << SIM_SOPT2_FLEXIOSRC_SHIFT) /* Core/system clock */
# define SIM_SOPT2_FLEXIOSRC_PLLSEL (1 << SIM_SOPT2_FLEXIOSRC_SHIFT) /* MCGFLLCLK,MCGPLLCLK,IRC48M,USB1 PFD
* clock as selected by SOPT2[PLLFLLSEL] */
# define SIM_SOPT2_FLEXIOSRC_OSCERCLK (2 << SIM_SOPT2_FLEXIOSRC_SHIFT) /* OSCERCLK clock */
# define SIM_SOPT2_FLEXIOSRC_MCGIRCLK (3 << SIM_SOPT2_FLEXIOSRC_SHIFT) /* MCGIRCLK clock */
# endif
# if defined(KINETIS_SIM_HAS_SOPT2_USBFSRC)
# define SIM_SOPT2_USBFSRC_SHIFT (22) /* Bits 22-23: USB FS clock source select */
# define SIM_SOPT2_USBFSRC_MASK (3 << SIM_SOPT2_USBFSRC_SHIFT)
# define SIM_SOPT2_USBFSRC_MCGCLK (0 << SIM_SOPT2_USBFSRC_SHIFT) /* MCGFLLCLK,MCGPLLCLK clock as selected by SOPT2[PLLFLLSEL] */
# define SIM_SOPT2_USBFSRC_MCGPLL0CLK (1 << SIM_SOPT2_USBFSRC_SHIFT) /* MCGPLL0CLK clock */
# define SIM_SOPT2_USBFSRC_MCGPLL1CLK (2 << SIM_SOPT2_USBFSRC_SHIFT) /* MCGPLL1CLK clock */
# define SIM_SOPT2_USBFSRC_OCS0ERCLK (3 << SIM_SOPT2_USBFSRC_SHIFT) /* OSC0ERCLK clock */
# endif
# if defined(KINETIS_SIM_HAS_SOPT2_TPMSRC)
# define SIM_SOPT2_TPMSRC_SHIFT (24) /* Bits 24-25: TPM clock source select */
# define SIM_SOPT2_TPMSRC_MASK (3 << SIM_SOPT2_TPMSRC_SHIFT)
# define SIM_SOPT2_TPMSRC_CORE (0 << SIM_SOPT2_TPMSRC_SHIFT) /* Clock disabled */
# define SIM_SOPT2_TPMSRC_MCGCLK (1 << SIM_SOPT2_TPMSRC_SHIFT) /* MCGFLLCLK,MCGPLLCLK,IRC48M,USB1 PFD
* clock as selected by SOPT2[PLLFLLSEL] and then
* divided by the PLLFLLCLK fractional divider
* as configured by SIM_CLKDIV3[PLLFLLFRAC, PLLFLLDIV] */
# define SIM_SOPT2_TPMSRC_OCSERCLK (2 << SIM_SOPT2_TPMSRC_SHIFT) /* OSCERCLK clock */
# define SIM_SOPT2_TPMSRC_MCGIRCLK (3 << SIM_SOPT2_TPMSRC_SHIFT) /* MCGIRCLK clock */
# endif
# if defined(KINETIS_SIM_HAS_SOPT2_I2SSRC)
# define SIM_SOPT2_I2SSRC_SHIFT (24) /* Bits 24-25: I2S master clock source select */
# define SIM_SOPT2_I2SSRC_MASK (3 << SIM_SOPT2_I2SSRC_SHIFT)
# define SIM_SOPT2_I2SCSRC_CORE (0 << SIM_SOPT2_I2SSRC_SHIFT) /* Core/system clock / I2S fractional divider */
# define SIM_SOPT2_I2SCSRC_MCGCLK (1 << SIM_SOPT2_I2SSRC_SHIFT) /* MCGPLLCLK/MCGFLLCLK clock/ I2S fractional divider */
# define SIM_SOPT2_I2SCSRC_OCSERCLK (2 << SIM_SOPT2_I2SSRC_SHIFT) /* OSCERCLK clock */
# define SIM_SOPT2_I2SCSRC_EXTBYP (3 << SIM_SOPT2_I2SSRC_SHIFT) /* External bypass clock (I2S0_CLKIN) */
# endif
/* Bits 26-27: Reserved */
# if defined(KINETIS_SIM_HAS_SOPT2_LPUARTSRC)
# define SIM_SOPT2_LPUARTSRC_SHIFT (26) /* Bits 26-27: LPUART clock source select */
# define SIM_SOPT2_LPUARTSRC_MASK (3 << SIM_SOPT2_LPUARTSRC_SHIFT)
# define SIM_SOPT2_LPUARTSRC_CORE (0 << SIM_SOPT2_LPUARTSRC_SHIFT) /* Clock disabled */
# define SIM_SOPT2_LPUARTSRC_MCGCLK (1 << SIM_SOPT2_LPUARTSRC_SHIFT) /* MCGFLLCLK,MCGPLLCLK,IRC48M,USB1 PFD
* clock as selected by SOPT2[PLLFLLSEL] and then
* divided by the PLLFLLCLK fractional divider
* as configured by SIM_CLKDIV3[PLLFLLFRAC, PLLFLLDIV] */
# define SIM_SOPT2_LPUARTSRC_OCSERCLK (2 << SIM_SOPT2_LPUARTSRC_SHIFT) /* OSCERCLK clock */
# define SIM_SOPT2_LPUARTSRC_MCGIRCLK (3 << SIM_SOPT2_LPUARTSRC_SHIFT) /* MCGIRCLK clock */
# endif
# if defined(KINETIS_SIM_HAS_SOPT2_SDHCSRC)
# define SIM_SOPT2_SDHCSRC_SHIFT (28) /* Bits 28-29: SDHC clock source select */
# define SIM_SOPT2_SDHCSRC_MASK (3 << SIM_SOPT2_SDHCSRC_SHIFT)
# define SIM_SOPT2_SDHCSRC_CORE (0 << SIM_SOPT2_SDHCSRC_SHIFT) /* Core/system clock */
# define SIM_SOPT2_SDHCSRC_MCGCLK (1 << SIM_SOPT2_SDHCSRC_SHIFT) /* MCGPLLCLK/MCGFLLCLK clock */
# define SIM_SOPT2_SDHCSRC_OCSERCLK (2 << SIM_SOPT2_SDHCSRC_SHIFT) /* OSCERCLK clock */
# define SIM_SOPT2_SDHCSRC_EXTBYP (3 << SIM_SOPT2_SDHCSRC_SHIFT) /* External bypass clock (SDHC0_CLKIN) */
/* Bits 30-31:
* Reserved
*/
# endif
/* Bits 30-31:
* Reserved
*/
# if defined(KINETIS_SIM_HAS_SOPT2_NFCSRC)
# define SIM_SOPT2_NFCSRC_SHIFT (30) /* Bits 30-31: NFC Flash clock source select */
# define SIM_SOPT2_NFCSRC_MASK (3 << SIM_SOPT2_NFCSRC_SHIFT)
# define SIM_SOPT2_NFCSRC_BUS (0 << SIM_SOPT2_NFCSRC_SHIFT) /* BUS clock */
# define SIM_SOPT2_NFCSRC_MCGPLL0CLK (1 << SIM_SOPT2_NFCSRC_SHIFT) /* MCGPLL0CLK clock */
# define SIM_SOPT2_NFCSRC_MCGPLL1CLK (2 << SIM_SOPT2_NFCSRC_SHIFT) /* MCGPLL1CLK clock */
# define SIM_SOPT2_NFCSRC_OCS0ERCLK (3 << SIM_SOPT2_NFCSRC_SHIFT) /* OSC0ERCLK clock */
# endif
#endif
/* System Options Register 4 */
#define SIM_SOPT4_FTM0FLT0 (1 << 0) /* Bit 0: FTM0 Fault 0 Select */
#define SIM_SOPT4_FTM0FLT1 (1 << 1) /* Bit 1: FTM0 Fault 1 Select */
#if defined(KINETIS_SIM_HAS_SOPT4_FTM0FLT2)
# define SIM_SOPT4_FTM0FLT2 (1 << 2) /* Bit 2: FTM0 Fault 2 Select */
#endif
/* Bit 3: Reserved */
#if defined(KINETIS_SIM_HAS_SOPT4_FTM0FLT3)
# define SIM_SOPT4_FTM0FLT3 (1 << 3) /* Bit 3: FTM0 Fault 3 Select */
#endif
#define SIM_SOPT4_FTM1FLT0 (1 << 4) /* Bit 4: FTM1 Fault 0 Select */
/* Bits 5-7: Reserved */
#define SIM_SOPT4_FTM2FLT0 (1 << 8) /* Bit 8: FTM2 Fault 0 Select */
/* Bits 9-17: Reserved */
#if defined(KINETIS_SIM_HAS_SOPT4_FTM3FLT0)
/* Bits 9-11,13-17: Reserved */
# define SIM_SOPT4_FTM3FLT0 (1 << 12) /* Bit 12: FTM3 Fault 0 Select */
#endif
#if defined(KINETIS_SIM_HAS_SOPT4_FTM1CH0SRC)
# define SIM_SOPT4_FTM1CH0SRC_SHIFT (18) /* Bits 18-19: FTM1 channel 0 input capture source select */
# define SIM_SOPT4_FTM1CH0SRC_MASK (3 << SIM_SOPT4_FTM1CH0SRC_SHIFT)
# define SIM_SOPT4_FTM1CH0SRC_CH0 (0 << SIM_SOPT4_FTM1CH0SRC_SHIFT) /* FTM1_CH0 signal */
# define SIM_SOPT4_FTM1CH0SRC_CMP0 (1 << SIM_SOPT4_FTM1CH0SRC_SHIFT) /* CMP0 output */
# define SIM_SOPT4_FTM1CH0SRC_CMP1 (2 << SIM_SOPT4_FTM1CH0SRC_SHIFT) /* CMP1 output */
# if KINETIS_SIM_HAS_SOPT4_FTM1CH0SRC > 2
# define SIM_SOPT4_FTM1CH0SRC_USBSOF (3 << SIM_SOPT4_FTM1CH0SRC_SHIFT) /* USB start of frame pulse */
# endif
#endif
#if defined(KINETIS_SIM_HAS_SOPT4_FTM2CH0SRC)
# define SIM_SOPT4_FTM2CH0SRC_SHIFT (20) /* Bits 20-21: FTM2 channel 0 input capture source select */
# define SIM_SOPT4_FTM2CH0SRC_MASK (3 << SIM_SOPT4_FTM2CH0SRC_SHIFT)
# define SIM_SOPT4_FTM2CH0SRC_CH0 (0 << SIM_SOPT4_FTM2CH0SRC_SHIFT) /* FTM2_CH0 signal */
# define SIM_SOPT4_FTM2CH0SRC_CMP0 (1 << SIM_SOPT4_FTM2CH0SRC_SHIFT) /* CMP0 output */
# define SIM_SOPT4_FTM2CH0SRC_CMP1 (2 << SIM_SOPT4_FTM2CH0SRC_SHIFT) /* CMP1 output */
#endif
/* Bits 22-23: Reserved */
#if defined(KINETIS_SIM_HAS_SOPT4_FTM2CH1SRC)
#define SIM_SOPT4_FTM2CH1SRC (1 << 22) /* Bit 22: FTM2 channel 1 input capture source select */
/* Bit 23: Reserved */
#endif
#define SIM_SOPT4_FTM0CLKSEL (1 << 24) /* Bit 24: FlexTimer 0 External Clock Pin Select */
#define SIM_SOPT4_FTM1CLKSEL (1 << 25) /* Bit 25: FTM1 External Clock Pin Select */
#define SIM_SOPT4_FTM2CLKSEL (1 << 26) /* Bit 26: FlexTimer 2 External Clock Pin Select */
/* Bits 27-31: Reserved */
#if defined(KINETIS_SIM_HAS_SOPT4_FTM3TRG1SRC) || defined(KINETIS_SIM_HAS_SOPT4_FTM3TRG0SRC)
# define SIM_SOPT4_FTM3CLKSEL (1 << 27) /* Bit 27: FlexTimer 3 External Clock Pin Select */
#endif
#if defined(KINETIS_SIM_HAS_SOPT4_FTM0TRG0SRC)
/* Bits 27,30-31: Reserved */
# define SIM_SOPT4_FTM0TRG0SRC (1 << 28) /* Bit 28: FlexTimer 0 Hardware Trigger 0 Source Select */
#endif
#if defined(KINETIS_SIM_HAS_SOPT4_FTM0TRG1SRC)
/* Bits 27,30-31: Reserved */
# define SIM_SOPT4_FTM0TRG1SRC (1 << 29) /* Bit 29: FlexTimer 0 Hardware Trigger 1 Source Select */
#endif
#if defined(KINETIS_SIM_HAS_SOPT4_FTM3TRG0SRC)
# define SIM_SOPT4_FTM3TRG0SRC (1 << 30) /* Bit 30: FlexTimer 3 Hardware Trigger 0 Source Select */
#endif
#if defined(KINETIS_SIM_HAS_SOPT4_FTM3TRG1SRC)
# define SIM_SOPT4_FTM3TRG1SRC (1 << 31) /* Bit 31: FlexTimer 3 Hardware Trigger 1 Source Select */
#endif
/* System Options Register 5 */
#if defined(KINETIS_SIM_HAS_SOPT5_UART0TXSRC)
# define SIM_SOPT5_UART0TXSRC_SHIFT (0) /* Bits 0-1: UART 0 transmit data source select */
# define SIM_SOPT5_UART0TXSRC_MASK (3 << SIM_SOPT5_UART0TXSRC_SHIFT)
# define SIM_SOPT5_UART0TXSRC_TX (0 << SIM_SOPT5_UART0TXSRC_SHIFT) /* UART0_TX pin */
# define SIM_SOPT5_UART0TXSRC_FTM1 (1 << SIM_SOPT5_UART0TXSRC_SHIFT) /* UART0_TX modulated with FTM1 ch0 output */
# define SIM_SOPT5_UART0TXSRC_FTM2 (2 << SIM_SOPT5_UART0TXSRC_SHIFT) /* UART0_TX modulated with FTM2 ch0 output */
#endif
#if defined(KINETIS_SIM_HAS_SOPT5_UART0RXSRC)
# define SIM_SOPT5_UART0RXSRC_SHIFT (2) /* Bits 2-3: UART 0 receive data source select */
# define SIM_SOPT5_UART0RXSRC_MASK (3 << SIM_SOPT5_UART0RXSRC_SHIFT)
# define SIM_SOPT5_UART0RXSRC_RX (0 << SIM_SOPT5_UART0RXSRC_SHIFT) /* UART0_RX pin */
# define SIM_SOPT5_UART0RXSRC_CMP0 (1 << SIM_SOPT5_UART0RXSRC_SHIFT) /* CMP0 */
# define SIM_SOPT5_UART0RXSRC_CMP1 (2 << SIM_SOPT5_UART0RXSRC_SHIFT) /* CMP1 */
#endif
#if defined(KINETIS_SIM_HAS_SOPT5_UART1TXSRC)
# define SIM_SOPT5_UART1TXSRC_SHIFT (4) /* Bits 4-5: UART 1 transmit data source select */
# define SIM_SOPT5_UART1TXSRC_MASK (3 << SIM_SOPT5_UART1TXSRC_SHIFT)
# define SIM_SOPT5_UART1TXSRC_TX (0 << SIM_SOPT5_UART1TXSRC_SHIFT) /* UART1_TX pin */
# define SIM_SOPT5_UART1TXSRC_FTM1 (1 << SIM_SOPT5_UART1TXSRC_SHIFT) /* UART1_TX modulated with FTM1 ch0 output */
# define SIM_SOPT5_UART1TXSRC_FTM2 (2 << SIM_SOPT5_UART1TXSRC_SHIFT) /* UART1_TX modulated with FTM2 ch0 output */
#endif
#if defined(KINETIS_SIM_HAS_SOPT5_UART1RXSRC)
# define SIM_SOPT5_UART1RXSRC_SHIFT (6) /* Bits 6-7: UART 1 receive data source select */
# define SIM_SOPT5_UART1RXSRC_MASK (3 << SIM_SOPT5_UART1RXSRC_SHIFT)
# define SIM_SOPT5_UART1RXSRC_RX (0 << SIM_SOPT5_UART1RXSRC_SHIFT) /* UART1_RX pin */
# define SIM_SOPT5_UART1RXSRC_CMP0 (1 << SIM_SOPT5_UART1RXSRC_SHIFT) /* CMP0 */
# define SIM_SOPT5_UART1RXSRC_CMP1 (2 << SIM_SOPT5_UART1RXSRC_SHIFT) /* CMP1 */
#endif
/* Bits 8-31: Reserved */
#if defined(KINETIS_SIM_HAS_SOPT5_LPUART0TXSRC)
/* Bits 8-15, 18-31: Reserved */
# define SIM_SOPT5_LPUART0TXSRC_SHIFT (16) /* Bit 16: LPUART0 transmit data source select */
# define SIM_SOPT5_LPUART0TXSRC_MASK (3 << SIM_SOPT5_LPUART0TXSRC_SHIFT)
# define SIM_SOPT5_LPUART0TXSRC_TX (0 << SIM_SOPT5_LPUART0TXSRC_SHIFT) /* LPUART0_TX pin */
# define SIM_SOPT5_LPUART0TXSRC_TXTMP1CH0 (1 << SIM_SOPT5_LPUART0TXSRC_SHIFT) /* LPUART0_TX pin modulated with TPM1 channel 0 output */
# define SIM_SOPT5_LPUART0TXSRC_TXTMP2CH0 (2 << SIM_SOPT5_LPUART0TXSRC_SHIFT) /* LPUART0_TX pin modulated with TPM2 channel 0 output */
#endif
/* Bits 8-15, 18-31: Reserved */
#if defined(KINETIS_SIM_HAS_SOPT5_LPUART0RXSRC)
/* Bits 8-15, 20-31: Reserved */
# define SIM_SOPT5_LPUART0RXSRC_SHIFT (18) /* Bit 18: LPUART0 receive data source select */
# define SIM_SOPT5_LPUART0RXSRC_MASK (3 << SIM_SOPT5_LPUART0RXSRC_SHIFT)
# define SIM_SOPT5_LPUART0RXSRC_TX (0 << SIM_SOPT5_LPUART0RXSRC_SHIFT) /* LPUART0_RX pin */
# define SIM_SOPT5_LPUART0RXSRC_TXTMP1CH0 (1 << SIM_SOPT5_LPUART0RXSRC_SHIFT) /* CMP0 output */
# define SIM_SOPT5_LPUART0RXSRC_TXTMP2CH0 (2 << SIM_SOPT5_LPUART0RXSRC_SHIFT) /* CMP1 output */
#endif
#if defined(KINETIS_SIM_HAS_SOPT5_LPUART1TXSRC)
/* Bits 8-15,
* 18-31:
* Reserved
*/
# define SIM_SOPT5_LPUART1TXSRC_SHIFT (16) /* Bit 16: LPUART1 transmit data source select */
# define SIM_SOPT5_LPUART1TXSRC_MASK (3 << SIM_SOPT5_LPUART1TXSRC_SHIFT)
# define SIM_SOPT5_LPUART1TXSRC_TX (0 << SIM_SOPT5_LPUART1TXSRC_SHIFT) /* LPUART1_TX pin */
# define SIM_SOPT5_LPUART1TXSRC_TXTMP1CH0 (1 << SIM_SOPT5_LPUART1TXSRC_SHIFT) /* LPUART1_TX pin modulated with TPM1 channel 0 output */
# define SIM_SOPT5_LPUART1TXSRC_TXTMP2CH0 (2 << SIM_SOPT5_LPUART1TXSRC_SHIFT) /* LPUART1_TX pin modulated with TPM2 channel 0 output */
#endif
/* Bits 8-15, 18-31: Reserved */
#if defined(KINETIS_SIM_HAS_SOPT5_LPUART1RXSRC)
/* Bits 8-15, 20-31: Reserved */
# define SIM_SOPT5_LPUART1RXSRC_SHIFT (18) /* Bit 18: LPUART1 receive data source select */
# define SIM_SOPT5_LPUART1RXSRC_MASK (3 << SIM_SOPT5_LPUART1RXSRC_SHIFT)
# define SIM_SOPT5_LPUART1RXSRC_TX (0 << SIM_SOPT5_LPUART1RXSRC_SHIFT) /* LPUART1_RX pin */
# define SIM_SOPT5_LPUART1RXSRC_TXTMP1CH0 (1 << SIM_SOPT5_LPUART1RXSRC_SHIFT) /* CMP0 output */
# define SIM_SOPT5_LPUART1RXSRC_TXTMP2CH0 (2 << SIM_SOPT5_LPUART1RXSRC_SHIFT) /* CMP1 output */
#endif
/* System Options Register 6 */
#if defined(KINETIS_SIM_HAS_SOPT6)
/* Bits 0-23:
* Reserved
*/
# if defined(KINETIS_SIM_HAS_SOPT6_MCC)
/* Bits 16-23:
* Reserved
*/
# define SIM_SOPT6_MCC_SHIFT (0) /* Bits 0-15: NFC hold cycle in case FlexBus request while NFC is granted */
# define SIM_SOPT6_MCC_MASK (0xffff << SIM_SOPT6_MCC_SHIFT)
# define SIM_SOPT6_MCC(n) (((n) & 0xffff) << SIM_SOPT6_MCC_SHIFT)
# endif
/* Bits 16-23: Reserved */
# if defined(KINETIS_SIM_HAS_SOPT6_PCR)
/* Bits 20-23: Reserved */
# define SIM_SOPT6_PCR_SHIFT (16) /* Bits 16-19: FlexBus hold cycles before FlexBus can release bus to NFC or to IDLE */
# define SIM_SOPT6_PCR_MASK (7 << SIM_SOPT6_PCR_SHIFT)
# define SIM_SOPT6_PCR(n) (((n) & 7) << SIM_SOPT6_PCR_SHIFT)
# endif
# if defined(KINETIS_SIM_HAS_SOPT6_RSTFLTSEL)
# define SIM_SOPT6_RSTFLTSEL_SHIFT (24) /* Bits 24-28: Reset pin filter select */
# define SIM_SOPT6_RSTFLTSEL_MASK (31 << SIM_SOPT6_RSTFLTSEL_SHIFT)
# define SIM_SOPT6_RSTFLTSEL(n) ((uint32_t)((n)-1) << SIM_SOPT6_RSTFLTSEL_SHIFT) /* n=1..32 */
# endif
# if defined(KINETIS_SIM_HAS_SOPT6_RSTFLTEN)
# define SIM_SOPT6_RSTFLTEN_SHIFT (29) /* Bits 29-31: Reset pin filter enable */
# define SIM_SOPT6_RSTFLTEN_MASK (7 << SIM_SOPT6_RSTFLTEN_SHIFT)
# define SIM_SOPT6_RSTFLTEN_DISABLED (0 << SIM_SOPT6_RSTFLTEN_SHIFT) /* All filtering disabled */
# define SIM_SOPT6_RSTFLTEN_BUSCLK1 (1 << SIM_SOPT6_RSTFLTEN_SHIFT) /* Bus clock filter enabled (normal); LPO clock filter enabled (stop) */
# define SIM_SOPT6_RSTFLTEN_LPO1 (2 << SIM_SOPT6_RSTFLTEN_SHIFT) /* LPO clock filter enabled */
# define SIM_SOPT6_RSTFLTEN_BUSCLK2 (3 << SIM_SOPT6_RSTFLTEN_SHIFT) /* Bus clock filter enabled (normal); All filtering disabled (stop) */
# define SIM_SOPT6_RSTFLTEN_LPO2 (4 << SIM_SOPT6_RSTFLTEN_SHIFT) /* PO clock filter enabled (normal); All filtering disabled (stop) */
# endif
#endif
/* System Options Register 7 */
#if defined(KINETIS_SIM_HAS_SOPT7_ADC0TRGSEL)
# define SIM_SOPT7_ADC0TRGSEL_SHIFT (0) /* Bits 0-3: ADC0 trigger select */
# define SIM_SOPT7_ADC0TRGSEL_MASK (15 << SIM_SOPT7_ADC0TRGSEL_SHIFT)
# define SIM_SOPT7_ADC0TRGSEL_PDB (0 << SIM_SOPT7_ADC0TRGSEL_SHIFT) /* PDB external trigger (PDB0_EXTRG) */
# define SIM_SOPT7_ADC0TRGSEL_CMP0 (1 << SIM_SOPT7_ADC0TRGSEL_SHIFT) /* High speed comparator 0 output */
# define SIM_SOPT7_ADC0TRGSEL_CMP1 (2 << SIM_SOPT7_ADC0TRGSEL_SHIFT) /* High speed comparator 1 output */
# define SIM_SOPT7_ADC0TRGSEL_CMP2 (3 << SIM_SOPT7_ADC0TRGSEL_SHIFT) /* High speed comparator 2 output */
# define SIM_SOPT7_ADC0TRGSEL_PIT0 (4 << SIM_SOPT7_ADC0TRGSEL_SHIFT) /* PIT trigger 0 */
# define SIM_SOPT7_ADC0TRGSEL_PIT1 (5 << SIM_SOPT7_ADC0TRGSEL_SHIFT) /* PIT trigger 1 */
# define SIM_SOPT7_ADC0TRGSEL_PIT2 (6 << SIM_SOPT7_ADC0TRGSEL_SHIFT) /* PIT trigger 2 */
# define SIM_SOPT7_ADC0TRGSEL_PIT3 (7 << SIM_SOPT7_ADC0TRGSEL_SHIFT) /* PIT trigger 3 */
# define SIM_SOPT7_ADC0TRGSEL_FTM0 (8 << SIM_SOPT7_ADC0TRGSEL_SHIFT) /* FTM0 trigger */
# define SIM_SOPT7_ADC0TRGSEL_FTM1 (9 << SIM_SOPT7_ADC0TRGSEL_SHIFT) /* FTM1 trigger */
# define SIM_SOPT7_ADC0TRGSEL_FTM2 (10 << SIM_SOPT7_ADC0TRGSEL_SHIFT) /* FTM2 trigger */
# if KINETIS_SIM_HAS_SOPT7_ADC0TRGSEL > 10 && defined(KINETIS_SIM_HAS_SOPT4_FTM3CH0SRC)
# define SIM_SOPT7_ADC0TRGSEL_FTM3 (11 << SIM_SOPT7_ADC0TRGSEL_SHIFT) /* FTM3 trigger */
# endif
# if KINETIS_SIM_HAS_SOPT7_ADC0TRGSEL > 11
# define SIM_SOPT7_ADC0TRGSEL_ALARM (12 << SIM_SOPT7_ADC0TRGSEL_SHIFT) /* RTC alarm */
# endif
# if KINETIS_SIM_HAS_SOPT7_ADC0TRGSEL > 12
# define SIM_SOPT7_ADC0TRGSEL_SECS (13 << SIM_SOPT7_ADC0TRGSEL_SHIFT) /* RTC seconds */
# endif
# if KINETIS_SIM_HAS_SOPT7_ADC0TRGSEL > 13
# define SIM_SOPT7_ADC0TRGSEL_LPTMR (14 << SIM_SOPT7_ADC0TRGSEL_SHIFT) /* Low-power timer trigger */
# endif
# if KINETIS_SIM_HAS_SOPT7_ADC0TRGSEL > 14
# define SIM_SOPT7_ADC0TRGSEL_TPM1CH0 (15 << SIM_SOPT7_ADC0TRGSEL_SHIFT) /* TPM1 channel 0 (A pretrigger) and channel 1 (B pretrigger) */
# endif
#endif
#if defined(KINETIS_SIM_HAS_SOPT7_ADC0PRETRGSEL)
# define SIM_SOPT7_ADC0PRETRGSEL (1 << 4) /* Bit 4: ADC0 pretrigger select */
#endif
/* Bits 5-6: Reserved */
#if defined(KINETIS_SIM_SOPT7_ADC0ALTTRGEN)
# define SIM_SOPT7_ADC0ALTTRGEN (1 << 7) /* Bit 7: ADC0 alternate trigger enable */
#endif
#if defined(KINETIS_SIM_HAS_SOPT7_ADC1TRGSEL)
# define SIM_SOPT7_ADC1TRGSEL_SHIFT (8) /* Bits 8-11: ADC1 trigger select */
# define SIM_SOPT7_ADC1TRGSEL_MASK (15 << SIM_SOPT7_ADC1TRGSEL_SHIFT)
# define SIM_SOPT7_ADC1TRGSEL_PDB (0 << SIM_SOPT7_ADC1TRGSEL_SHIFT) /* PDB external trigger (PDB0_EXTRG) */
# define SIM_SOPT7_ADC1TRGSEL_CMP0 (1 << SIM_SOPT7_ADC1TRGSEL_SHIFT) /* High speed comparator 0 output */
# define SIM_SOPT7_ADC1TRGSEL_CMP1 (2 << SIM_SOPT7_ADC1TRGSEL_SHIFT) /* High speed comparator 1 output */
# define SIM_SOPT7_ADC1TRGSEL_CMP2 (3 << SIM_SOPT7_ADC1TRGSEL_SHIFT) /* High speed comparator 2 output */
# define SIM_SOPT7_ADC1TRGSEL_PIT0 (4 << SIM_SOPT7_ADC1TRGSEL_SHIFT) /* PIT trigger 0 */
# define SIM_SOPT7_ADC1TRGSEL_PIT1 (5 << SIM_SOPT7_ADC1TRGSEL_SHIFT) /* PIT trigger 1 */
# define SIM_SOPT7_ADC1TRGSEL_PIT2 (6 << SIM_SOPT7_ADC1TRGSEL_SHIFT) /* PIT trigger 2 */
# define SIM_SOPT7_ADC1TRGSEL_PIT3 (7 << SIM_SOPT7_ADC1TRGSEL_SHIFT) /* PIT trigger 3 */
# define SIM_SOPT7_ADC1TRGSEL_FTM0 (8 << SIM_SOPT7_ADC1TRGSEL_SHIFT) /* FTM0 trigger */
# define SIM_SOPT7_ADC1TRGSEL_FTM1 (9 << SIM_SOPT7_ADC1TRGSEL_SHIFT) /* FTM1 trigger */
# define SIM_SOPT7_ADC1TRGSEL_FTM2 (10 << SIM_SOPT7_ADC1TRGSEL_SHIFT) /* FTM2 trigger */
# define SIM_SOPT7_ADC1TRGSEL_ALARM (12 << SIM_SOPT7_ADC1TRGSEL_SHIFT) /* RTC alarm */
# if KINETIS_SIM_HAS_SOPT7_ADC1TRGSEL > 10 && defined(KINETIS_SIM_HAS_SOPT4_FTM3CH0SRC)
# define SIM_SOPT7_ADC1TRGSEL_FTM3 (11 << SIM_SOPT7_ADC1TRGSEL_SHIFT) /* FTM3 trigger */
# endif
# if KINETIS_SIM_HAS_SOPT7_ADC1TRGSEL > 11
# define SIM_SOPT7_ADC1TRGSEL_ALARM (12 << SIM_SOPT7_ADC1TRGSEL_SHIFT) /* RTC alarm */
# endif
# if KINETIS_SIM_HAS_SOPT7_ADC1TRGSEL > 12
# define SIM_SOPT7_ADC1TRGSEL_SECS (13 << SIM_SOPT7_ADC1TRGSEL_SHIFT) /* RTC seconds */
# endif
# if KINETIS_SIM_HAS_SOPT7_ADC1TRGSEL > 13
# define SIM_SOPT7_ADC1TRGSEL_LPTMR (14 << SIM_SOPT7_ADC1TRGSEL_SHIFT) /* Low-power timer trigger */
# endif
# if KINETIS_SIM_HAS_SOPT7_ADC1TRGSEL > 14
# define SIM_SOPT7_ADC1TRGSEL_TPM2CH0 (15 << SIM_SOPT7_ADC1TRGSEL_SHIFT) /* TPM2 channel 0 (A pretrigger) and channel 1 (B pretrigger) */
# endif
#endif
#if defined(KINETIS_SIM_HAS_SOPT7_ADC1PRETRGSEL)
# define SIM_SOPT7_ADC1PRETRGSEL (1 << 12) /* Bit 12: ADC1 pre-trigger select */
#endif
/* Bits 13-14: Reserved */
#if defined(KINETIS_SIM_SOPT7_ADC1ALTTRGEN)
# define SIM_SOPT7_ADC1ALTTRGEN (1 << 15) /* Bit 15: ADC1 alternate trigger enable */
#endif
/* Bits 16-31: Reserved */
#if defined(KINETIS_SIM_HAS_SOPT7_ADC2TRGSEL)
# define SIM_SOPT7_ADC2TRGSEL_SHIFT (16) /* Bits 16-19: ADC2 trigger select */
# define SIM_SOPT7_ADC2TRGSEL_MASK (15 << SIM_SOPT7_ADC2TRGSEL_SHIFT)
# define SIM_SOPT7_ADC2TRGSEL_PDB (0 << SIM_SOPT7_ADC2TRGSEL_SHIFT) /* PDB external trigger (PDB0_EXTRG) */
# define SIM_SOPT7_ADC2TRGSEL_CMP0 (1 << SIM_SOPT7_ADC2TRGSEL_SHIFT) /* High speed comparator 0 output */
# define SIM_SOPT7_ADC2TRGSEL_CMP1 (2 << SIM_SOPT7_ADC2TRGSEL_SHIFT) /* High speed comparator 1 output */
# define SIM_SOPT7_ADC2TRGSEL_CMP2 (3 << SIM_SOPT7_ADC2TRGSEL_SHIFT) /* High speed comparator 2 output */
# define SIM_SOPT7_ADC2TRGSEL_PIT0 (4 << SIM_SOPT7_ADC2TRGSEL_SHIFT) /* PIT trigger 0 */
# define SIM_SOPT7_ADC2TRGSEL_PIT1 (5 << SIM_SOPT7_ADC2TRGSEL_SHIFT) /* PIT trigger 1 */
# define SIM_SOPT7_ADC2TRGSEL_PIT2 (6 << SIM_SOPT7_ADC2TRGSEL_SHIFT) /* PIT trigger 2 */
# define SIM_SOPT7_ADC2TRGSEL_PIT3 (7 << SIM_SOPT7_ADC2TRGSEL_SHIFT) /* PIT trigger 3 */
# define SIM_SOPT7_ADC2TRGSEL_FTM0 (8 << SIM_SOPT7_ADC2TRGSEL_SHIFT) /* FTM0 trigger */
# define SIM_SOPT7_ADC2TRGSEL_FTM1 (9 << SIM_SOPT7_ADC2TRGSEL_SHIFT) /* FTM1 trigger */
# define SIM_SOPT7_ADC2TRGSEL_FTM2 (10 << SIM_SOPT7_ADC2TRGSEL_SHIFT) /* FTM2 trigger */
# if KINETIS_SIM_HAS_SOPT7_ADC2TRGSEL > 10 && defined(KINETIS_SIM_HAS_SOPT4_FTM3CH0SRC)
# define SIM_SOPT7_ADC2TRGSEL_FTM3 (11 << SIM_SOPT7_ADC2TRGSEL_SHIFT) /* FTM3 trigger */
# endif
# if KINETIS_SIM_HAS_SOPT7_ADC2TRGSEL > 11
# define SIM_SOPT7_ADC2TRGSEL_ALARM (12 << SIM_SOPT7_ADC2TRGSEL_SHIFT) /* RTC alarm */
# endif
# if KINETIS_SIM_HAS_SOPT7_ADC2TRGSEL > 12
# define SIM_SOPT7_ADC2TRGSEL_SECS (13 << SIM_SOPT7_ADC2TRGSEL_SHIFT) /* RTC seconds */
# endif
# if KINETIS_SIM_HAS_SOPT7_ADC2TRGSEL > 13
# define SIM_SOPT7_ADC2TRGSEL_LPTMR (14 << SIM_SOPT7_ADC2TRGSEL_SHIFT) /* Low-power timer trigger */
# endif
# if KINETIS_SIM_HAS_SOPT7_ADC2TRGSEL > 14
# define SIM_SOPT7_ADC2TRGSEL_CMP3 (15 << SIM_SOPT7_ADC2TRGSEL_SHIFT) /* High speed comparator 3 asynchronous interrupt */
# endif
#endif
#if defined(KINETIS_SIM_HAS_SOPT7_ADC2PRETRGSEL)
# define SIM_SOPT7_ADC2PRETRGSEL (1 << 20) /* Bit 20: ADC2 pretrigger select */
#endif
/* Bits 21-22: Reserved */
#if defined(KINETIS_SIM_SOPT7_ADC2ALTTRGEN)
# define SIM_SOPT7_ADC2ALTTRGEN (1 << 23) /* Bit 23: ADC2 alternate trigger enable */
#endif
/* Bits 23-27: Reserved */
#if defined(KINETIS_SIM_HAS_SOPT7_ADC3TRGSEL)
# define SIM_SOPT7_ADC3TRGSEL_SHIFT (24) /* Bits 24-27: ADC3 trigger select */
# define SIM_SOPT7_ADC3TRGSEL_MASK (15 << SIM_SOPT7_ADC3TRGSEL_SHIFT)
# define SIM_SOPT7_ADC3TRGSEL_PDB (0 << SIM_SOPT7_ADC3TRGSEL_SHIFT) /* PDB external trigger (PDB0_EXTRG) */
# define SIM_SOPT7_ADC3TRGSEL_CMP0 (1 << SIM_SOPT7_ADC3TRGSEL_SHIFT) /* High speed comparator 0 output */
# define SIM_SOPT7_ADC3TRGSEL_CMP1 (2 << SIM_SOPT7_ADC3TRGSEL_SHIFT) /* High speed comparator 1 output */
# define SIM_SOPT7_ADC3TRGSEL_CMP2 (3 << SIM_SOPT7_ADC3TRGSEL_SHIFT) /* High speed comparator 2 output */
# define SIM_SOPT7_ADC3TRGSEL_PIT0 (4 << SIM_SOPT7_ADC3TRGSEL_SHIFT) /* PIT trigger 0 */
# define SIM_SOPT7_ADC3TRGSEL_PIT1 (5 << SIM_SOPT7_ADC3TRGSEL_SHIFT) /* PIT trigger 1 */
# define SIM_SOPT7_ADC3TRGSEL_PIT2 (6 << SIM_SOPT7_ADC3TRGSEL_SHIFT) /* PIT trigger 2 */
# define SIM_SOPT7_ADC3TRGSEL_PIT3 (7 << SIM_SOPT7_ADC3TRGSEL_SHIFT) /* PIT trigger 3 */
# define SIM_SOPT7_ADC3TRGSEL_FTM0 (8 << SIM_SOPT7_ADC3TRGSEL_SHIFT) /* FTM0 trigger */
# define SIM_SOPT7_ADC3TRGSEL_FTM1 (9 << SIM_SOPT7_ADC3TRGSEL_SHIFT) /* FTM1 trigger */
# define SIM_SOPT7_ADC3TRGSEL_FTM2 (10 << SIM_SOPT7_ADC3TRGSEL_SHIFT) /* FTM2 trigger */
# if KINETIS_SIM_HAS_SOPT7_ADC3TRGSEL > 10 && defined(KINETIS_SIM_HAS_SOPT4_FTM3CH0SRC)
# define SIM_SOPT7_ADC3TRGSEL_FTM3 (11 << SIM_SOPT7_ADC3TRGSEL_SHIFT) /* FTM3 trigger */
# endif
# if KINETIS_SIM_HAS_SOPT7_ADC3TRGSEL > 11
# define SIM_SOPT7_ADC3TRGSEL_ALARM (12 << SIM_SOPT7_ADC3TRGSEL_SHIFT) /* RTC alarm */
# endif
# if KINETIS_SIM_HAS_SOPT7_ADC3TRGSEL > 12
# define SIM_SOPT7_ADC3TRGSEL_SECS (13 << SIM_SOPT7_ADC3TRGSEL_SHIFT) /* RTC seconds */
# endif
# if KINETIS_SIM_HAS_SOPT7_ADC3TRGSEL > 13
# define SIM_SOPT7_ADC3TRGSEL_LPTMR (14 << SIM_SOPT7_ADC3TRGSEL_SHIFT) /* Low-power timer trigger */
# endif
# if KINETIS_SIM_HAS_SOPT7_ADC3TRGSEL > 14
# define SIM_SOPT7_ADC3TRGSEL_CMP3 (15 << SIM_SOPT7_ADC3TRGSEL_SHIFT) /* High speed comparator 3 asynchronous interrupt */
# endif
#endif
#if defined(KINETIS_SIM_HAS_SOPT7_ADC3PRETRGSEL)
# define SIM_SOPT7_ADC3PRETRGSEL (1 << 28) /* Bit 28: ADC3 pretrigger select */
#endif
/* Bits 29-30: Reserved */
#if defined(KINETIS_SIM_SOPT7_ADC3ALTTRGEN)
# define SIM_SOPT7_ADC3ALTTRGEN (1 << 31) /* Bit 31: ADC3 alternate trigger enable */
#endif
/* System Options Register 8 */
#if defined(KINETIS_SIM_HAS_SOPT8)
# if defined(KINETIS_SIM_HAS_SOPT8_FTM0SYNCBIT)
# define SIM_SOPT8_FTM0SYNCBIT (1 << 0) /* Bit 0: FTM0 Hardware Trigger 0 Software Synchronization */
# endif
# if defined(KINETIS_SIM_HAS_SOPT8_FTM1SYNCBIT)
# define SIM_SOPT8_FTM1SYNCBIT (1 << 1) /* Bit 1: FTM1 Hardware Trigger 0 Software Synchronization */
# endif
# if defined(KINETIS_SIM_HAS_SOPT8_FTM2SYNCBIT)
# define SIM_SOPT8_FTM2SYNCBIT (1 << 2) /* Bit 2: FTM2 Hardware Trigger 0 Software Synchronization */
# endif
# if defined(KINETIS_SIM_HAS_SOPT8_FTM3SYNCBIT)
# define SIM_SOPT8_FTM3SYNCBIT (1 << 3) /* Bit 3: FTM3 Hardware Trigger 0 Software Synchronization */
# endif
/* Bits 4-15: Reserved */
# if defined(KINETIS_SIM_HAS_SOPT8_FTM0OCH0SRC)
# define SIM_SOPT8_FTM0OCH0SRC (1 << 16) /* Bit 16: FTM0 channel 0 output source */
# endif
# if defined(KINETIS_SIM_HAS_SOPT8_FTM0OCH1SRC)
# define SIM_SOPT8_FTM0OCH1SRC (1 << 17) /* Bit 17: FTM0 channel 1 output source */
# endif
# if defined(KINETIS_SIM_HAS_SOPT8_FTM0OCH2SRC)
# define SIM_SOPT8_FTM0OCH2SRC (1 << 18) /* Bit 18: FTM0 channel 2 output source */
# endif
# if defined(KINETIS_SIM_HAS_SOPT8_FTM0OCH3SRC)
# define SIM_SOPT8_FTM0OCH3SRC (1 << 19) /* Bit 19: FTM0 channel 3 output source */
# endif
# if defined(KINETIS_SIM_HAS_SOPT8_FTM0OCH4SRC)
# define SIM_SOPT8_FTM0OCH4SRC (1 << 20) /* Bit 20: FTM0 channel 4 output source */
# endif
# if defined(KINETIS_SIM_HAS_SOPT8_FTM0OCH5SRC)
# define SIM_SOPT8_FTM0OCH5SRC (1 << 21) /* Bit 21: FTM0 channel 5 output source */
# endif
# if defined(KINETIS_SIM_HAS_SOPT8_FTM0OCH6SRC)
# define SIM_SOPT8_FTM0OCH6SRC (1 << 22) /* Bit 22: FTM0 channel 6 output source */
# endif
# if defined(KINETIS_SIM_HAS_SOPT8_FTM0OCH7SRC)
# define SIM_SOPT8_FTM0OCH7SRC (1 << 23) /* Bit 23: FTM0 channel 7 output source */
# endif
# if defined(KINETIS_SIM_HAS_SOPT8_FTM3OCH0SRC)
# define SIM_SOPT8_FTM3OCH0SRC (1 << 24) /* Bit 24: FTM3 channel 0 output source */
# endif
# if defined(KINETIS_SIM_HAS_SOPT8_FTM3OCH1SRC)
# define SIM_SOPT8_FTM3OCH1SRC (1 << 25) /* Bit 25: FTM3 channel 1 output source */
# endif
# if defined(KINETIS_SIM_HAS_SOPT8_FTM3OCH2SRC)
# define SIM_SOPT8_FTM3OCH2SRC (1 << 26) /* Bit 26: FTM3 channel 2 output source */
# endif
# if defined(KINETIS_SIM_HAS_SOPT8_FTM3OCH3SRC)
# define SIM_SOPT8_FTM3OCH3SRC (1 << 27) /* Bit 27: FTM3 channel 3 output source */
# endif
# if defined(KINETIS_SIM_HAS_SOPT8_FTM3OCH4SRC)
# define SIM_SOPT8_FTM3OCH4SRC (1 << 28) /* Bit 28: FTM3 channel 4 output source */
# endif
# if defined(KINETIS_SIM_HAS_SOPT8_FTM3OCH5SRC)
# define SIM_SOPT8_FTM3OCH5SRC (1 << 29) /* Bit 29: FTM3 channel 5 output source */
# endif
# if defined(KINETIS_SIM_HAS_SOPT8_FTM3OCH6SRC)
# define SIM_SOPT8_FTM3OCH6SRC (1 << 30) /* Bit 30: FTM3 channel 6 output source */
# endif
# if defined(KINETIS_SIM_HAS_SOPT8_FTM3OCH7SRC)
# define SIM_SOPT8_FTM3OCH7SRC (1 << 31) /* Bit 31: FTM3 channel 7 output source */
# endif
#endif
/* System Options Register 9 */
#if defined(KINETIS_SIM_HAS_SOPT9)
/* Bits 0-17:
* Reserved
*/
# if defined(KINETIS_SIM_HAS_SOPT9_TPM1CH0SRC)
# define SIM_SOPT9_TPM1CH0SRC_SHIFT (18) /* Bits 18-19: TPM1 channel 0 input capture source select */
# define SIM_SOPT9_TPM1CH0SRC_MASK (3 << SIM_SOPT9_TPM1CH0SRC_SHIFT)
# define SIM_SOPT9_TPM1CH0SRC_TMP1CH0 (0 << SIM_SOPT9_TPM1CH0SRC_SHIFT)
# define SIM_SOPT9_TPM1CH0SRC_CMP0 (1 << SIM_SOPT9_TPM1CH0SRC_SHIFT)
# define SIM_SOPT9_TPM1CH0SRC_CMP1 (2 << SIM_SOPT9_TPM1CH0SRC_SHIFT)
# endif
# if defined(KINETIS_SIM_HAS_SOPT9_TPM2CH0SRC)
# define SIM_SOPT9_TPM2CH0SRC_SHIFT (20) /* Bits 20-21 TPM2 channel 0 input capture source select */
# define SIM_SOPT9_TPM2CH0SRC_MASK (3 << SIM_SOPT9_TPM2CH0SRC_SHIFT)
# define SIM_SOPT9_TPM2CH0SRC_TMP1CH0 (0 << SIM_SOPT9_TPM2CH0SRC_SHIFT)
# define SIM_SOPT9_TPM2CH0SRC_CMP0 (1 << SIM_SOPT9_TPM2CH0SRC_SHIFT)
# define SIM_SOPT9_TPM2CH0SRC_CMP1 (2 << SIM_SOPT9_TPM2CH0SRC_SHIFT)
# endif
/* Bits 22-24: Reserved */
# if defined(KINETIS_SIM_HAS_SOPT9_TPM1CLKSEL)
# define SIM_SOPT9_TPM1CLKSEL (1 << 25) /* Bit 25: TPM1 External Clock Pin Select */
# endif
# if defined(KINETIS_SIM_HAS_SOPT9_TPM2CLKSEL)
# define SIM_SOPT9_TPM2CLKSEL (1 << 26) /* Bit 26: TPM2 External Clock Pin Select */
# endif
/* Bits 27-31: Reserved */
#endif
/* System Device Identification Register */
#define SIM_SDID_PINID_SHIFT (0) /* Bits 0-3: Pincount identification */
#define SIM_SDID_PINID_MASK (15 << SIM_SDID_PINID_SHIFT)
# define SIM_SDID_PINID_32PIN (2 << SIM_SDID_PINID_SHIFT) /* 32-pin */
# define SIM_SDID_PINID_48PIN (4 << SIM_SDID_PINID_SHIFT) /* 48-pin */
# define SIM_SDID_PINID_64PIN (5 << SIM_SDID_PINID_SHIFT) /* 64-pin */
# define SIM_SDID_PINID_80PIN (6 << SIM_SDID_PINID_SHIFT) /* 80-pin */
# define SIM_SDID_PINID_81PIN (7 << SIM_SDID_PINID_SHIFT) /* 81-pin */
# define SIM_SDID_PINID_100PIN (8 << SIM_SDID_PINID_SHIFT) /* 100-pin */
# define SIM_SDID_PINID_121PIN (9 << SIM_SDID_PINID_SHIFT) /* 121-pin */
# define SIM_SDID_PINID_144PIN (10 << SIM_SDID_PINID_SHIFT) /* 144-pin */
# define SIM_SDID_PINID_196PIN (12 << SIM_SDID_PINID_SHIFT) /* 196-pin */
# define SIM_SDID_PINID_256PIN (14 << SIM_SDID_PINID_SHIFT) /* 256-pin */
#if defined(KINETIS_SIM_HAS_SDID_FAMID)
# if !defined(KINETIS_SIM_HAS_SDID_FAMILYID)
# define SIM_SDID_FAMID_SHIFT (4) /* Bits 4-6: Kinetis family identification */
# define SIM_SDID_FAMID_MASK (7 << SIM_SDID_FAMID_SHIFT)
# define SIM_SDID_FAMID_K10 (0 << SIM_SDID_FAMID_SHIFT) /* K10 */
# define SIM_SDID_FAMID_K20 (1 << SIM_SDID_FAMID_SHIFT) /* K20 */
# define SIM_SDID_FAMID_K30 (2 << SIM_SDID_FAMID_SHIFT) /* K30 */
# define SIM_SDID_FAMID_K40 (3 << SIM_SDID_FAMID_SHIFT) /* K40 */
# define SIM_SDID_FAMID_K60 (4 << SIM_SDID_FAMID_SHIFT) /* K60 */
# define SIM_SDID_FAMID_K70 (5 << SIM_SDID_FAMID_SHIFT) /* K70 */
# define SIM_SDID_FAMID_K50 (6 << SIM_SDID_FAMID_SHIFT) /* K50 and K52 */
# define SIM_SDID_FAMID_K51 (7 << SIM_SDID_FAMID_SHIFT) /* K51 and K53 */
# else
# define SIM_SDID_FAMID_K1X (0 << SIM_SDID_FAMID_SHIFT) /* K1X */
# define SIM_SDID_FAMID_K2X (1 << SIM_SDID_FAMID_SHIFT) /* K2X */
# define SIM_SDID_FAMID_K3X (2 << SIM_SDID_FAMID_SHIFT) /* K3X */
# define SIM_SDID_FAMID_K4X (3 << SIM_SDID_FAMID_SHIFT) /* K4X */
# define SIM_SDID_FAMID_K6X (4 << SIM_SDID_FAMID_SHIFT) /* K6X */
# define SIM_SDID_FAMID_K7X (5 << SIM_SDID_FAMID_SHIFT) /* K7X */
# endif
#endif
/* Bits 7-11: Reserved */
#if defined(KINETIS_SIM_HAS_SDID_DIEID)
# define SIM_SDID_DIEID_SHIFT (7) /* Bits 7-11: Device Die ID */
# define SIM_SDID_DIEID_MASK (31 < SIM_SDID_DIEID_SHIFT)
#endif
#define SIM_SDID_REVID_SHIFT (12) /* Bits 12-15: Device revision number */
#define SIM_SDID_REVID_MASK (15 << SIM_SDID_REVID_SHIFT)
/* Bits 16-31: Reserved */
#if defined(KINETIS_SIM_HAS_SDID_SRAMSIZE)
# define SIM_SDID_SRAMSIZE_SHIFT (16) /* Bits 16-19: SRAM Size */
# define SIM_SDID_SRAMSIZE_MASK (15 < SIM_SDID_SRAMSIZE_SHIFT)
#endif
#if defined(KINETIS_SIM_HAS_SDID_SERIESID)
# define SIM_SDID_SERIESID_SHIFT (20) /* Bits 20-23: Kinetis Series ID */
# define SIM_SDID_SERIESID_MASK (15 << SIM_SDID_SERIESID_SHIFT)
# define SIM_SDID_SERIESID_K (0 << SIM_SDID_SERIESID_SHIFT) /* Kinetis K series */
# define SIM_SDID_SERIESID_L (1 << SIM_SDID_SERIESID_SHIFT) /* Kinetis L series */
# define SIM_SDID_SERIESID_W (5 << SIM_SDID_SERIESID_SHIFT) /* Kinetis W series */
# define SIM_SDID_SERIESID_V (6 << SIM_SDID_SERIESID_SHIFT) /* Kinetis V series */
#endif
#if defined(KINETIS_SIM_HAS_SDID_SUBFAMID)
# define SIM_SDID_SUBFAMID_SHIFT (24) /* Bits 24-27: Kinetis Sub-Family ID */
# define SIM_SDID_SUBFAMID_MASK (15 << SIM_SDID_SUBFAMID_SHIFT)
# define SIM_SDID_SUBFAMID_KX0 (0 << SIM_SDID_SUBFAMID_SHIFT) /* Kx0 Subfamily */
# define SIM_SDID_SUBFAMID_KX1 (1 << SIM_SDID_SUBFAMID_SHIFT) /* Kx1 Subfamily (tamper detect) */
# define SIM_SDID_SUBFAMID_KX2 (2 << SIM_SDID_SUBFAMID_SHIFT) /* Kx2 Subfamily */
# define SIM_SDID_SUBFAMID_KX3 (3 << SIM_SDID_SUBFAMID_SHIFT) /* Kx3 Subfamily (tamper detect) */
# define SIM_SDID_SUBFAMID_KX4 (4 << SIM_SDID_SUBFAMID_SHIFT) /* Kx4 Subfamily */
# define SIM_SDID_SUBFAMID_KX5 (5 << SIM_SDID_SUBFAMID_SHIFT) /* Kx5 Subfamily (tamper detect) */
# define SIM_SDID_SUBFAMID_KX6 (6 << SIM_SDID_SUBFAMID_SHIFT) /* Kx6 Subfamily */
#endif
#if defined(KINETIS_SIM_HAS_SDID_FAMILYID)
# define SIM_SDID_FAMILYID_SHIFT (28) /* Bits 28-31: Kinetis Family ID */
# define SIM_SDID_FAMILYID_MASK (15 << SIM_SDID_FAMILYID_SHIFT)
# define SIM_SDID_FAMILYID_K0X (0 << SIM_SDID_FAMILYID_SHIFT) /* K0x Family */
# define SIM_SDID_FAMILYID_K1X (1 << SIM_SDID_FAMILYID_SHIFT) /* K1x Family */
# define SIM_SDID_FAMILYID_K2X (2 << SIM_SDID_FAMILYID_SHIFT) /* K2x Family */
# define SIM_SDID_FAMILYID_K3X (3 << SIM_SDID_FAMILYID_SHIFT) /* K3x Family */
# define SIM_SDID_FAMILYID_K4X (4 << SIM_SDID_FAMILYID_SHIFT) /* K4x Family */
# define SIM_SDID_FAMILYID_K6X (6 << SIM_SDID_FAMILYID_SHIFT) /* K6x Family */
# define SIM_SDID_FAMILYID_K7X (7 << SIM_SDID_FAMILYID_SHIFT) /* K7x Family */
# define SIM_SDID_FAMILYID_K8X (8 << SIM_SDID_FAMILYID_SHIFT) /* K8x Family */
#endif
/* System Clock Gating Control Register 1 */
#if defined(KINETIS_SIM_HAS_SCGC1)
/* Bits 0-9:
* Reserved
*/
# if defined(KINETIS_SIM_HAS_SCGC1_OSC1)
/* Bits 0-4:
* Reserved
*/
# define SIM_SCGC1_OSC1 (1 << 5) /* OSC1 clock gate control */
# endif
/* Bits 6-9: Reserved */
# if defined(KINETIS_SIM_HAS_SCGC1_I2C2)
# define SIM_SCGC1_I2C2 (1 << 6) /* Bit 6: I2C2 Clock Gate Control */
# endif
/* Bits 7-9: Reserved */
# if defined(KINETIS_SIM_HAS_SCGC1_I2C3)
# define SIM_SCGC1_I2C3 (1 << 7) /* Bit 7: I2C3 Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC1_UART4)
# define SIM_SCGC1_UART4 (1 << 10) /* Bit 10: UART4 Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC1_UART5)
# define SIM_SCGC1_UART5 (1 << 11) /* Bit 11: UART5 Clock Gate Control */
# endif
/* Bits 12-31: Reserved */
#endif
/* System Clock Gating Control Register 2 */
#if defined(KINETIS_SIM_HAS_SCGC2)
# if defined(KINETIS_SIM_HAS_SCGC2_ENET) && defined(KINETIS_NENET) && KINETIS_NENET > 0
# define SIM_SCGC2_ENET (1 << 0) /* Bit 0: ENET Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC2_LPUART0)
# define SIM_SCGC2_LPUART0 (1 << 4) /* Bit 4: LPUART0 Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC2_LPUART1)
# define SIM_SCGC2_LPUART1 (1 << 5) /* Bit 5: LPUART1 Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC2_LPUART2)
# define SIM_SCGC2_LPUART2 (1 << 6) /* Bit 6: LPUART2 Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC2_LPUART3)
# define SIM_SCGC2_LPUART3 (1 << 7) /* Bit 7: LPUART3 Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC2_TPM1)
# define SIM_SCGC2_TPM1 (1 << 9) /* Bit 9: TPM1 Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC2_TPM2)
# define SIM_SCGC2_TPM2 (1 << 10) /* Bit 10: TPM2 Clock Gate Control */
# endif
# define SIM_SCGC2_DAC0 (1 << 12) /* Bit 12: DAC0 Clock Gate Control */
# if defined(KINETIS_SIM_HAS_SCGC2_DAC1)
# define SIM_SCGC2_DAC1 (1 << 13) /* Bit 13: DAC1 Clock Gate Control */
# endif
/* Bits 14-21: Reserved */
# if defined(KINETIS_SIM_HAS_SCGC2_LPUART4)
# define SIM_SCGC2_LPUART4 (1 << 22) /* Bit 22: LPUART4 Clock Gate Control */
# endif
/* Bits 23-25: Reserved */
# if defined(KINETIS_SIM_HAS_SCGC2_QSPI)
# define SIM_SCGC2_QSPI (1 << 26) /* Bit 26: QSPI Clock Gate Control */
# endif
/* Bits 27-30: Reserved */
# if defined(KINETIS_SIM_HAS_SCGC2_FLEXIO)
# define SIM_SCGC2_FLEXIO (1 << 31) /* Bit 31: FlexIO Clock Gate Control */
# endif
#endif
/* System Clock Gating Control Register 3 */
#if defined(KINETIS_SIM_HAS_SCGC3)
# if defined(KINETIS_SIM_HAS_SCGC3_RNGA) && defined(KINETIS_NRNG) && KINETIS_NRNG > 0
# define SIM_SCGC3_RNGA (1 << 0) /* Bit 0: TRNG/RNGA Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC3_USBHS)
# define SIM_SCGC3_USBHS (1 << 1) /* Bit 1: USBHS Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC3_USBHSPHY)
# define SIM_SCGC3_USBHSPHY (1 << 2) /* Bit 2: USBHS PHY Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC3_USBHSDCD)
# define SIM_SCGC3_USBHSDCD (1 << 3) /* Bit 3: USBHS DCD Clock Gate Control */
# endif
/* Bits 5-11: Reserved */
# if defined(KINETIS_SIM_HAS_SCGC3_FLEXCAN1)
# define SIM_SCGC3_FLEXCAN1 (1 << 4) /* Bit 4: FlexCAN1 Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC3_NFC)
# define SIM_SCGC3_FLEXCAN1 (1 << 8) /* Bit 8: NFC Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC3_SPI2)
# define SIM_SCGC3_SPI2 (1 << 12) /* Bit 12: SPI2 Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC3_SPI3)
# define SIM_SCGC3_SPI3 (1 << 13) /* Bit 13: SPI3 Clock Gate Control */
# endif
/* Bit 14: Reserved */
# if defined(KINETIS_SIM_HAS_SCGC3_SAI1)
# define SIM_SCGC3_SAI1 (1 << 15) /* Bit 15: I2S1/SAI1 clock Gate control */
# endif
/* Bit 16: Reserved */
# if defined(KINETIS_SIM_HAS_SCGC3_SDHC)
# define SIM_SCGC3_SDHC (1 << 17) /* Bit 17: SDHC Clock Gate Control */
# endif
/* Bits 18-23: Reserved */
# if defined(KINETIS_SIM_HAS_SCGC3_FTM2)
# define SIM_SCGC3_FTM2 (1 << 24) /* Bit 24: FTM2 Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC3_FTM3) && defined(KINETIS_SIM_HAS_SOPT4_FTM3CH0SRC)
# define SIM_SCGC3_FTM3 (1 << 25) /* Bit 25: RFTM3 Clock Gate Control */
# endif
/* Bit 26: Reserved */
# if defined(KINETIS_SIM_HAS_SCGC3_ADC1)
# define SIM_SCGC3_ADC1 (1 << 27) /* Bit 27: ADC1 Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC3_ADC3)
# define SIM_SCGC3_ADC3 (1 << 28) /* Bit 28: ADC3 Clock Gate Control */
# endif
/* Bit 29: Reserved */
# if defined(KINETIS_SIM_HAS_SCGC3_SLCD) && defined(KINETIS_NSLCD) && KINETIS_NSLCD > 0
# define SIM_SCGC3_SLCD (1 << 30) /* Bit 30: Segment LCD Clock Gate Control */
# endif
/* Bit 31: Reserved */
#endif
/* System Clock Gating Control Register 4 */
/* Bit 0: Reserved */
#define SIM_SCGC4_EWM (1 << 1) /* Bit 1: EWM Clock Gate Control */
#define SIM_SCGC4_CMT (1 << 2) /* Bit 2: CMT Clock Gate Control */
/* Bits 3-5: Reserved */
#define SIM_SCGC4_I2C0 (1 << 6) /* Bit 6: I2C0 Clock Gate Control */
#define SIM_SCGC4_I2C1 (1 << 7) /* Bit 7: I2C1 Clock Gate Control */
/* Bits 8-9: Reserved */
#if defined(KINETIS_SIM_HAS_SCGC4_UART0)
# define SIM_SCGC4_UART0 (1 << 10) /* Bit 10: UART0 Clock Gate Control */
#endif
#if defined(KINETIS_SIM_HAS_SCGC4_UART1)
# define SIM_SCGC4_UART1 (1 << 11) /* Bit 11: UART1 Clock Gate Control */
#endif
#if defined(KINETIS_SIM_HAS_SCGC4_UART2)
# define SIM_SCGC4_UART2 (1 << 12) /* Bit 12: UART2 Clock Gate Control */
#endif
#if defined(KINETIS_SIM_HAS_SCGC4_UART3)
# define SIM_SCGC4_UART3 (1 << 13) /* Bit 13: UART3 Clock Gate Control */
#endif
/* Bits 14-17: Reserved */
#define SIM_SCGC4_USBOTG (1 << 18) /* Bit 18: USB Clock Gate Control */
#define SIM_SCGC4_CMP (1 << 19) /* Bit 19: Comparator Clock Gate Control */
#define SIM_SCGC4_VREF (1 << 20) /* Bit 20: VREF Clock Gate Control */
/* Bits 21-17: Reserved */
#if defined(KINETIS_SIM_HAS_SCGC4_LLWU)
# define SIM_SCGC4_LLWU (1 << 28) /* Bit 28: LLWU Clock Gate Control */
#endif
/* Bits 29-31: Reserved */
/* System Clock Gating Control Register 5 */
#define SIM_SCGC5_LPTMR0 (1 << 0) /* Bit 0: Low Power Timer 0 Clock Gate Control */
#if defined(KINETIS_SIM_HAS_SCGC5_REGFILE)
# define SIM_SCGC5_REGFILE (1 << 1) /* Bit 1: Register File Clock Gate Control */
#endif
/* Bits 2-3: Reserved */
#if defined(KINETIS_SIM_HAS_SCGC5_LPTMR1)
# define SIM_SCGC5_LPTMR1 (1 << 4) /* Bit 4: Low Power Timer 1 Clock Gate Control */
#endif
#if defined(KINETIS_SIM_HAS_SCGC5_TSI)
# define SIM_SCGC5_TSI (1 << 5) /* Bit 5: TSI Clock Gate Control */
#endif
/* Bits 6-8: Reserved */
#define SIM_SCGC5_PORTA (1 << 9) /* Bit 9: Port A Clock Gate Control */
#define SIM_SCGC5_PORTB (1 << 10) /* Bit 10: Port B Clock Gate Control */
#define SIM_SCGC5_PORTC (1 << 11) /* Bit 11: Port C Clock Gate Control */
#define SIM_SCGC5_PORTD (1 << 12) /* Bit 12: Port D Clock Gate Control */
#define SIM_SCGC5_PORTE (1 << 13) /* Bit 13: Port E Clock Gate Control */
#if defined(KINETIS_SIM_HAS_SCGC5_PORTF)
# define SIM_SCGC5_PORTF (1 << 14) /* Bit 14: Port F Clock Gate Control */
#endif
/* Bits 14-31: Reserved */
/* System Clock Gating Control Register 6 */
#if defined(KINETIS_SIM_HAS_SCGC6_FTFL)
# define SIM_SCGC6_FTFL (1 << 0) /* Bit 0: Flash Memory Clock Gate Control */
#endif
#define SIM_SCGC6_DMAMUX0 (1 << 1) /* Bit 1: DMA Mux 0 Clock Gate Control */
/* Bits 2-3: Reserved */
#if defined(KINETIS_SIM_HAS_SCGC6_DMAMUX1)
# define SIM_SCGC6_DMAMUX1 (1 << 2) /* Bit 2: DMA Mux 1 Clock Gate Control */
#endif
#if defined(KINETIS_SIM_HAS_SCGC6_FLEXCAN0)
# define SIM_SCGC6_FLEXCAN0 (1 << 4) /* Bit 4: FlexCAN0 Clock Gate Control */
#endif
/* Bits 5-9: Reserved */
#if defined(KINETIS_SIM_HAS_SCGC6_RNGA)
# define SIM_SCGC6_RNGA (1 << 9) /* Bit 9: SPI0 Clock Gate Control */
#endif
/* Bits 10-11: Reserved */
#define SIM_SCGC6_SPI0 (1 << 12) /* Bit 12: SPI0 Clock Gate Control */
#define SIM_SCGC6_SPI1 (1 << 13) /* Bit 13: SPI1 Clock Gate Control */
/* Bit 14: Reserved */
#define SIM_SCGC6_I2S0 (1 << 15) /* Bit 15: I2S0 Clock Gate Control */
/* Bits 16-17: Reserved */
#define SIM_SCGC6_CRC (1 << 18) /* Bit 18: CRC Clock Gate Control */
/* Bits 19-20: Reserved */
#if defined(KINETIS_SIM_HAS_SCGC6_USBHS)
# define SIM_SCGC6_USBHS (1 << 20) /* Bit 20: USB HS Clock Gate Control */
#endif
#define SIM_SCGC6_USBDCD (1 << 21) /* Bit 21: USB DCD Clock Gate Control */
#define SIM_SCGC6_PDB (1 << 22) /* Bit 22: PDB Clock Gate Control */
#define SIM_SCGC6_PIT (1 << 23) /* Bit 23: PIT Clock Gate Control */
#define SIM_SCGC6_FTM0 (1 << 24) /* Bit 24: FTM0 Clock Gate Control */
#define SIM_SCGC6_FTM1 (1 << 25) /* Bit 25: FTM1 Clock Gate Control */
#if defined(KINETIS_SIM_HAS_SCGC6_FTM2)
# define SIM_SCGC6_FTM2 (1 << 26) /* Bit 26: FTM2 Clock Gate Control */
#endif
#define SIM_SCGC6_ADC0 (1 << 27) /* Bit 27: ADC0 Clock Gate Control */
/* Bit 28: Reserved */
#if defined(KINETIS_SIM_HAS_SCGC6_ADC2)
# define SIM_SCGC6_ADC2 (1 << 28) /* Bit 28: ADC2 Clock Gate Control */
#endif
#define SIM_SCGC6_RTC (1 << 29) /* Bit 29: RTC Clock Gate Control */
/* Bits 30-31: Reserved */
#if defined(KINETIS_SIM_HAS_SCGC6_DAC0)
# define SIM_SCGC6_DAC0 (1 << 31) /* Bit 31: RTC Clock Gate Control */
#endif
/* System Clock Gating Control Register 7 */
#if defined(KINETIS_SIM_HAS_SCGC7)
# if defined(KINETIS_SIM_HAS_SCGC7_FLEXBUS)
# define SIM_SCGC7_FLEXBUS (1 << 0) /* Bit 0: FlexBus Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC7_DMA)
# define SIM_SCGC7_DMA (1 << 1) /* Bit 1: DMA Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC7_MPU)
# define SIM_SCGC7_MPU (1 << 2) /* Bit 2: MPU Clock Gate Control */
# endif
# if defined(KINETIS_SIM_HAS_SCGC7_SDRAMC)
# define SIM_SCGC7_SDRAMC (1 << 3) /* Bit 3: SDRAMC Clock Gate Control */
# endif
/* Bits 4-31: Reserved */
# endif
/* System Clock Divider Register 1 */
#if defined(KINETIS_SIM_HAS_CLKDIV1_OUTDIV5)
/* Bits 0-15:
* Reserved
*/
#endif
#if defined(KINETIS_SIM_HAS_CLKDIV1_OUTDIV4)
# define SIM_CLKDIV1_OUTDIV4_SHIFT (16) /* Bits 16-19: Clock 4 output divider value */
# define SIM_CLKDIV1_OUTDIV4_MASK (15 << SIM_CLKDIV1_OUTDIV4_SHIFT)
# define SIM_CLKDIV1_OUTDIV4(n) ((uint32_t)(((n)-1) & 0xf) << SIM_CLKDIV1_OUTDIV4_SHIFT) /* n=1..16 */
# define SIM_CLKDIV1_OUTDIV4_1 (0 << SIM_CLKDIV1_OUTDIV4_SHIFT) /* Divide by 1 */
# define SIM_CLKDIV1_OUTDIV4_2 (1 << SIM_CLKDIV1_OUTDIV4_SHIFT) /* Divide by 2 */
# define SIM_CLKDIV1_OUTDIV4_3 (2 << SIM_CLKDIV1_OUTDIV4_SHIFT) /* Divide by 3 */
# define SIM_CLKDIV1_OUTDIV4_4 (3 << SIM_CLKDIV1_OUTDIV4_SHIFT) /* Divide by 4 */
# define SIM_CLKDIV1_OUTDIV4_5 (4 << SIM_CLKDIV1_OUTDIV4_SHIFT) /* Divide by 5 */
# define SIM_CLKDIV1_OUTDIV4_6 (5 << SIM_CLKDIV1_OUTDIV4_SHIFT) /* Divide by 6 */
# define SIM_CLKDIV1_OUTDIV4_7 (6 << SIM_CLKDIV1_OUTDIV4_SHIFT) /* Divide by 7 */
# define SIM_CLKDIV1_OUTDIV4_8 (7 << SIM_CLKDIV1_OUTDIV4_SHIFT) /* Divide by 8 */
# define SIM_CLKDIV1_OUTDIV4_9 (8 << SIM_CLKDIV1_OUTDIV4_SHIFT) /* Divide by 9 */
# define SIM_CLKDIV1_OUTDIV4_10 (9 << SIM_CLKDIV1_OUTDIV4_SHIFT) /* Divide by 10 */
# define SIM_CLKDIV1_OUTDIV4_11 (10 << SIM_CLKDIV1_OUTDIV4_SHIFT) /* Divide by 11 */
# define SIM_CLKDIV1_OUTDIV4_12 (11 << SIM_CLKDIV1_OUTDIV4_SHIFT) /* Divide by 12 */
# define SIM_CLKDIV1_OUTDIV4_13 (12 << SIM_CLKDIV1_OUTDIV4_SHIFT) /* Divide by 13 */
# define SIM_CLKDIV1_OUTDIV4_14 (13 << SIM_CLKDIV1_OUTDIV4_SHIFT) /* Divide by 14 */
# define SIM_CLKDIV1_OUTDIV4_15 (14 << SIM_CLKDIV1_OUTDIV4_SHIFT) /* Divide by 15 */
# define SIM_CLKDIV1_OUTDIV4_16 (15 << SIM_CLKDIV1_OUTDIV4_SHIFT) /* Divide by 16 */
#endif
#if defined(KINETIS_SIM_HAS_CLKDIV1_OUTDIV3)
# define SIM_CLKDIV1_OUTDIV3_SHIFT (20) /* Bits 20-23: Clock 3 output divider value */
# define SIM_CLKDIV1_OUTDIV3_MASK (15 << SIM_CLKDIV1_OUTDIV3_SHIFT)
# define SIM_CLKDIV1_OUTDIV3(n) ((uint32_t)(((n)-1) & 0xf) << SIM_CLKDIV1_OUTDIV3_SHIFT) /* n=1..16 */
# define SIM_CLKDIV1_OUTDIV3_1 (0 << SIM_CLKDIV1_OUTDIV3_SHIFT) /* Divide by 1 */
# define SIM_CLKDIV1_OUTDIV3_2 (1 << SIM_CLKDIV1_OUTDIV3_SHIFT) /* Divide by 2 */
# define SIM_CLKDIV1_OUTDIV3_3 (2 << SIM_CLKDIV1_OUTDIV3_SHIFT) /* Divide by 3 */
# define SIM_CLKDIV1_OUTDIV3_4 (3 << SIM_CLKDIV1_OUTDIV3_SHIFT) /* Divide by 4 */
# define SIM_CLKDIV1_OUTDIV3_5 (4 << SIM_CLKDIV1_OUTDIV3_SHIFT) /* Divide by 5 */
# define SIM_CLKDIV1_OUTDIV3_6 (5 << SIM_CLKDIV1_OUTDIV3_SHIFT) /* Divide by 6 */
# define SIM_CLKDIV1_OUTDIV3_7 (6 << SIM_CLKDIV1_OUTDIV3_SHIFT) /* Divide by 7 */
# define SIM_CLKDIV1_OUTDIV3_8 (7 << SIM_CLKDIV1_OUTDIV3_SHIFT) /* Divide by 8 */
# define SIM_CLKDIV1_OUTDIV3_9 (8 << SIM_CLKDIV1_OUTDIV3_SHIFT) /* Divide by 9 */
# define SIM_CLKDIV1_OUTDIV3_10 (9 << SIM_CLKDIV1_OUTDIV3_SHIFT) /* Divide by 10 */
# define SIM_CLKDIV1_OUTDIV3_11 (10 << SIM_CLKDIV1_OUTDIV3_SHIFT) /* Divide by 11 */
# define SIM_CLKDIV1_OUTDIV3_12 (11 << SIM_CLKDIV1_OUTDIV3_SHIFT) /* Divide by 12 */
# define SIM_CLKDIV1_OUTDIV3_13 (12 << SIM_CLKDIV1_OUTDIV3_SHIFT) /* Divide by 13 */
# define SIM_CLKDIV1_OUTDIV3_14 (13 << SIM_CLKDIV1_OUTDIV3_SHIFT) /* Divide by 14 */
# define SIM_CLKDIV1_OUTDIV3_15 (14 << SIM_CLKDIV1_OUTDIV3_SHIFT) /* Divide by 15 */
# define SIM_CLKDIV1_OUTDIV3_16 (15 << SIM_CLKDIV1_OUTDIV3_SHIFT) /* Divide by 16 */
#endif
#if defined(KINETIS_SIM_HAS_CLKDIV1_OUTDIV2)
# define SIM_CLKDIV1_OUTDIV2_SHIFT (24) /* Bits 24-27: Clock 2 output divider value */
# define SIM_CLKDIV1_OUTDIV2_MASK (15 << SIM_CLKDIV1_OUTDIV2_SHIFT)
# define SIM_CLKDIV1_OUTDIV2(n) ((uint32_t)(((n)-1) & 0xf) << SIM_CLKDIV1_OUTDIV2_SHIFT) /* n=1..16 */
# define SIM_CLKDIV1_OUTDIV2_1 (0 << SIM_CLKDIV1_OUTDIV2_SHIFT) /* Divide by 1 */
# define SIM_CLKDIV1_OUTDIV2_2 (1 << SIM_CLKDIV1_OUTDIV2_SHIFT) /* Divide by 2 */
# define SIM_CLKDIV1_OUTDIV2_3 (2 << SIM_CLKDIV1_OUTDIV2_SHIFT) /* Divide by 3 */
# define SIM_CLKDIV1_OUTDIV2_4 (3 << SIM_CLKDIV1_OUTDIV2_SHIFT) /* Divide by 4 */
# define SIM_CLKDIV1_OUTDIV2_5 (4 << SIM_CLKDIV1_OUTDIV2_SHIFT) /* Divide by 5 */
# define SIM_CLKDIV1_OUTDIV2_6 (5 << SIM_CLKDIV1_OUTDIV2_SHIFT) /* Divide by 6 */
# define SIM_CLKDIV1_OUTDIV2_7 (6 << SIM_CLKDIV1_OUTDIV2_SHIFT) /* Divide by 7 */
# define SIM_CLKDIV1_OUTDIV2_8 (7 << SIM_CLKDIV1_OUTDIV2_SHIFT) /* Divide by 8 */
# define SIM_CLKDIV1_OUTDIV2_9 (8 << SIM_CLKDIV1_OUTDIV2_SHIFT) /* Divide by 9 */
# define SIM_CLKDIV1_OUTDIV2_10 (9 << SIM_CLKDIV1_OUTDIV2_SHIFT) /* Divide by 10 */
# define SIM_CLKDIV1_OUTDIV2_11 (10 << SIM_CLKDIV1_OUTDIV2_SHIFT) /* Divide by 11 */
# define SIM_CLKDIV1_OUTDIV2_12 (11 << SIM_CLKDIV1_OUTDIV2_SHIFT) /* Divide by 12 */
# define SIM_CLKDIV1_OUTDIV2_13 (12 << SIM_CLKDIV1_OUTDIV2_SHIFT) /* Divide by 13 */
# define SIM_CLKDIV1_OUTDIV2_14 (13 << SIM_CLKDIV1_OUTDIV2_SHIFT) /* Divide by 14 */
# define SIM_CLKDIV1_OUTDIV2_15 (14 << SIM_CLKDIV1_OUTDIV2_SHIFT) /* Divide by 15 */
# define SIM_CLKDIV1_OUTDIV2_16 (15 << SIM_CLKDIV1_OUTDIV2_SHIFT) /* Divide by 16 */
#endif
#define SIM_CLKDIV1_OUTDIV1_SHIFT (28) /* Bits 28-31: Clock 1 output divider value */
#define SIM_CLKDIV1_OUTDIV1_MASK (15 << SIM_CLKDIV1_OUTDIV1_SHIFT)
# define SIM_CLKDIV1_OUTDIV1(n) ((uint32_t)(((n)-1) & 0xf) << SIM_CLKDIV1_OUTDIV1_SHIFT) /* n=1..16 */
# define SIM_CLKDIV1_OUTDIV1_1 (0 << SIM_CLKDIV1_OUTDIV1_SHIFT) /* Divide by 1 */
# define SIM_CLKDIV1_OUTDIV1_2 (1 << SIM_CLKDIV1_OUTDIV1_SHIFT) /* Divide by 2 */
# define SIM_CLKDIV1_OUTDIV1_3 (2 << SIM_CLKDIV1_OUTDIV1_SHIFT) /* Divide by 3 */
# define SIM_CLKDIV1_OUTDIV1_4 (3 << SIM_CLKDIV1_OUTDIV1_SHIFT) /* Divide by 4 */
# define SIM_CLKDIV1_OUTDIV1_5 (4 << SIM_CLKDIV1_OUTDIV1_SHIFT) /* Divide by 5 */
# define SIM_CLKDIV1_OUTDIV1_6 (5 << SIM_CLKDIV1_OUTDIV1_SHIFT) /* Divide by 6 */
# define SIM_CLKDIV1_OUTDIV1_7 (6 << SIM_CLKDIV1_OUTDIV1_SHIFT) /* Divide by 7 */
# define SIM_CLKDIV1_OUTDIV1_8 (7 << SIM_CLKDIV1_OUTDIV1_SHIFT) /* Divide by 8 */
# define SIM_CLKDIV1_OUTDIV1_9 (8 << SIM_CLKDIV1_OUTDIV1_SHIFT) /* Divide by 9 */
# define SIM_CLKDIV1_OUTDIV1_10 (9 << SIM_CLKDIV1_OUTDIV1_SHIFT) /* Divide by 10 */
# define SIM_CLKDIV1_OUTDIV1_11 (10 << SIM_CLKDIV1_OUTDIV1_SHIFT) /* Divide by 11 */
# define SIM_CLKDIV1_OUTDIV1_12 (11 << SIM_CLKDIV1_OUTDIV1_SHIFT) /* Divide by 12 */
# define SIM_CLKDIV1_OUTDIV1_13 (12 << SIM_CLKDIV1_OUTDIV1_SHIFT) /* Divide by 13 */
# define SIM_CLKDIV1_OUTDIV1_14 (13 << SIM_CLKDIV1_OUTDIV1_SHIFT) /* Divide by 14 */
# define SIM_CLKDIV1_OUTDIV1_15 (14 << SIM_CLKDIV1_OUTDIV1_SHIFT) /* Divide by 15 */
# define SIM_CLKDIV1_OUTDIV1_16 (15 << SIM_CLKDIV1_OUTDIV1_SHIFT) /* Divide by 16 */
/* System Clock Divider Register 2 */
#if defined(KINETIS_SIM_HAS_CLKDIV2_USBFRAC)
# define SIM_CLKDIV2_USBFRAC_SHIFT (0) /* Bit 0: USB clock divider fraction */
# define SIM_CLKDIV2_USBFRAC_MASK (1 << SIM_CLKDIV2_USBFRAC_SHIFT)
# define SIM_CLKDIV2_USBFRAC(n) ((((n)-1) & 1) << SIM_CLKDIV2_USBFRAC_SHIFT) /* n=1..2 */
#endif
#if defined(KINETIS_SIM_HAS_CLKDIV2_USBDIV)
# define SIM_CLKDIV2_USBDIV_SHIFT (1) /* Bits 1-3: USB clock divider divisor */
# define SIM_CLKDIV2_USBDIV_MASK (7 << SIM_CLKDIV2_USBDIV_SHIFT)
# define SIM_CLKDIV2_USBDIV(n) ((((n)-1) & 7) << SIM_CLKDIV2_USBDIV_SHIFT) /* n=1..8 */
#endif
/* Bits 4-7: Reserved */
#if defined(KINETIS_SIM_HAS_CLKDIV2_USBHSFRAC)
# define SIM_CLKDIV2_USBHSFRAC_SHIFT (8) /* Bit 8: USB HS clock divider fraction */
# define SIM_CLKDIV2_USBHSFRAC_MASK (1 << SIM_CLKDIV2_USBHSFRAC_SHIFT)
# define SIM_CLKDIV2_USBHSFRAC(n) ((((n)-1) & 1) << SIM_CLKDIV2_USBHSFRAC_SHIFT) /* n=1..2 */
#endif
#if defined(KINETIS_SIM_HAS_CLKDIV2_USBHSDIV)
# define SIM_CLKDIV2_USBHSDIV_SHIFT (9) /* Bits 1-3: USB HS clock divider divisor */
# define SIM_CLKDIV2_USBHSDIV_MASK (7 << SIM_CLKDIV2_USBHSDIV_SHIFT)
# define SIM_CLKDIV2_USBHSDIV(n) ((((n)-1) & 7) << SIM_CLKDIV2_USBHSDIV_SHIFT) /* n=1..8 */
#endif
#if defined(KINETIS_SIM_HAS_CLKDIV2_I2SFRAC)
# define SIM_CLKDIV2_I2SFRAC_SHIFT (8) /* Bits 8-15: I2S clock divider fraction */
# define SIM_CLKDIV2_I2SFRAC_MASK (0xff << SIM_CLKDIV2_I2SFRAC_SHIFT)
#endif
/* Bits 16-19: Reserved */
#if defined(KINETIS_SIM_HAS_CLKDIV2_I2SDIV)
# define SIM_CLKDIV2_I2SDIV_SHIFT (20) /* Bits 20-31: I2S clock divider value */
# define SIM_CLKDIV2_I2SDIV_MASK (0xfff << SIM_CLKDIV2_I2SDIV_SHIFT)
#endif
/* Flash Configuration Register 1 */
#if defined(KINETIS_SIM_HAS_FCFG1_FTFDIS)
# define SIM_FCFG1_FTFDIS (1 << 0) /* Bit 0: Disable FTFE */
#endif
#if defined(KINETIS_SIM_HAS_FCFG1_FLASHDIS)
# define SIM_FCFG1_FLASHDIS (1 << 0) /* Bit 0: Flash Disable */
#endif
#if defined(KINETIS_SIM_HAS_FCFG1_FLASHDOZE)
# define SIM_FCFG1_FLASHDOZE (1 << 1) /* Bit 1: Flash Doze */
#endif
/* Bits 0-7: Reserved */
#if defined(KINETIS_SIM_HAS_FCFG1_DEPART)
# define SIM_FCFG1_DEPART_SHIFT (8) /* Bits 8-11: FlexNVM partition */
# define SIM_FCFG1_DEPART_MASK (15 << SIM_FCFG1_DEPART_SHIFT)
#endif
/* Bits 12-15: Reserved */
#if defined(KINETIS_SIM_HAS_FCFG1_EESIZE)
# define SIM_FCFG1_EESIZE_SHIFT (16) /* Bits 16-19: EEPROM size */
# define SIM_FCFG1_EESIZE_MASK (15 << SIM_FCFG1_EESIZE_SHIFT)
# define SIM_FCFG1_EESIZE_16KB (0 << SIM_FCFG1_EESIZE_SHIFT) /* 16 KB */
# define SIM_FCFG1_EESIZE_8KB (1 << SIM_FCFG1_EESIZE_SHIFT) /* 8 KB */
# define SIM_FCFG1_EESIZE_4KB (2 << SIM_FCFG1_EESIZE_SHIFT) /* 4 KB */
# define SIM_FCFG1_EESIZE_2KB (3 << SIM_FCFG1_EESIZE_SHIFT) /* 2 KB */
# define SIM_FCFG1_EESIZE_1KB (4 << SIM_FCFG1_EESIZE_SHIFT) /* 1 KB */
# define SIM_FCFG1_EESIZE_512B (5 << SIM_FCFG1_EESIZE_SHIFT) /* 512 Bytes */
# define SIM_FCFG1_EESIZE_256B (6 << SIM_FCFG1_EESIZE_SHIFT) /* 256 Bytes */
# define SIM_FCFG1_EESIZE_128B (7 << SIM_FCFG1_EESIZE_SHIFT) /* 128 Bytes */
# define SIM_FCFG1_EESIZE_64B (8 << SIM_FCFG1_EESIZE_SHIFT) /* 64 Bytes */
# define SIM_FCFG1_EESIZE_32B (9 << SIM_FCFG1_EESIZE_SHIFT) /* 32 Bytes */
# define SIM_FCFG1_EESIZE_NONE (15 << SIM_FCFG1_EESIZE_SHIFT) /* 0 Bytes */
#endif
/* Bits 20-23: Reserved */
#define SIM_FCFG1_PFSIZE_SHIFT (24) /* Bits 24-27: Program flash size */
#define SIM_FCFG1_PFSIZE_MASK (15 << SIM_FCFG1_PFSIZE_SHIFT)
# if defined(KINETIS_K40)
# define SIM_FCFG1_PFSIZE_128KB (7 << SIM_FCFG1_PFSIZE_SHIFT) /* 128KB program flash, 4KB protection region */
# define SIM_FCFG1_PFSIZE_256KB (9 << SIM_FCFG1_PFSIZE_SHIFT) /* 256KB program flash, 8KB protection region */
# define SIM_FCFG1_PFSIZE_512KB (11 << SIM_FCFG1_PFSIZE_SHIFT) /* 512KB program flash, 16KB protection region */
# define SIM_FCFG1_PFSIZE_512KB2 (15 << SIM_FCFG1_PFSIZE_SHIFT) /* 512KB program flash, 16KB protection region */
# endif
# if defined(KINETIS_K60)
# define SIM_FCFG1_PFSIZE_512KB (11 << SIM_FCFG1_PFSIZE_SHIFT) /* 512 KB, 16 KB protection size */
# define SIM_FCFG1_PFSIZE_1024KB (13 << SIM_FCFG1_PFSIZE_SHIFT) /* 1024 KB, 32 KB protection size */
# define SIM_FCFG1_PFSIZE_2048KB (15 << SIM_FCFG1_PFSIZE_SHIFT) /* 1024 KB, 32 KB protection size */
# endif
# if defined(KINETIS_K28) || defined(KINETIS_K64) || defined(KINETIS_K66)
# define SIM_FCFG1_PFSIZE_32KB (3 << SIM_FCFG1_PFSIZE_SHIFT) /* 32 KB of program flash memory */
# define SIM_FCFG1_PFSIZE_64KB (5 << SIM_FCFG1_PFSIZE_SHIFT) /* 64 KB of program flash memory */
# define SIM_FCFG1_PFSIZE_128KB (7 << SIM_FCFG1_PFSIZE_SHIFT) /* 128 KB of program flash memory */
# define SIM_FCFG1_PFSIZE_256KB (9 << SIM_FCFG1_PFSIZE_SHIFT) /* 256 KB of program flash memory */
# define SIM_FCFG1_PFSIZE_512KB (11 << SIM_FCFG1_PFSIZE_SHIFT) /* 512 KB of program flash memory */
# define SIM_FCFG1_PFSIZE_1024KB (13 << SIM_FCFG1_PFSIZE_SHIFT) /* 1024 KB of program flash memory */
# define SIM_FCFG1_PFSIZE_2048KB (15 << SIM_FCFG1_PFSIZE_SHIFT) /* 2048 KB of program flash memory */
# endif
#if defined(KINETIS_SIM_HAS_FCFG1_NVMSIZE)
# define SIM_FCFG1_NVMSIZE_SHIFT (28) /* Bits 28-31: FlexNVM size */
# define SIM_FCFG1_NVMSIZE_MASK (15 << SIM_FCFG1_NVMSIZE_SHIFT)
# define SIM_FCFG1_NVMSIZE_NONE (0 << SIM_FCFG1_NVMSIZE_SHIFT) /* 0KB FlexNVM */
# if defined(KINETIS_K28)
# define SIM_FCFG1_NVMSIZE_32KB (3 << SIM_FCFG1_NVMSIZE_SHIFT) /* 32KB FlexNVM */
# define SIM_FCFG1_NVMSIZE_64KB (5 << SIM_FCFG1_NVMSIZE_SHIFT) /* 64KB FlexNVM */
# define SIM_FCFG1_NVMSIZE_128KB (7 << SIM_FCFG1_NVMSIZE_SHIFT) /* 128KB FlexNVM */
# define SIM_FCFG1_NVMSIZE_256KB (9 << SIM_FCFG1_NVMSIZE_SHIFT) /* 256KB FlexNVM */
# define SIM_FCFG1_NVMSIZE_512KB (11 << SIM_FCFG1_NVMSIZE_SHIFT) /* 512KB FlexNVM */
# else
# define SIM_FCFG1_NVMSIZE_128KB (7 << SIM_FCFG1_NVMSIZE_SHIFT) /* 128KB FlexNVM, 16KB protection region */
# define SIM_FCFG1_NVMSIZE_256KB (9 << SIM_FCFG1_NVMSIZE_SHIFT) /* 256KB FlexNVM, 32KB protection region */
# define SIM_FCFG1_NVMSIZE_256KB2 (15 << SIM_FCFG1_NVMSIZE_SHIFT) /* 256KB FlexNVM, 32KB protection region */
# endif
#endif
/* Flash Configuration Register 2 */
/* Bits 0-15: Reserved */
#if defined(KINETIS_SIM_HAS_FCFG2_MAXADDR1)
# define SIM_FCFG2_MAXADDR1_SHIFT (16) /* Bits 16-[21|22]: Max address block 1 */
# define SIM_FCFG2_MAXADDR1_MASK (KINETIS_SIM_FCFG2_MAXADDR1_MASK << SIM_FCFG2_MAXADDR1_SHIFT)
# define SIM_FCFG2_MAXADDR1(n) (((n) & KINETIS_SIM_FCFG2_MAXADDR1_MASK) << SIM_FCFG2_MAXADDR1_SHIFT)
#endif
/* Bit 22: Reserved */
#if defined(KINETIS_SIM_HAS_FCFG2_PFLSH)
# define SIM_FCFG2_PFLSH (1 << 23) /* Bit 23: Program flash */
#endif
#if defined(KINETIS_SIM_HAS_FCFG2_MAXADDR0)
# define SIM_FCFG2_MAXADDR0_SHIFT (24) /* Bits 24-[29|30]: Max address block 0 */
# define SIM_FCFG2_MAXADDR0_MASK (KINETIS_SIM_FCFG2_MAXADDR0_MASK << SIM_FCFG2_MAXADDR0_SHIFT)
# define SIM_FCFG2_MAXADDR0(n) (((n) & KINETIS_SIM_FCFG2_MAXADDR0_MASK) << SIM_FCFG2_MAXADDR0_SHIFT)
/* Bit 30: Reserved */
#endif
#if defined(KINETIS_SIM_HAS_FCFG2_SWAPPFLSH)
# define SIM_FCFG2_SWAPPFLSH (1 << 31) /* Bit 31: Swap program flash */
#endif
/* Unique Identification Register High. 32-bit Unique Identification. */
/* Unique Identification Register Mid-High. 32-bit Unique Identification. */
/* Unique Identification Register Mid Low. 32-bit Unique Identification. */
/* Unique Identification Register Low. 32-bit Unique Identification. */
#if defined(KINETIS_SIM_HAS_CLKDIV3)
/* System Clock Divider Register 3 */
# if defined(KINETIS_SIM_HAS_CLKDIV3_PLLFLLFRAC)
# define SIM_CLKDIV3_PLLFLLFRAC_SHIFT (0) /* Bit 0: PLLFLL clock divider fraction */
# define SIM_CLKDIV3_PLLFLLFRAC_MASK (1 << SIM_CLKDIV3_PLLFLLFRAC_SHIFT)
# define SIM_CLKDIV3_PLLFLLFRAC(n) ((((n)-1) & 1) << SIM_CLKDIV3_PLLFLLFRAC_SHIFT) /* n=1..2 */
# endif
# if defined(KINETIS_SIM_HAS_CLKDIV3_PLLFLLDIV)
# define SIM_CLKDIV3_PLLFLLDIV_SHIFT (1) /* Bits 1-3: PLLFLL clock divider divisor */
# define SIM_CLKDIV3_PLLFLLDIV_MASK (7 << SIM_CLKDIV3_PLLFLLDIV_SHIFT)
# define SIM_CLKDIV3_PLLFLLDIV(n) ((((n)-1) & 7) << SIM_CLKDIV3_PLLFLLDIV_SHIFT) /* n=1..8 */
# endif
#endif
/* System Clock Divider Register 4 */
#if defined(KINETIS_SIM_HAS_CLKDIV4)
# if defined(KINETIS_SIM_HAS_CLKDIV4_TRACEFRAC)
# define SIM_CLKDIV4_TRACEFRAC_SHIFTS (0) /* Bit 0: Trace clock divider fraction */
# define SIM_CLKDIV4_TRACEFRAC_MASK (1 << SIM_CLKDIV4_TRACEFRAC_SHIFTS)
# define SIM_CLKDIV4_TRACEFRAC(n) ((((n)-1) & 1) << SIM_CLKDIV4_TRACEFRAC_SHIFTS) /* n=1..2 */
# endif
# if defined(KINETIS_SIM_HAS_CLKDIV4_TRACEDIV)
# define SIM_CLKDIV4_TRACEDIV_SHIFT (1) /* Bits 1-3: Trace clock divider divisor */
# define SIM_CLKDIV4_TRACEDIV_MASK (7 << SIM_CLKDIV3_TRACEDIV_SHIFT)
# define SIM_CLKDIV4_TRACEDIV(n) ((((n)-1) & 7) << SIM_CLKDIV4_TRACEDIV_SHIFT) /* n=1..8 */
# endif
# if defined(KINETIS_SIM_HAS_CLKDIV4_NFCFRAC)
# define SIM_CLKDIV4_NFCFRAC_SHIFT (24) /* Bits 24-26: NFC clock divider fraction */
# define SIM_CLKDIV4_NFCFRAC_MASK (7 << SIM_CLKDIV4_NFCFRAC_SHIFT)
# define SIM_CLKDIV4_NFCFRAC(n) ((((n)-1) & 7) << SIM_CLKDIV4_NFCFRAC_SHIFT) /* n=1..8 */
# endif
# if defined(KINETIS_SIM_HAS_CLKDIV4_NFCDIV)
# define SIM_CLKDIV4_NFCDIV_SHIFT (27) /* Bits 27-31: NFC clock divider divisor */
# define SIM_CLKDIV4_NFCDIV_MASK (31 << SIM_CLKDIV3_NFCDIV_SHIFT)
# define SIM_CLKDIV4_NFCDIV(n) ((((n)-1) & 31) << SIM_CLKDIV4_NFCDIV_SHIFT) /* n=1..32 */
# endif
#endif
/* Misc Control Register */
#if defined(KINETIS_SIM_HAS_MCR)
/* Bits 0-28:
* Reserved
*/
# define SIM_MCR_PDBLOOP (1<< 29) /* Bit 29: PDB Loop Mode */
/* Bit 30: Reserved */
# define SIM_MCR_TRACECLKDIS (1<< 31) /* Bit 31: Trace clock disable. */
#endif
/****************************************************************************
* Public Types
****************************************************************************/
/****************************************************************************
* Public Data
****************************************************************************/
/****************************************************************************
* Public Functions Prototypes
****************************************************************************/
#endif /* __ARCH_ARM_SRC_KINETIS_HARDWARE_KINETIS_SIM_H */
| 51,511
|
809
|
/**
* @file
* @brief
*
* @author <NAME>
* @date 25.02.14
*/
#ifndef KERNEL_TASK_RESOURCE_SIG_TABLE_H_
#define KERNEL_TASK_RESOURCE_SIG_TABLE_H_
#include <kernel/task.h>
#include <sys/cdefs.h>
struct task;
struct sigaction;
__BEGIN_DECLS
extern struct sigaction * task_resource_sig_table(
const struct task *task);
#define task_self_resource_sig_table() \
task_resource_sig_table(task_self())
__END_DECLS
#endif /* KERNEL_TASK_RESOURCE_SIG_TABLE_H_ */
| 205
|
1,127
|
<filename>src/tests_deprecated/unit/engines/vpu/myriad_tests/helpers/myriad_test_case.h
// Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <gtest/gtest.h>
#include <memory>
#include <tuple>
#include "myriad_plugin.h"
#include "myriad_mvnc_stub.h"
#define DEFAULT_SEED_VALUE (43)
using namespace vpu::MyriadPlugin;
using namespace ::testing;
using AvailableDevices = std::vector<std::string>;
using UnbootedDevices = std::vector<std::string>;
using BootedDevices = std::vector<std::string>;
using range_type = std::tuple<unsigned int, unsigned int, unsigned int>;
using config_t = std::map<std::string, std::string>;
using MyriadEngineSetConfigTestParam = WithParamInterface<config_t>;
using MyriadMetricsTestParam = WithParamInterface<AvailableDevices>;
using MyriadMetricsContainerTestParam = WithParamInterface<std::tuple<UnbootedDevices, BootedDevices>>;
using MyriadRangeMetricsContainerTestParam = WithParamInterface<std::tuple<range_type, std::string>>;
//------------------------------------------------------------------------------
// class MyriadEngineTest
//------------------------------------------------------------------------------
class MyriadEngineTest : public Test {
public:
MyriadEngineTest();
protected:
//Data section
std::shared_ptr<MvncStub> mvnc_stub_;
std::shared_ptr<Engine> myriad_engine_;
};
//------------------------------------------------------------------------------
// class MyriadEngineTest
//------------------------------------------------------------------------------
class MyriadEngineSetConfigTest : public MyriadEngineTest,
public MyriadEngineSetConfigTestParam{
protected:
//Operations
void SetUp() override;
protected:
//Data section
std::map<std::string, std::string> config_;
};
//------------------------------------------------------------------------------
// class MyriadGetMetricsTestCase
//------------------------------------------------------------------------------
class MyriadGetMetricsTestCase : public MyriadEngineTest {
public:
MyriadGetMetricsTestCase() = default;
//Operations
void SetupOneDevice();
protected:
//Data section
std::vector<std::string> exp_devices_names_;
std::map<std::string, InferenceEngine::Parameter> options_;
};
//------------------------------------------------------------------------------
// class MyriadGetMetricsTestCaseWithParam
//------------------------------------------------------------------------------
class MyriadGetMetricsTestCaseWithParam : public MyriadGetMetricsTestCase,
public MyriadMetricsTestParam {
protected:
//Operations
void SetUp() override;
};
//------------------------------------------------------------------------------
// class MyriadMetricsTest
//------------------------------------------------------------------------------
class MyriadMetricsTest : public Test {
public:
MyriadMetricsTest();
//Operations
void SetDevices(std::vector<std::string> deviceNames);
protected:
//Data section
std::shared_ptr<MyriadMetrics> metrics_container_;
std::shared_ptr<MvncStub> mvnc_stub_;
std::vector<DevicePtr> devices_;
};
//------------------------------------------------------------------------------
// class MyriadDeviceMetricsTestWithParam
//------------------------------------------------------------------------------
class MyriadDeviceMetricsTestWithParam : public MyriadMetricsTest,
public MyriadMetricsContainerTestParam{
protected:
//Operations
void SetUp() override;
//Data section
std::vector<std::string> exp_unbooted_devices_names_;
std::vector<std::string> exp_booted_devices_names_;
};
//------------------------------------------------------------------------------
// class MyriadDeviceMetricsTestWithParam
//------------------------------------------------------------------------------
class MyriadRangeInferMetricsTestWithParam : public MyriadMetricsTest,
public MyriadRangeMetricsContainerTestParam{
protected:
//Operations
void SetUp() override;
//Data section
range_type exp_range_;
std::string confir_param_;
};
| 1,247
|
22,779
|
<filename>plugins/org.jkiss.dbeaver.ui/src/org/jkiss/dbeaver/ui/notifications/DatabaseNotificationSink.java
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 DBeaver Corp and others
*
* 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.jkiss.dbeaver.ui.notifications;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchPreferenceConstants;
import org.eclipse.ui.PlatformUI;
import org.jkiss.dbeaver.ModelPreferences;
import java.util.*;
public class DatabaseNotificationSink {
private static final long DELAY_OPEN = 200;
private static final boolean runSystem = true;
private final WeakHashMap<Object, Object> cancelledTokens = new WeakHashMap<>();
private final Set<AbstractNotification> notifications = new HashSet<>();
private final Set<AbstractNotification> currentlyNotifying = Collections.synchronizedSet(notifications);
private final Job openJob = new Job("Database notifications") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
if (Platform.isRunning() && PlatformUI.getWorkbench() != null
&& PlatformUI.getWorkbench().getDisplay() != null
&& !PlatformUI.getWorkbench().getDisplay().isDisposed()) {
PlatformUI.getWorkbench().getDisplay().asyncExec(() -> {
collectNotifications();
if (popup != null && popup.getReturnCode() == Window.CANCEL) {
List<AbstractNotification> notifications = popup.getNotifications();
for (AbstractNotification notification : notifications) {
if (notification.getToken() != null) {
cancelledTokens.put(notification.getToken(), null);
}
}
}
currentlyNotifying.removeIf(notification -> notification.getToken() != null
&& cancelledTokens.containsKey(notification.getToken()));
synchronized (DatabaseNotificationSink.class) {
if (currentlyNotifying.size() > 0) {
// popup.close();
showPopup();
}
}
});
}
} finally {
if (popup != null) {
schedule(popup.getDelayClose() / 2);
}
}
if (monitor.isCanceled()) {
return Status.CANCEL_STATUS;
}
return Status.OK_STATUS;
}
};
private DatabaseNotificationPopup popup;
public DatabaseNotificationSink() {
openJob.setSystem(runSystem);
}
private void cleanNotified() {
currentlyNotifying.clear();
}
/** public for testing */
private void collectNotifications() {
}
/**
* public for testing purposes
*/
public Set<AbstractNotification> getNotifications() {
synchronized (DatabaseNotificationSink.class) {
return currentlyNotifying;
}
}
private boolean isAnimationsEnabled() {
IPreferenceStore store = PlatformUI.getPreferenceStore();
return store.getBoolean(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS);
}
public void notify(NotificationSinkEvent event) {
currentlyNotifying.addAll(event.getNotifications());
if (!openJob.cancel()) {
try {
openJob.join();
} catch (InterruptedException e) {
// ignore
}
}
openJob.schedule(DELAY_OPEN);
}
private void showPopup() {
if (popup != null) {
popup.close();
}
Shell shell = new Shell(PlatformUI.getWorkbench().getDisplay());
popup = new DatabaseNotificationPopup(shell);
popup.setFadingEnabled(isAnimationsEnabled());
popup.setDelayClose(ModelPreferences.getPreferences().getInt(ModelPreferences.NOTIFICATIONS_CLOSE_DELAY_TIMEOUT));
List<AbstractNotification> toDisplay = new ArrayList<>(currentlyNotifying);
Collections.sort(toDisplay);
popup.setContents(toDisplay);
cleanNotified();
popup.setBlockOnOpen(false);
popup.open();
}
}
| 2,234
|
410
|
{
"authors": [],
"date_download": null,
"date_modify": null,
"date_publish": "2017-11-11T11:46:46",
"description": "Volkswagen may be the subject of a new allegation of insider information disclosure as the Dieselgate emissions scam remains in the headlines more than two years following its disclosure.",
"filename": "https%3A%2F%2Fwww.torquenews.com%2F3769%2Fdieselgate-seems-be-scandal-keeps-giving-new-vw-probe-possible.json",
"image_url": "https://www.torquenews.com/sites/default/files/images/vw_sign_700_x_440_600_x_377_0.jpg",
"language": "en",
"localpath": null,
"source_domain": "www.torquenews.com",
"text": "Fully two years after the scam first broke, Dieselgate is the scandal that keeps on giving and Volkswagen has likely had enough of it. Already the subject of an investigation by Germany\u2019s financial watchdog BaFin, the agency Friday disclosed that it is probing whether the automaker illegally informed others of its emissions violations.\nAgencies probing VW on several fronts\nVolkswagen, the world\u2019s largest automaker, is the subject of another investigation by the agency for suspected insider trading relating to the diesel emissions scam. And, the German state of Braunschweig, is probing reports of market manipulation relating to the scandal.\nIn another significant setback for the automaker, a German court has ruled that an independent auditor should be appointed to probe Volkswagen\u2019s plans to cheat on U.S. diesel engine testing. Said Reuters of this development: The development boosted \u201cinvestors\u2019 hopes for compensation.\u201d Investor compensation has been the subject of legal action for more than a year.\nRegarding the latest accusations of potential financial impropriety, <NAME>, the German newsmagazine, said in its current issue that VW\u2019s chief, at that time, <NAME>, had mentioned the true extent of the scandal before the automaker went public. Winterkorn reportedly told then-Transport Minister <NAME>, also head of Germany\u2019s KBA, the motor vehicle watchdog agency, on Sept. 21, 2015, about the extent of the scandal. However, the automaker did not alert the public until the next day that it had installed cheating software in 11 million vehicles worldwide. The cheating software contained the so-called \u201cdefeat switch\u201d that allowed VWs to pass U.S. emissions testing. At the same time, the automaker disclosed that it would have to set aside billions in euros to cover the scandal\u2019s costs.\nAgency probes potential insider information violation\n\u201cWe are looking at this process with a view to a potentially unauthorized disclosure of inside information,\u201d a BaFin spokesman said, in confirming the report in Der Spiegel. VW declined to comment on the story but said its management board had done their due diligence regarding capital market disclosure rules. KBA was unavailable for comment.\nSources: Automotive News, Reuters, Der Spiegel",
"title": "Dieselgate seems to be the scandal the keeps on giving; new VW probe possible",
"title_page": null,
"title_rss": null,
"url": "https://www.torquenews.com/3769/dieselgate-seems-be-scandal-keeps-giving-new-vw-probe-possible",
"category_id": 4,
"category": "Dieselgate",
"dId": "bbbc3473055fec8ee8f9b8d92be71d5bf87b793a092e338488d2abc0"
}
| 887
|
5,169
|
<filename>Specs/d/d/9/Swace/0.0.13/Swace.podspec.json
{
"name": "Swace",
"version": "0.0.13",
"summary": "Common components used that can be re-used in multiple apps",
"description": "This pod exists to be able to re-use and add code that is commonly shared among multiple projects.",
"homepage": "https://github.com/orgs/swacedigital/",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"<EMAIL>": "<EMAIL>"
},
"source": {
"git": "https://github.com/swacedigital/swace-ios.git",
"tag": "0.0.13",
"branch": "master"
},
"platforms": {
"ios": "10.0"
},
"source_files": "Swace/Classes/**/*"
}
| 273
|
7,482
|
/**
* \file
*
* \brief DFLL management
*
* Copyright (c) 2010-2015 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \asf_license_stop
*
*/
/*
* Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a>
*/
#ifndef CLK_DFLL_H_INCLUDED
#define CLK_DFLL_H_INCLUDED
#include <parts.h>
#include "conf_clock.h"
#if UC3L
# include "uc3l/dfll.h"
#elif SAM4L
# include "sam4l/dfll.h"
#else
# error Unsupported chip type
#endif
/**
* \ingroup clk_group
* \defgroup dfll_group DFLL Management
*
* A Digital Frequency Locked Loop can be used to generate a highly
* accurate frequency from a slower-running reference clock, in much the
* same way as a PLL. DFLLs typically have shorter startup times and
* less jitter. They can also be used in open-loop mode to generate a
* less accurate frequency without the use of a reference clock.
*
* There may be significant variations between platforms in the support
* for certain features.
*
* \par Example: Setting up DFLL0 with default parameters and dithering enabled
*
* The following example shows how to configure and enable DFLL0 in
* closed-loop mode using the default parameters specified through
* configuration symbols.
* \code
dfll_enable_config_defaults(0); \endcode
*
* To configure and enable DFLL0 in closed-loop mode using the default
* parameters and to enable specific feature like dithering for better accuracy,
* you can use this initialization process.
* \code
struct dfll_config dfllcfg;
dfll_enable_source(CONFIG_DFLL0_SOURCE);
dfll_config_defaults(&dfllcfg, 0);
dfll_config_enable_dithering(&dfllcfg);
dfll_enable(&dfllcfg, 0);
dfll_wait_for_accurate_lock(0); \endcode
*
* When the last function call returns, DFLL0 is running at a frequency
* which matches the default configuration as accurately as possible.
* Any additional alterations to the default configuration can be added
* at the same place as the call to dfll_config_enable_dithering(), but
* note that the DFLL will never achieve "accurate" lock if dithering is
* disabled.
*
* @{
*/
//! \name Chip-specific DFLL characteristics
//@{
/**
* \def NR_DFLLS
* \brief Number of on-chip DFLLs.
*/
/**
* \def DFLL_MIN_HZ
* \brief Minimum frequency that the DFLL can generate.
*/
/**
* \def DFLL_MAX_HZ
* \brief Maximum frequency that the DFLL can generate.
*/
//@}
/**
* \typedef dfll_refclk_t
* \brief Type used for identifying a reference clock source for the DFLL.
*/
//! \name DFLL Configuration
//@{
/**
* \struct dfll_config
* \brief Hardware-specific representation of DFLL configuration.
*
* This structure contains one or more device-specific values
* representing the current DFLL configuration. The contents of this
* structure is typically different from platform to platform, and the
* user should not access any fields except through the DFLL
* configuration API.
*/
/**
* \fn void dfll_config_init_open_loop_mode(struct dfll_config *cfg)
* \brief Configure the DFLL configuration \a cfg for open-loop mode.
*
* \param cfg The DFLL configuration to be initialized.
*/
/**
* \fn void dfll_config_init_closed_loop_mode(struct dfll_config *cfg,
* dfll_refclk_t refclk, uint16_t div, uint16_t mul)
* \brief Configure the DFLL configuration \a cfg for closed-loop mode.
*
* \param cfg The DFLL configuration to be initialized.
* \param refclk The reference clock source.
* \param div Reference clock divider.
* \param mul Multiplier (integer part only).
*/
/**
* \def dfll_config_defaults(cfg, dfll_id)
* \brief Initialize DFLL configuration using default parameters.
*
* After this function returns, \a cfg will contain a configuration
* which will make the DFLL run at (CONFIG_DFLLx_MUL / CONFIG_DFLLx_DIV)
* times the frequency of CONFIG_DFLLx_SOURCE. The default configuration
* will always use closed-loop mode with no fractional multiplier.
*
* \param cfg The DFLL configuration to be initialized.
* \param dfll_id Use defaults for this DFLL.
*/
/**
* \def dfll_get_default_rate(dfll_id)
* \brief Return the default rate in Hz of \a dfll_id.
*/
/**
* \fn void dfll_config_set_fractional_multiplier(struct dfll_config *cfg,
* uint16_t mul_i, uint16_t mul_f)
* \brief Set a fractional multiplier.
*
* This function has no effect in open-loop mode, and is only available
* on devices which support fractional multipliers.
*
* The fractional part of the multiplier is assumed to be 16 bits. The
* low-level driver will make sure to shift this value to match the
* hardware if necessary.
*
* \param cfg The DFLL configuration to be modified.
* \param mul_i Integer part of multiplier.
* \param mul_f Fractional part of multiplier.
*/
/**
* \fn void dfll_config_enable_dithering(struct dfll_config *cfg)
* \brief Enable dithering for more accurate frequency generation.
*
* The fine LSB input to the VCO is dithered to achieve fractional
* approximation to the correct multiplication ratio.
*
* \param cfg The DFLL configuration to be modified.
*/
/**
* \fn void dfll_config_disable_dithering(struct dfll_config *cfg)
* \brief Disable dithering.
*
* \see dfll_config_enable_dithering()
*
* \param cfg The DFLL configuration to be modified.
*/
/**
* \fn void dfll_config_set_initial_tuning(struct dfll_config *cfg,
* uint16_t coarse, uint16_t fine)
* \brief Set initial VCO tuning.
*
* In open loop mode, this will determine the frequency of the output.
*
* In closed loop mode, this will provide an initial estimate of the VCO
* tuning. While the DFLL will automatically adjust these values to
* match the desired output frequency, careful selection of initial
* values might reduce the time to achieve coarse and fine lock.
*
* \param cfg The DFLL configuration to be modified.
* \param coarse Coarse tuning of the frequency generator.
* \param fine Fine tuning of the frequency generator.
*/
/**
* \fn void dfll_config_set_max_step(struct dfll_config *cfg,
* uint16_t coarse, uint16_t fine)
* \brief Set the maximum VCO tuning step size.
*
* This function has no effect in open-loop mode.
*
* By default, both of these values are set to 50% of their respective
* maximums. It is not recommended to set the values any higher than
* this, but setting them lower might reduce the frequency overshoot at
* the expense of longer time to achieve coarse and/or fine lock.
*
* \param cfg The DFLL configuration to be modified
* \param coarse The maximum step size of the coarse VCO tuning.
* \param fine The maximum step size of the fine VCO tuning.
*/
/**
* \fn void dfll_config_enable_ssg(struct dfll_config *cfg,
* uint16_t amplitude, uint16_t step_size)
* \brief Enable Spread Spectrum Generator.
*
* \param cfg The DFLL configuration to be modified.
* \param amplitude The amplitude of the spread spectrum.
* \param step_size The step size of the spread spectrum.
*/
/**
* \fn void dfll_config_disable_ssg(struct dfll_config *cfg)
* \brief Disable Spread Spectrum Generator.
*
* \param cfg The DFLL configuration to be modified.
*/
//@}
//! \name Interaction with the DFLL hardware
//@{
/**
* \fn void dfll_enable_open_loop(const struct dfll_config *cfg,
* unsigned int dfll_id)
* \brief Activate the configuration \a cfg and enable DFLL \a dfll_id
* in open-loop mode.
*
* \pre The configuration in \a cfg must represent an open-loop
* configuration.
*
* \param cfg The configuration to be activated.
* \param dfll_id The ID of the DFLL to be enabled.
*/
/**
* \fn void dfll_enable_closed_loop(const struct dfll_config *cfg,
* unsigned int dfll_id)
* \brief Activate the configuration \a cfg and enable DFLL \a dfll_id
* in closed-loop mode.
*
* \pre The configuration in \a cfg must represent a closed-loop
* configuration.
*
* \param cfg The configuration to be activated.
* \param dfll_id The ID of the DFLL to be enabled.
*/
/**
* \fn void dfll_disable_open_loop(unsigned int dfll_id)
* \brief Disable the DFLL identified by \a dfll_id.
*
* \pre The DFLL must have been enabled in open loop mode.
*
* \param dfll_id The ID of the DFLL to be disabled.
*/
/**
* \fn void dfll_disable_closed_loop(unsigned int dfll_id)
* \brief Disable the DFLL identified by \a dfll_id.
*
* \pre The DFLL must have been enabled in closed loop mode.
*
* \param dfll_id The ID of the DFLL to be disabled.
*/
/**
* \fn bool dfll_is_coarse_locked(unsigned int dfll_id)
* \brief Determine whether or not a DFLL has achieved coarse lock.
*
* \param dfll_id The ID of the DFLL to check.
*
* \retval true The DFLL has determined the final value of the coarse
* VCO tuning value.
* \retval false The DFLL has not yet determined the coarse VCO tuning
* value, or has not been enabled.
*/
/**
* \fn bool dfll_is_fine_locked(unsigned int dfll_id)
* \brief Determine whether or not a DFLL has achieved fine lock.
*
* \param dfll_id The ID of the DFLL to check.
*
* \retval true The DFLL has determined the final value of the fine VCO
* tuning value.
* \retval false The DFLL has not yet determined the fine VCO tuning
* value, or has not been enabled.
*/
/**
* \fn bool dfll_is_accurate_locked(unsigned int dfll_id)
* \brief Determine whether or not a DFLL has achieved accurate lock.
*
* \param dfll_id The ID of the DFLL to check.
*
* \retval true The DFLL has determined the final dithering duty cycle.
* \retval false The DFLL has not yet determined the dithering duty
* cycle, or has not been enabled with dithering enabled.
*/
/**
* \fn void dfll_enable_source(enum dfll_refclk_t src)
* \brief Enable the source of the dfll.
* The source is enabled, if the source is not already running.
*
* \param dfll_source src The ID of the DFLL source to enable.
*/
/**
* \fn void dfll_enable_config_defaults(unsigned int dfll_id)
* \brief Enable the dfll with the default configuration.
* DFLL is enabled, if the DFLL is not already locked.
*
* \param dfll_id The ID of the DFLL to enable.
*/
/**
* \brief Wait for the DFLL identified by \a dfll_id to achieve coarse
* lock.
*
* \param dfll_id The ID of the DFLL to wait for.
*
* \retval STATUS_OK The DFLL has achieved coarse lock.
* \retval ERR_TIMEOUT Timed out waiting for lock.
*/
static inline int dfll_wait_for_coarse_lock(unsigned int dfll_id)
{
/* TODO: Add timeout mechanism */
while (!dfll_is_coarse_locked(dfll_id)) {
/* Do nothing */
}
return 0;
}
/**
* \brief Wait for the DFLL identified by \a dfll_id to achieve fine
* lock.
*
* \param dfll_id The ID of the DFLL to wait for.
*
* \retval STATUS_OK The DFLL has achieved fine lock.
* \retval ERR_TIMEOUT Timed out waiting for lock.
*/
static inline int dfll_wait_for_fine_lock(unsigned int dfll_id)
{
/* TODO: Add timeout mechanism */
while (!dfll_is_fine_locked(dfll_id)) {
/* Do nothing */
}
return 0;
}
/**
* \brief Wait for the DFLL identified by \a dfll_id to achieve accurate
* lock.
*
* \param dfll_id The ID of the DFLL to wait for.
*
* \retval STATUS_OK The DFLL has achieved accurate lock.
* \retval ERR_TIMEOUT Timed out waiting for lock.
*/
static inline int dfll_wait_for_accurate_lock(unsigned int dfll_id)
{
/* TODO: Add timeout mechanism */
while (!dfll_is_accurate_locked(dfll_id)) {
/* Do nothing */
}
return 0;
}
//@}
//! @}
#endif /* CLK_DFLL_H_INCLUDED */
| 4,040
|
737
|
# ----- Copyright (c) 2014 Datacratic. All rights reserved.
"""
This module extends tornados handler classes implementing GET and POST
requests to respond to BID requests
A basic openRtb class helps to interpret requests and prepare responses
Tornado request handlers are extended to handle openRtb, and a
FixedPriceBidder MixIn is used to calculate the bids.
Replacing the Mixin by a smarter strategy using the same HTTP handlers
will create a new bid agent.
There are 2 tornado apps listening at win and event ports
playing the role of a dummy ad server. No action is taken on the events though!
To improve response time a tornado http server is being used to spawn extra
proceses to deal with larger volume of requests.
This is a simplistic implementation and should not be expected to
perform under high load, as it was tested under a few kqps
Currently the average response time for bids is around 14 to 21 ms.
"""
# NOTE: This example is not integrated as part of the rtbkit build system
# as it is an example of how to build a bidder that uses only HTTP interface
# Therefore, TornadoWeb must be manually installed to have this script working
# To do so, execute the following command from your shell:
# $> pip install tornado
# this will install tornado system wide
# to have tornado installed only at the user level do:
# $> pip install --user tornado
__version__ = "0.1"
__all__ = ["OpenRTBResponse",
"FixedPriceBidderMixIn",
"TornadoDummyRequestHandler",
"TornadoBaseBidAgentRequestHandler",
"TornadoFixPriceBidAgentRequestHandler",
"BudgetControl"]
# IMPORTS
# util libs
from copy import deepcopy
import json
import random
# tornado web
from tornado import process
from tornado import netutil
from tornado import httpserver
from tornado.web import RequestHandler, Application, url
from tornado.ioloop import IOLoop
from tornado.httpclient import AsyncHTTPClient
from tornado.ioloop import PeriodicCallback
# IMPLEMENTATION
# helper function reads the global config obj from file
def read_config(configFile):
"""read config file into config object"""
cfg = open(configFile)
contents = json.load(cfg)
return contents
# this global is used by the bidder class to configure itself
# because the request handler class makes it hard to pass this
# as a argument
CONFIGURATION_FILE = "../http_config.json"
CONFIG_OBJ = read_config(CONFIGURATION_FILE)
# ----- minimalistic OpenRTB response message class
class OpenRTBResponse():
"""this is a helper class to build basic OpenRTB json objects"""
# field names - constants to avoid magic strings inside the function
key_id = "id"
key_bid = "bid"
key_crid = "crid"
key_ext = "ext"
key_extid = "external-id"
key_ext_creatives = "creative-indexes"
key_priority = "priority"
key_impid = "impid"
key_price = "price"
key_seatbid = "seatbid"
# template obejcts
bid_object = {key_id: "1",
key_impid: "1",
key_price: 1.0,
key_crid: "",
key_ext: {key_priority: 1.0}}
seat_bid_object = {key_bid: [deepcopy(bid_object)]}
bid_response_object = {key_id: "1",
key_seatbid: [deepcopy(seat_bid_object)]}
def get_empty_response(self):
"""returns an object with the scafold of an rtb response
but containing only default values"""
empty_resp = deepcopy(self.bid_response_object)
return empty_resp
def get_default_response(self, req):
"""returns an object with the scafold of an rtb response
and fills some fields based on the request provided"""
default_resp = None
if (self.validate_req(req)):
# since this is a valid request we can return a response
default_resp = deepcopy(self.bid_response_object)
# copy request id
default_resp[self.key_id] = req[self.key_id]
# empty the bid list (we assume only one seat bid for simplicity)
default_resp[self.key_seatbid][0][self.key_bid] = []
# default values for some of the fields of the bid response
id_counter = 0
new_bid = deepcopy(self.bid_object)
# iterate over impressions array from request and
# populate bid list
# NOTE: as an example we are bidding on all the impressions,
# usually that is not what one real bid would look like!!!
for imp in req["imp"]:
# -> imp is the field name @ the req
# dumb bid id, just a counter
id_counter = id_counter + 1
new_bid[self.key_id] = str(id_counter)
# copy impression id as imp for this bid
new_bid[self.key_impid] = imp[self.key_id]
externalId = 0
# try to copy external id to the response
try:
externalId = imp[self.key_ext]["external-ids"][0]
new_bid[self.key_ext][self.key_extid] = externalId
except:
externalId = -1 # and do not add this fiel
# will keep the defaul price as it'll be changed by bidder
# and append this bid into the bid response
ref2bidList = default_resp[self.key_seatbid][0][self.key_bid]
ref2bidList.append(deepcopy(new_bid))
return default_resp
def validate_req(self, req):
""" validates the fields in the request"""
# not implemented yet. should check if the structure from
# the request is according to the spec
# this is just a dummy implementation and we assume everything is fine
valid = True
return valid
# ----- simplistic fixed price bidder MixIn class,
# has to be mixed into a request handler
class FixedPriceBidderMixIn():
"""Dumb bid agent Mixin that bid 100% at $1"""
# mixins do not have their __init__ (constructor) called
# so this class do not have it and the load of configuration
# have to be dealt with by the class that incorporates it!!!
bid_config = None
openRtb = OpenRTBResponse()
def do_config(self, cfgObj):
self.bid_config = {}
self.bid_config["probability"] = cfgObj["bidProbability"]
self.bid_config["price"] = 1.0
self.bid_config["creatives"] = cfgObj["creatives"]
def do_bid(self, bid_req):
# -------------------
# bid logic:
# since this is a fix price bidder,
# just mapping the request to the response
# and using the default price ($1) will do the work.
# -------------------
# assemble defaul response
resp = self.openRtb.get_default_response(bid_req)
# ---
# update bid with price and creatives
# ---
# first we need to buid a dictionary
# that correlates impressions from the request
# to creative lists
# FORMAT: dict[extId][impId] = [creat1..creatN]
impDict = {}
impList = bid_req["imp"]
for imp in impList:
# list of external ids from this impression
extIdsList = imp[OpenRTBResponse.key_ext]["external-ids"]
for extId in extIdsList:
tempDict = {}
creatives = imp[OpenRTBResponse.key_ext][OpenRTBResponse.key_ext_creatives]
impId = imp[OpenRTBResponse.key_id]
tempDict[impId] = creatives[str(extId)]
impDict[extId] = deepcopy(tempDict)
# then we iterate over all bids and choose a a random creative for each bid
# NOTE: we are just doing this fot the first seatbid for simplicity's sake
ref2seatbid0 = resp[OpenRTBResponse.key_seatbid][0]
for bid in ref2seatbid0[OpenRTBResponse.key_bid]:
# update bid price
bid[OpenRTBResponse.key_price] = self.bid_config["price"]
# gets the list of creatives from the ext field in the request
extId = bid[OpenRTBResponse.key_ext][OpenRTBResponse.key_extid]
impId = bid[OpenRTBResponse.key_impid]
creativeList = impDict[extId][impId]
# gets one of the creative indexes randomly
creatNdx = random.choice(creativeList)
# get creative id
creativeId = str(self.bid_config["creatives"][creatNdx]["id"])
# set the cretive id to the bid
bid[OpenRTBResponse.key_crid] = creativeId
return resp
# ----- this dummy handler always answers HTTP 200 to adserver events
# no further action is taken on the events received
class TornadoDummyRequestHandler(RequestHandler):
"""dummy handler just answer 200. Used to run a dummy adserver"""
def post(self):
self.set_status(200)
self.write("")
def get(self):
self.set_status(200)
self.write("")
# ----- tornado request handler class extend
# this class is a general bid Agent hadler.
# bid processing must be implemented in a derived class
class TornadoBaseBidAgentRequestHandler(RequestHandler):
""" extends tornado handler to answer openRtb requests"""
def post(self):
result_body = self.process_req()
self.write(result_body)
def get(self):
result_body = self.process_req()
self.write(result_body)
def process_req(self):
"""processes post requests"""
ret_val = ""
if self.request.headers["Content-Type"].startswith("application/json"):
req = json.loads(self.request.body)
else:
req = None
if (req is not None):
resp = self.process_bid(req)
if (resp is not None):
self.set_status(200)
self.set_header("Content-type", "application/json")
self.set_header("x-openrtb-version", "2.1")
ret_val = json.dumps(resp)
else:
# print("process_bid error")
self.set_status(204)
ret_val = "Error\n"
else:
# print("request not json")
self.set_status(204)
ret_val = "Error\n"
# print DEBUG
# print("req: " + self.request.body)
# print("resp: " + ret_val)
return ret_val
def process_bid(self, req):
"""---TBD in subclass---"""
resp = None
return resp
# ----- minimal fixed price bid agent implementation.
# just extends base request handler class and mix in fix price strategy
class TornadoFixPriceBidAgentRequestHandler(TornadoBaseBidAgentRequestHandler,
FixedPriceBidderMixIn):
""" This class extends TornadoBaseBidAgentRequestHandler
The bidding logic is provided by a external object passed as
parameter to the constructor"""
def __init__(self, application, request, **kwargs):
"""constructor just call parent INIT and run MixIn's do_config"""
super(TornadoBaseBidAgentRequestHandler, self).__init__(application, request, **kwargs)
if (self.bid_config is None):
# due to the way this class is instantiated
# we have to use this global var
self.do_config(CONFIG_OBJ["ACS"]["Config"])
def process_bid(self, req):
"""process bid request by calling bidder mixin do_bid() method"""
resp = self.do_bid(req)
return resp
# ----- callback funtion used by Budget pacer
def handle_async_request(response):
""" this callback function will handle the response from
the AsyncHTTPClient call to the banker"""
if response.error:
print ("Request Error!")
else:
print ("Request response OK")
print response.body
# ----- Budget allocation class do top up budget for bid agent account
class BudgetControl(object):
"""send rest requests to the banker to pace the budget)"""
def start(self, cfgObj):
"""config pacer"""
self.body = '{"USD/1M": ' + str(cfgObj["Banker"]["Budget"]) + '}'
self.headers = {"Accept": "application/json"}
self.url = "http://" + cfgObj["Banker"]["Ip"]
self.url = self.url + ":" + str(cfgObj["Banker"]["Port"])
acc = cfgObj["ACS"]["Config"]["account"]
self.url = self.url + "/v1/accounts/" + acc[0]+":"+acc[1] + "/balance"
self.http_client = AsyncHTTPClient()
# register with ACS
self.acs_register(cfgObj["ACS"])
# call the first budget pace request
self.http_request()
def http_request(self):
"""called periodically to updated the budget"""
try:
print("Budgeting: " + self.body)
self.http_client.fetch(self.url, callback=handle_async_request, method='POST', headers=self.headers, body=self.body)
except:
print("pacing - Failed!")
def acs_register(self, cfgObj):
"""calls Agent configurations server to set up this agent"""
url = "http://" + cfgObj["Ip"]
url = url + ":" + str(cfgObj["Port"])
url = url + "/v1/agents/my_http_config/config"
data = json.dumps(cfgObj["Config"])
# send request to ACS
try:
print("ACS reg'ing: " + data)
self.http_client.fetch(url, callback=handle_async_request, method='POST', headers=self.headers, body=data)
except:
print("ACS registration failed")
# ----- test function
def tornado_bidder_run():
"""runs httpapi bidder agent"""
# bind tcp port to launch processes on requests
sockets = netutil.bind_sockets(CONFIG_OBJ["Bidder"]["Port"])
# fork working processes
process.fork_processes(0)
# Tornado app implementation
app = Application([url(r"/", TornadoFixPriceBidAgentRequestHandler)])
# start http servers and attach the web app to it
server = httpserver.HTTPServer(app)
server.add_sockets(sockets)
# perform following actions only in the parent process
process_counter = process.task_id()
if (process_counter == 0):
# run dummy ad server
adserver_win = Application([url(r"/", TornadoDummyRequestHandler)])
winport = CONFIG_OBJ["Bidder"]["Win"]
adserver_win.listen(winport)
adserver_evt = Application([url(r"/", TornadoDummyRequestHandler)])
evtport = CONFIG_OBJ["Bidder"]["Event"]
adserver_evt.listen(evtport)
# --instantiate budget pacer
pacer = BudgetControl()
pacer.start(CONFIG_OBJ)
# add periodic event to call pacer
PeriodicCallback(pacer.http_request, CONFIG_OBJ["Banker"]["Period"]).start()
# main io loop. it will loop waiting for requests
IOLoop.instance().start()
# run test of this module
if __name__ == '__main__':
tornado_bidder_run()
| 5,963
|
938
|
<filename>rabbit-base/src/main/java/com/susion/rabbit/base/greendao/RabbitAppStartSpeedInfoDao.java
package com.susion.rabbit.base.greendao;
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.internal.DaoConfig;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseStatement;
import com.susion.rabbit.base.entities.RabbitAppStartSpeedInfo;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "RABBIT_APP_START_SPEED_INFO".
*/
public class RabbitAppStartSpeedInfoDao extends AbstractDao<RabbitAppStartSpeedInfo, Long> {
public static final String TABLENAME = "RABBIT_APP_START_SPEED_INFO";
/**
* Properties of entity RabbitAppStartSpeedInfo.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property Time = new Property(1, long.class, "time", false, "TIME");
public final static Property CreateStartTime = new Property(2, long.class, "createStartTime", false, "CREATE_START_TIME");
public final static Property CreateEndTime = new Property(3, long.class, "createEndTime", false, "CREATE_END_TIME");
public final static Property FullShowCostTime = new Property(4, long.class, "fullShowCostTime", false, "FULL_SHOW_COST_TIME");
}
public RabbitAppStartSpeedInfoDao(DaoConfig config) {
super(config);
}
public RabbitAppStartSpeedInfoDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}
/** Creates the underlying database table. */
public static void createTable(Database db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"RABBIT_APP_START_SPEED_INFO\" (" + //
"\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id
"\"TIME\" INTEGER NOT NULL ," + // 1: time
"\"CREATE_START_TIME\" INTEGER NOT NULL ," + // 2: createStartTime
"\"CREATE_END_TIME\" INTEGER NOT NULL ," + // 3: createEndTime
"\"FULL_SHOW_COST_TIME\" INTEGER NOT NULL );"); // 4: fullShowCostTime
}
/** Drops the underlying database table. */
public static void dropTable(Database db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"RABBIT_APP_START_SPEED_INFO\"";
db.execSQL(sql);
}
@Override
protected final void bindValues(DatabaseStatement stmt, RabbitAppStartSpeedInfo entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
stmt.bindLong(2, entity.getTime());
stmt.bindLong(3, entity.getCreateStartTime());
stmt.bindLong(4, entity.getCreateEndTime());
stmt.bindLong(5, entity.getFullShowCostTime());
}
@Override
protected final void bindValues(SQLiteStatement stmt, RabbitAppStartSpeedInfo entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
stmt.bindLong(2, entity.getTime());
stmt.bindLong(3, entity.getCreateStartTime());
stmt.bindLong(4, entity.getCreateEndTime());
stmt.bindLong(5, entity.getFullShowCostTime());
}
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
@Override
public RabbitAppStartSpeedInfo readEntity(Cursor cursor, int offset) {
RabbitAppStartSpeedInfo entity = new RabbitAppStartSpeedInfo( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.getLong(offset + 1), // time
cursor.getLong(offset + 2), // createStartTime
cursor.getLong(offset + 3), // createEndTime
cursor.getLong(offset + 4) // fullShowCostTime
);
return entity;
}
@Override
public void readEntity(Cursor cursor, RabbitAppStartSpeedInfo entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setTime(cursor.getLong(offset + 1));
entity.setCreateStartTime(cursor.getLong(offset + 2));
entity.setCreateEndTime(cursor.getLong(offset + 3));
entity.setFullShowCostTime(cursor.getLong(offset + 4));
}
@Override
protected final Long updateKeyAfterInsert(RabbitAppStartSpeedInfo entity, long rowId) {
entity.setId(rowId);
return rowId;
}
@Override
public Long getKey(RabbitAppStartSpeedInfo entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
@Override
public boolean hasKey(RabbitAppStartSpeedInfo entity) {
return entity.getId() != null;
}
@Override
protected final boolean isEntityUpdateable() {
return true;
}
}
| 2,127
|
17,242
|
// Copyright 2019 The MediaPipe Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.mediapipe.apps.handtrackinggpu;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import com.google.mediapipe.formats.proto.LandmarkProto.NormalizedLandmark;
import com.google.mediapipe.formats.proto.LandmarkProto.NormalizedLandmarkList;
import com.google.mediapipe.framework.AndroidPacketCreator;
import com.google.mediapipe.framework.Packet;
import com.google.mediapipe.framework.PacketGetter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** Main activity of MediaPipe hand tracking app. */
public class MainActivity extends com.google.mediapipe.apps.basic.MainActivity {
private static final String TAG = "MainActivity";
private static final String INPUT_NUM_HANDS_SIDE_PACKET_NAME = "num_hands";
private static final String INPUT_MODEL_COMPLEXITY = "model_complexity";
private static final String OUTPUT_LANDMARKS_STREAM_NAME = "hand_landmarks";
// Max number of hands to detect/process.
private static final int NUM_HANDS = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ApplicationInfo applicationInfo;
try {
applicationInfo =
getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
} catch (NameNotFoundException e) {
throw new AssertionError(e);
}
AndroidPacketCreator packetCreator = processor.getPacketCreator();
Map<String, Packet> inputSidePackets = new HashMap<>();
inputSidePackets.put(INPUT_NUM_HANDS_SIDE_PACKET_NAME, packetCreator.createInt32(NUM_HANDS));
if (applicationInfo.metaData.containsKey("modelComplexity")) {
inputSidePackets.put(
INPUT_MODEL_COMPLEXITY,
packetCreator.createInt32(applicationInfo.metaData.getInt("modelComplexity")));
}
processor.setInputSidePackets(inputSidePackets);
// To show verbose logging, run:
// adb shell setprop log.tag.MainActivity VERBOSE
if (Log.isLoggable(TAG, Log.VERBOSE)) {
processor.addPacketCallback(
OUTPUT_LANDMARKS_STREAM_NAME,
(packet) -> {
Log.v(TAG, "Received multi-hand landmarks packet.");
List<NormalizedLandmarkList> multiHandLandmarks =
PacketGetter.getProtoVector(packet, NormalizedLandmarkList.parser());
Log.v(
TAG,
"[TS:"
+ packet.getTimestamp()
+ "] "
+ getMultiHandLandmarksDebugString(multiHandLandmarks));
});
}
}
private String getMultiHandLandmarksDebugString(List<NormalizedLandmarkList> multiHandLandmarks) {
if (multiHandLandmarks.isEmpty()) {
return "No hand landmarks";
}
String multiHandLandmarksStr = "Number of hands detected: " + multiHandLandmarks.size() + "\n";
int handIndex = 0;
for (NormalizedLandmarkList landmarks : multiHandLandmarks) {
multiHandLandmarksStr +=
"\t#Hand landmarks for hand[" + handIndex + "]: " + landmarks.getLandmarkCount() + "\n";
int landmarkIndex = 0;
for (NormalizedLandmark landmark : landmarks.getLandmarkList()) {
multiHandLandmarksStr +=
"\t\tLandmark ["
+ landmarkIndex
+ "]: ("
+ landmark.getX()
+ ", "
+ landmark.getY()
+ ", "
+ landmark.getZ()
+ ")\n";
++landmarkIndex;
}
++handIndex;
}
return multiHandLandmarksStr;
}
}
| 1,622
|
655
|
//
// CardIOConfigurableTextFieldDelegate.h
// See the file "LICENSE.md" for the full license governing this code.
//
#import <Foundation/Foundation.h>
@interface CardIOConfigurableTextFieldDelegate : NSObject<UITextFieldDelegate> {
@private
BOOL numbersOnly;
NSInteger maxLength; // set to zero for no max length
}
@property(nonatomic, assign, readwrite) BOOL numbersOnly;
@property(nonatomic, assign, readwrite) NSInteger maxLength;
+ (BOOL)containsNumbersOnly:(NSString *)newText;
+ (NSInteger)lengthOfString:(NSString *)originalText afterChangingCharactersInRange:(NSRange)range replacementString:(NSString *)string;
+ (NSInteger)nonDigitsInTextField:(UITextField *)textField beforeOffset:(NSInteger)offset;
+ (UITextPosition *)positionInTextField:(UITextField *)textField after:(NSInteger)numberOfDigits;
+ (void)getSelectionInTextField:(UITextField *)textField
withSelectedTextRange:(UITextRange *)selectedTextRange
forStart:(NSInteger *)startSelectionOffset
forEnd:(NSInteger *)endSelectionOffset;
+ (void)vibrate;
@end
| 374
|
4,845
|
package cn.dev33.satoken.reactor.context;
import org.springframework.web.server.ServerWebExchange;
import cn.dev33.satoken.context.SaTokenContextForThreadLocalStorage;
import cn.dev33.satoken.context.SaTokenContextForThreadLocalStorage.Box;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.context.model.SaResponse;
import cn.dev33.satoken.context.model.SaStorage;
import cn.dev33.satoken.fun.SaFunction;
import cn.dev33.satoken.reactor.model.SaRequestForReactor;
import cn.dev33.satoken.reactor.model.SaResponseForReactor;
import cn.dev33.satoken.reactor.model.SaStorageForReactor;
/**
* Reactor上下文操作 [同步]
* @author kong
*
*/
public class SaReactorSyncHolder {
/**
* 写入上下文对象
* @param exchange see note
*/
public static void setContext(ServerWebExchange exchange) {
SaRequest request = new SaRequestForReactor(exchange.getRequest());
SaResponse response = new SaResponseForReactor(exchange.getResponse());
SaStorage storage = new SaStorageForReactor(exchange);
SaTokenContextForThreadLocalStorage.setBox(request, response, storage);
}
/**
* 获取上下文对象
* @return see note
*/
public static ServerWebExchange getContext() {
Box box = SaTokenContextForThreadLocalStorage.getBoxNotNull();
return (ServerWebExchange)box.getStorage().getSource();
}
/**
* 清除上下文对象
*/
public static void clearContext() {
SaTokenContextForThreadLocalStorage.clearBox();
}
/**
* 写入上下文对象, 并在执行函数后将其清除
* @param exchange see note
* @param fun see note
*/
public static void setContext(ServerWebExchange exchange, SaFunction fun) {
try {
setContext(exchange);
fun.run();
} finally {
clearContext();
}
}
}
| 663
|
1,408
|
<reponame>Nuvoton-Israel/arm-trusted-firmware<filename>plat/nvidia/tegra/soc/t194/drivers/se/se_private.h<gh_stars>1000+
/*
* Copyright (c) 2020, ARM Limited and Contributors. All rights reserved.
* Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef SE_PRIVATE_H
#define SE_PRIVATE_H
#include <lib/utils_def.h>
#include <tegra_def.h>
/* SE0 security register */
#define SE0_SECURITY U(0x18)
#define SE0_SECURITY_SE_SOFT_SETTING (((uint32_t)1) << 16U)
/* SE0 SHA GSCID register */
#define SE0_SHA_GSCID_0 U(0x100)
/* SE0 config register */
#define SE0_SHA_CONFIG U(0x104)
#define SE0_SHA_TASK_CONFIG U(0x108)
#define SE0_SHA_CONFIG_HW_INIT_HASH (((uint32_t)1) << 0U)
#define SE0_SHA_CONFIG_HW_INIT_HASH_DISABLE U(0)
#define SE0_CONFIG_ENC_ALG_SHIFT U(12)
#define SE0_CONFIG_ENC_ALG_SHA \
(((uint32_t)3) << SE0_CONFIG_ENC_ALG_SHIFT)
#define SE0_CONFIG_DEC_ALG_SHIFT U(8)
#define SE0_CONFIG_DEC_ALG_NOP \
(((uint32_t)0) << SE0_CONFIG_DEC_ALG_SHIFT)
#define SE0_CONFIG_DST_SHIFT U(2)
#define SE0_CONFIG_DST_HASHREG \
(((uint32_t)1) << SE0_CONFIG_DST_SHIFT)
#define SHA256_HASH_SIZE_BYTES U(256)
#define SE0_CONFIG_ENC_MODE_SHIFT U(24)
#define SE0_CONFIG_ENC_MODE_SHA256 \
(((uint32_t)5) << SE0_CONFIG_ENC_MODE_SHIFT)
/* SHA input message length */
#define SE0_IN_ADDR U(0x10c)
#define SE0_IN_HI_ADDR_HI U(0x110)
#define SE0_IN_HI_ADDR_HI_0_MSB_SHIFT U(24)
/* SHA input message length */
#define SE0_SHA_MSG_LENGTH_0 U(0x11c)
#define SE0_SHA_MSG_LENGTH_1 U(0x120)
#define SE0_SHA_MSG_LENGTH_2 U(0x124)
#define SE0_SHA_MSG_LENGTH_3 U(0x128)
/* SHA input message left */
#define SE0_SHA_MSG_LEFT_0 U(0x12c)
#define SE0_SHA_MSG_LEFT_1 U(0x130)
#define SE0_SHA_MSG_LEFT_2 U(0x134)
#define SE0_SHA_MSG_LEFT_3 U(0x138)
/* SE HASH-RESULT */
#define SE0_SHA_HASH_RESULT_0 U(0x13c)
/* SE OPERATION */
#define SE0_OPERATION_REG_OFFSET U(0x17c)
#define SE0_UNIT_OPERATION_PKT_LASTBUF_SHIFT U(16)
#define SE0_UNIT_OPERATION_PKT_LASTBUF_FIELD \
((uint32_t)0x1 << SE0_UNIT_OPERATION_PKT_LASTBUF_SHIFT)
#define SE0_OPERATION_SHIFT U(0)
#define SE0_OP_START \
(((uint32_t)0x1) << SE0_OPERATION_SHIFT)
/* SE Interrupt */
#define SE0_SHA_INT_ENABLE U(0x180)
#define SE0_INT_STATUS_REG_OFFSET U(0x184)
#define SE0_INT_OP_DONE_SHIFT U(4)
#define SE0_INT_OP_DONE_CLEAR \
(((uint32_t)0U) << SE0_INT_OP_DONE_SHIFT)
#define SE0_INT_OP_DONE(x) \
((x) & (((uint32_t)0x1U) << SE0_INT_OP_DONE_SHIFT))
/* SE SHA Status */
#define SE0_SHA_STATUS_0 U(0x188)
#define SE0_SHA_STATUS_IDLE U(0)
/* SE error status */
#define SE0_ERR_STATUS_REG_OFFSET U(0x18c)
#define SE0_ERR_STATUS_CLEAR U(0)
/* SE error status */
#define SECURE_SCRATCH_TZDRAM_SHA256_HASH_START SECURE_SCRATCH_RSV68_LO
#define SECURE_SCRATCH_TZDRAM_SHA256_HASH_END SECURE_SCRATCH_RSV71_HI
/* SE0_INT_ENABLE_0 */
#define SE0_INT_ENABLE U(0x88)
#define SE0_DISABLE_ALL_INT U(0x0)
/* SE0_INT_STATUS_0 */
#define SE0_INT_STATUS U(0x8C)
#define SE0_CLEAR_ALL_INT_STATUS U(0x3F)
/* SE0_SHA_INT_STATUS_0 */
#define SHA_INT_STATUS U(0x184)
#define SHA_SE_OP_DONE (U(1) << 4)
/* SE0_SHA_ERR_STATUS_0 */
#define SHA_ERR_STATUS U(0x18C)
/* SE0_AES0_INT_STATUS_0 */
#define AES0_INT_STATUS U(0x2F0)
#define AES0_SE_OP_DONE (U(1) << 4)
/* SE0_AES0_ERR_STATUS_0 */
#define AES0_ERR_STATUS U(0x2F8)
/* SE0_AES1_INT_STATUS_0 */
#define AES1_INT_STATUS U(0x4F0)
/* SE0_AES1_ERR_STATUS_0 */
#define AES1_ERR_STATUS U(0x4F8)
/* SE0_RSA_INT_STATUS_0 */
#define RSA_INT_STATUS U(0x758)
/* SE0_RSA_ERR_STATUS_0 */
#define RSA_ERR_STATUS U(0x760)
/* SE0_AES0_OPERATION_0 */
#define AES0_OPERATION U(0x238)
#define OP_MASK_BITS U(0x7)
#define SE_OP_CTX_SAVE U(0x3)
/* SE0_AES0_CTX_SAVE_CONFIG_0 */
#define CTX_SAVE_CONFIG U(0x2D4)
/* SE0_AES0_CTX_SAVE_AUTO_STATUS_0 */
#define CTX_SAVE_AUTO_STATUS U(0x300)
#define CTX_SAVE_AUTO_SE_READY U(0xFF)
#define CTX_SAVE_AUTO_SE_BUSY (U(0x1) << 31)
/* SE0_AES0_CTX_SAVE_AUTO_CTRL_0 */
#define CTX_SAVE_AUTO_CTRL U(0x304)
#define SE_CTX_SAVE_AUTO_EN (U(0x1) << 0)
#define SE_CTX_SAVE_AUTO_LOCK_EN (U(0x1) << 1)
/* SE0_AES0_CTX_SAVE_AUTO_START_ADDR_0 */
#define CTX_SAVE_AUTO_START_ADDR U(0x308)
/* SE0_AES0_CTX_SAVE_AUTO_START_ADDR_HI_0 */
#define CTX_SAVE_AUTO_START_ADDR_HI U(0x30C)
/*******************************************************************************
* Inline functions definition
******************************************************************************/
static inline uint32_t tegra_se_read_32(uint32_t offset)
{
return mmio_read_32((uint32_t)(TEGRA_SE0_BASE + offset));
}
static inline void tegra_se_write_32(uint32_t offset, uint32_t val)
{
mmio_write_32((uint32_t)(TEGRA_SE0_BASE + offset), val);
}
#endif /* SE_PRIVATE_H */
| 2,536
|
1,056
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.websvc.saas.ui.actions;
import java.util.ArrayList;
import java.util.List;
import org.netbeans.modules.websvc.saas.model.Saas;
import org.netbeans.modules.websvc.saas.model.SaasServicesModel;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.util.actions.NodeAction;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import org.openide.nodes.Node;
import org.openide.util.RequestProcessor;
/**
* Deletes a user-defined web service.
*
* @author nam
*/
public class DeleteServiceAction extends NodeAction {
@Override
protected boolean enable(Node[] nodes) {
for (Node n : nodes) {
Saas saas = n.getLookup().lookup(Saas.class);
if (saas == null || !saas.isUserDefined()) {
return false;
}
}
return true;
}
@Override
public org.openide.util.HelpCtx getHelpCtx() {
return HelpCtx.DEFAULT_HELP;
}
@Override
protected String iconResource() {
return "org/netbeans/modules/websvc/saas/ui/resources/ActionIcon.gif"; // NOI18N
}
@Override
public String getName() {
return NbBundle.getMessage(DeleteServiceAction.class, "DELETE"); // NOI18N
}
@Override
protected void performAction(Node[] nodes) {
final List<Saas> saases = new ArrayList<Saas>();
for (Node n : nodes) {
Saas saas = n.getLookup().lookup(Saas.class);
saases.add(saas);
}
String msg = NbBundle.getMessage(this.getClass(), "WS_DELETE", saases); // NOI18N
NotifyDescriptor d = new NotifyDescriptor.Confirmation(msg, NotifyDescriptor.YES_NO_OPTION);
Object response = DialogDisplayer.getDefault().notify(d);
if (NotifyDescriptor.YES_OPTION.equals(response)) {
RequestProcessor.getDefault().post(new Runnable() {
@Override
public void run() {
for (Saas saas : saases) {
SaasServicesModel.getInstance().removeService(saas);
}
}
});
}
}
@Override
protected boolean asynchronous() {
return false;
}
}
| 1,205
|
782
|
<filename>main/boofcv-feature/src/main/java/boofcv/alg/background/BackgroundAlgorithmBasic.java
/*
* Copyright (c) 2021, <NAME>. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.alg.background;
/**
* <p>
* Performs background subtraction on an image using the very simple per-pixel "basic" model, as described in [1].
* A simple image is used to represent the background. Each pixel is updated individually using the formula below:<br>
* <br>
* B(i+1) = (1-α)*B(i) + αI(i)<br>
* Where B is the background image, I is the current observed image, and α is the learning rate 0 to 1.
* Where 0 is static and 1 is instant.
* </p>
* <p>
* If a specific pixel has not been observed before it will be set to the value of the equivalent pixel in the
* input image.
* </p>
*
* <p>
* [1] <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2010).
* Comparative study of background subtraction algorithms. Journal of Electronic Imaging, 19(3), 033003-033003.
* </p>
*
* @author <NAME>
*/
public interface BackgroundAlgorithmBasic {
/**
* Returns the learning rate.
*
* @return 0 (slow) to 1 (fast)
*/
float getLearnRate();
/**
* Specifies the learning rate
*
* @param learnRate 0 (slow) to 1 (fast)
*/
void setLearnRate( float learnRate );
/**
* Returns the threshold for background/moving object.
*
* @return background threshold
*/
float getThreshold();
/**
* Sets the threshold for background/moving object
*
* @param threshold background threshold
*/
void setThreshold( float threshold );
}
| 646
|
589
|
<reponame>nurely/lxdui
from app.api.lib import cert, log as logger
import os
import pathlib
import unittest
import logging
log = logging.getLogger(__name__)
class TestConfig(unittest.TestCase):
@classmethod
def setUp(cls):
logger.Log('test')
pass
@classmethod
def tearDown(cls):
pass
def test_logger(self):
l = logger.Log('test')
self.assertIsInstance(l, logger.Log)
def test_cert(self):
c = cert.Certificate()
print('key file = {}'.format(c.key_file))
print('cert file = {}'.format(c.cert_file))
print('key = {}'.format(c.key))
print('cert = {}'.format(c.cert))
self.assertEqual(c.key_file, 'client.key')
self.assertEqual(c.cert_file, 'client.crt')
self.assertRegex(bytes.decode(c.key), r'^-----BEGIN PRIVATE KEY-----.*')
self.assertRegex(bytes.decode(c.cert), r'^-----BEGIN CERTIFICATE-----.*')
def test_save(self):
def delete(file):
if pathlib.Path(file).exists():
os.remove(file)
c = cert.Certificate()
key = os.path.abspath(os.path.join('../conf', c.key_file))
crt = os.path.abspath(os.path.join('../conf', c.cert_file))
delete(key)
delete(crt)
c.save(key, c.key)
c.save(crt, c.cert)
self.assertEqual(os.stat(key).st_size, c.key.__len__() )
self.assertEqual(os.stat(crt).st_size, c.cert.__len__())
if __name__ == '__main__':
unittest.main()
| 721
|
2,399
|
<reponame>nue8080/SJMediaCacheServer<filename>Example/Pods/SJBaseVideoPlayer/SJBaseVideoPlayer/Common/Interfaces/SJReachabilityDefines.h
//
// SJReachabilityDefines
// Project
//
// Created by 畅三江 on 2018/6/1.
// Copyright © 2018年 changsanjiang. All rights reserved.
//
#ifndef SJNetworkStatus_h
#define SJNetworkStatus_h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol SJReachabilityObserver;
/**
This enumeration lists the three state values of the network.
It is used to identify the current network state. You can obtain the current network state as follows:
这个枚举列出了网络的3种状态值, 用来标识当前的网络状态, 你可以像下面这样获取当前的网络状态:
```
_videoPlayer.networkStatus;
```
*/
typedef NS_ENUM(NSInteger, SJNetworkStatus) {
SJNetworkStatus_NotReachable = 0,
SJNetworkStatus_ReachableViaWWAN = 1,
SJNetworkStatus_ReachableViaWiFi = 2
};
@protocol SJReachability <NSObject>
- (id<SJReachabilityObserver>)getObserver;
@property (nonatomic, readonly) SJNetworkStatus networkStatus;
@property (nonatomic, strong, readonly) NSString *networkSpeedStr;
- (void)startRefresh;
- (void)stopRefresh;
@end
@protocol SJReachabilityObserver <NSObject>
@property (nonatomic, copy, nullable) void(^networkStatusDidChangeExeBlock)(id<SJReachability> r);
@property (nonatomic, copy, nullable) void(^networkSpeedDidChangeExeBlock)(id<SJReachability> r);
@end
NS_ASSUME_NONNULL_END
#endif /* SJNetworkStatus_h */
| 574
|
16,500
|
#include <os.h>
ModLink::~ModLink(){
}
ModLink::ModLink(char* n) : File(n,TYPE_FILE)
{
fsm.addFile("/sys/mods/",this);
}
u32 ModLink::open(u32 flag){
return RETURN_OK;
}
u32 ModLink::close(){
return RETURN_OK;
}
u32 ModLink::read(u8* buffer,u32 size){
return NOT_DEFINED;
}
u32 ModLink::write(u8* buffer,u32 size){
return NOT_DEFINED;
}
u32 ModLink::ioctl(u32 id,u8* buffer){
return NOT_DEFINED;
}
u32 ModLink::remove(){
delete this;
}
void ModLink::scan(){
}
| 227
|
771
|
<reponame>JustWon/semantic_segmap<filename>segmappy/bin/analyse_database.py
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
import os
import ensure_segmappy_is_installed
from segmappy import Config
from segmappy.tools.classifiertools import get_default_dataset, get_default_preprocessor
# read config file
configfile = "default_training.ini"
config = Config(configfile)
# load dataset and preprocessor
dataset = get_default_dataset(config)
preprocessor = get_default_preprocessor(config)
segments, positions, classes, n_classes, _, _, _ = dataset.load(
preprocessor=preprocessor
)
# Class size distribution
class_histogram, _ = np.histogram(classes, bins=range(n_classes + 1))
class_size_histogram, bins = np.histogram(
class_histogram, bins=range(np.max(class_histogram) + 2)
)
plt.figure(1)
plt.bar(bins[:-1], class_size_histogram)
# Segment size distribution
segments_size = []
for segment in segments:
segments_size.append(np.max(segment, axis=0) - np.min(segment, axis=0))
segments_size = np.array(segments_size)
plt.figure(2)
segments_size = np.ceil(segments_size)
for axis in range(segments_size.shape[1]):
axis_sizes = segments_size[:, axis]
sizes_histogram, bins = np.histogram(
axis_sizes, bins=np.arange(np.min(axis_sizes), np.max(axis_sizes) + 2)
)
sizes_cdf = np.cumsum(sizes_histogram) / float(np.sum(sizes_histogram))
plt.subplot(3, 1, axis + 1)
plt.plot(bins[:-1], sizes_cdf)
plt.show()
| 568
|
831
|
<gh_stars>100-1000
/*
* Copyright (C) 2017 The Android Open Source Project
*
* 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.android.tools.idea.navigator.nodes.ndk.includes.utils;
import org.junit.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import static com.google.common.truth.Truth.assertThat;
public class TestLexicalIncludePaths {
@Test
public void testCommonRelativeIncludePath1() {
List<String> paths = new ArrayList<>();
paths.add("usr/one/two");
paths.add("usr/one/three");
String common = LexicalIncludePaths.findCommonParentFolder(paths);
assertThat(common).isEqualTo("usr/one");
}
@Test
public void testCommonRelativeIncludePath2() {
List<String> paths = new ArrayList<>();
paths.add("usr/one/two");
paths.add("usr/one/two");
String common = LexicalIncludePaths.findCommonParentFolder(paths);
assertThat(common).isEqualTo("usr/one/two");
}
@Test
public void testCommonRelativeIncludePath3() {
List<String> paths = new ArrayList<>();
paths.add("/usr/one/two");
paths.add("/usr/one/three");
String common = LexicalIncludePaths.findCommonParentFolder(paths);
assertThat(common).isEqualTo("/usr/one");
}
@Test
public void testCommonRelativeIncludePathWindowsDifferentDrive() {
List<String> paths = new ArrayList<>();
paths.add("c:/usr/one/two");
paths.add("d:/usr/one/three");
String common = LexicalIncludePaths.findCommonParentFolder(paths);
assertThat(common).isEqualTo("");
}
@Test
public void testCommonRelativeIncludePathWindowsSameDrive() {
List<String> paths = new ArrayList<>();
paths.add("c:/usr/one/two");
paths.add("c:/usr/one/three");
String common = LexicalIncludePaths.findCommonParentFolder(paths);
assertThat(common).isEqualTo("c:/usr/one");
}
@Test
public void testCommonRelativeIncludePathEmptyList() {
List<String> paths = new ArrayList<>();
String common = LexicalIncludePaths.findCommonParentFolder(paths);
assertThat(common).isEqualTo("");
}
@Test
public void testHeaderExtension() {
assertThat(LexicalIncludePaths.hasHeaderExtension("header")).isTrue();
assertThat(LexicalIncludePaths.hasHeaderExtension("header.h")).isTrue();
assertThat(LexicalIncludePaths.hasHeaderExtension("header.inl")).isTrue();
assertThat(LexicalIncludePaths.hasHeaderExtension("header.cpp")).isFalse();
}
@Test
public void testMatchRegex() {
assertThat(LexicalIncludePaths.matchFolderToRegex(Pattern.compile("/.*"), new File("\\header.h")).matches()).isTrue();
assertThat(LexicalIncludePaths.matchFolderToRegex(Pattern.compile("/.*"), new File("/header.h")).matches()).isTrue();
}
@Test
public void testTrimPathSeparator() {
assertThat(LexicalIncludePaths.trimPathSeparators("a")).isEqualTo("a");
assertThat(LexicalIncludePaths.trimPathSeparators("/a")).isEqualTo("a");
assertThat(LexicalIncludePaths.trimPathSeparators("a/")).isEqualTo("a");
assertThat(LexicalIncludePaths.trimPathSeparators("/a/")).isEqualTo("a");
}
}
| 1,264
|
868
|
/*
* Copyright 2020 OmniSci, 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 "ParquetInPlaceEncoder.h"
namespace foreign_storage {
// ParquetFixedLengthEncoder is used in two separate use cases: metadata
// scanning & chunk loading. During metadata scan the type of metadata (& in
// some cases data) must be known, while during chunk loading only the type of
// data needs to be known.
//
// The following semantics apply to the templated types below.
//
// At metadata scan:
// V - type of metadata (for loading metadata)
// T - physical type of parquet data
//
// At chunk load:
// V - type of data (to load data)
// T - physical type of parquet data
// NullType - the type to use for encoding nulls
template <typename V, typename T, typename NullType = V>
class ParquetFixedLengthEncoder : public TypedParquetInPlaceEncoder<V, T, NullType>,
public ParquetMetadataValidator {
public:
ParquetFixedLengthEncoder(Data_Namespace::AbstractBuffer* buffer,
const ColumnDescriptor* column_desciptor,
const parquet::ColumnDescriptor* parquet_column_descriptor)
: TypedParquetInPlaceEncoder<V, T, NullType>(buffer,
column_desciptor,
parquet_column_descriptor) {}
ParquetFixedLengthEncoder(Data_Namespace::AbstractBuffer* buffer,
const size_t omnisci_data_type_byte_size,
const size_t parquet_data_type_byte_size)
: TypedParquetInPlaceEncoder<V, T, NullType>(buffer,
omnisci_data_type_byte_size,
parquet_data_type_byte_size) {}
void encodeAndCopy(const int8_t* parquet_data_bytes,
int8_t* omnisci_data_bytes) override {
const auto& parquet_data_value = reinterpret_cast<const T*>(parquet_data_bytes)[0];
auto& omnisci_data_value = reinterpret_cast<V*>(omnisci_data_bytes)[0];
omnisci_data_value = parquet_data_value;
}
void validate(std::shared_ptr<parquet::Statistics> stats,
const SQLTypeInfo& column_type) const override {
validateIntegralOrFloatingPointMetadata(stats, column_type);
}
void validate(const int8_t* parquet_data,
const int64_t j,
const SQLTypeInfo& column_type) const override {
const auto& parquet_data_value = reinterpret_cast<const T*>(parquet_data)[j];
validateIntegralOrFloatingPointValue(parquet_data_value, column_type);
}
bool encodingIsIdentityForSameTypes() const override { return true; }
private:
template <
typename TT = T,
std::enable_if_t<(!std::is_integral<TT>::value || std::is_same<TT, bool>::value) &&
!std::is_floating_point<TT>::value,
int> = 0>
void validateIntegralOrFloatingPointValue(const T& value,
const SQLTypeInfo& column_type) const {
// do nothing when type `T` is non-integral and non-floating-point (case
// for which this can happen are when `T` is bool)
}
template <typename TT = T, std::enable_if_t<std::is_floating_point<TT>::value, int> = 0>
void validateIntegralOrFloatingPointValue(const T& value,
const SQLTypeInfo& column_type) const {
if (column_type.is_fp()) {
FloatPointValidator<T>::validateValue(value, column_type);
} else {
UNREACHABLE();
}
}
template <
typename TT = T,
std::enable_if_t<std::is_integral<TT>::value && !std::is_same<TT, bool>::value,
int> = 0>
void validateIntegralOrFloatingPointValue(const T& value,
const SQLTypeInfo& column_type) const {
if (column_type.is_integer()) {
IntegralFixedLengthBoundsValidator<T>::validateValue(value, column_type);
} else if (column_type.is_timestamp()) {
TimestampBoundsValidator<T>::validateValue(value, column_type);
}
}
void validateIntegralOrFloatingPointMetadata(std::shared_ptr<parquet::Statistics> stats,
const SQLTypeInfo& column_type) const {
if (!column_type.is_integer() && !column_type.is_timestamp() &&
!column_type.is_fp()) {
return;
}
auto [unencoded_stats_min, unencoded_stats_max] =
TypedParquetInPlaceEncoder<V, T, NullType>::getUnencodedStats(stats);
validateIntegralOrFloatingPointValue(unencoded_stats_min, column_type);
validateIntegralOrFloatingPointValue(unencoded_stats_max, column_type);
}
};
// ParquetUnsignedFixedLengthEncoder is used in two separate use cases:
// metadata scanning & chunk loading. During metadata scan the type of
// metadata (& in some cases data) must be known, while during chunk loading
// only the type of data needs to be known.
//
// The following semantics apply to the templated types below.
//
// At metadata scan:
// V - type of metadata (for loading metadata)
// T - physical type of parquet data
// U - unsigned type that the parquet data represents
//
// At chunk load:
// V - type of data (to load data)
// T - physical type of parquet data
// U - unsigned type that the parquet data represents
// NullType - the type to use for encoding nulls
template <typename V, typename T, typename U, typename NullType = V>
class ParquetUnsignedFixedLengthEncoder
: public TypedParquetInPlaceEncoder<V, T, NullType>,
public ParquetMetadataValidator {
public:
ParquetUnsignedFixedLengthEncoder(
Data_Namespace::AbstractBuffer* buffer,
const ColumnDescriptor* column_desciptor,
const parquet::ColumnDescriptor* parquet_column_descriptor)
: TypedParquetInPlaceEncoder<V, T, NullType>(buffer,
column_desciptor,
parquet_column_descriptor) {}
ParquetUnsignedFixedLengthEncoder(Data_Namespace::AbstractBuffer* buffer,
const size_t omnisci_data_type_byte_size,
const size_t parquet_data_type_byte_size)
: TypedParquetInPlaceEncoder<V, T, NullType>(buffer,
omnisci_data_type_byte_size,
parquet_data_type_byte_size) {}
void encodeAndCopy(const int8_t* parquet_data_bytes,
int8_t* omnisci_data_bytes) override {
const auto& parquet_data_value = reinterpret_cast<const T*>(parquet_data_bytes)[0];
auto& omnisci_data_value = reinterpret_cast<V*>(omnisci_data_bytes)[0];
omnisci_data_value = static_cast<U>(parquet_data_value);
}
void validate(std::shared_ptr<parquet::Statistics> stats,
const SQLTypeInfo& column_type) const override {
if (!column_type.is_integer()) { // do not validate non-integral types
return;
}
auto [unencoded_stats_min, unencoded_stats_max] =
TypedParquetInPlaceEncoder<V, T, NullType>::getUnencodedStats(stats);
IntegralFixedLengthBoundsValidator<U>::validateValue(unencoded_stats_max,
column_type);
IntegralFixedLengthBoundsValidator<U>::validateValue(unencoded_stats_min,
column_type);
}
void validate(const int8_t* parquet_data,
const int64_t j,
const SQLTypeInfo& column_type) const override {
const auto& parquet_data_value = reinterpret_cast<const T*>(parquet_data)[j];
IntegralFixedLengthBoundsValidator<U>::validateValue(parquet_data_value, column_type);
}
};
} // namespace foreign_storage
| 3,561
|
1,350
|
<gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.billing.implementation;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.SimpleResponse;
import com.azure.core.util.Context;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.billing.fluent.BillingPropertiesClient;
import com.azure.resourcemanager.billing.fluent.models.BillingPropertyInner;
import com.azure.resourcemanager.billing.models.BillingProperties;
import com.azure.resourcemanager.billing.models.BillingProperty;
import com.fasterxml.jackson.annotation.JsonIgnore;
public final class BillingPropertiesImpl implements BillingProperties {
@JsonIgnore private final ClientLogger logger = new ClientLogger(BillingPropertiesImpl.class);
private final BillingPropertiesClient innerClient;
private final com.azure.resourcemanager.billing.BillingManager serviceManager;
public BillingPropertiesImpl(
BillingPropertiesClient innerClient, com.azure.resourcemanager.billing.BillingManager serviceManager) {
this.innerClient = innerClient;
this.serviceManager = serviceManager;
}
public BillingProperty get() {
BillingPropertyInner inner = this.serviceClient().get();
if (inner != null) {
return new BillingPropertyImpl(inner, this.manager());
} else {
return null;
}
}
public Response<BillingProperty> getWithResponse(Context context) {
Response<BillingPropertyInner> inner = this.serviceClient().getWithResponse(context);
if (inner != null) {
return new SimpleResponse<>(
inner.getRequest(),
inner.getStatusCode(),
inner.getHeaders(),
new BillingPropertyImpl(inner.getValue(), this.manager()));
} else {
return null;
}
}
public BillingProperty update(BillingPropertyInner parameters) {
BillingPropertyInner inner = this.serviceClient().update(parameters);
if (inner != null) {
return new BillingPropertyImpl(inner, this.manager());
} else {
return null;
}
}
public Response<BillingProperty> updateWithResponse(BillingPropertyInner parameters, Context context) {
Response<BillingPropertyInner> inner = this.serviceClient().updateWithResponse(parameters, context);
if (inner != null) {
return new SimpleResponse<>(
inner.getRequest(),
inner.getStatusCode(),
inner.getHeaders(),
new BillingPropertyImpl(inner.getValue(), this.manager()));
} else {
return null;
}
}
private BillingPropertiesClient serviceClient() {
return this.innerClient;
}
private com.azure.resourcemanager.billing.BillingManager manager() {
return this.serviceManager;
}
}
| 1,149
|
1,179
|
/// @copyright
/// Copyright (C) 2020 Assured Information Security, Inc.
///
/// @copyright
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// @copyright
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// @copyright
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
/// SOFTWARE.
#include "../../../mocks/basic_root_page_table_t.hpp"
#include <basic_alloc_page_t.hpp>
#include <basic_page_4k_t.hpp>
#include <basic_page_pool_t.hpp>
#include <basic_page_table_t.hpp>
#include <intrinsic_t.hpp>
#include <l0e_t.hpp>
#include <l1e_t.hpp>
#include <l2e_t.hpp>
#include <l3e_t.hpp>
#include <tls_t.hpp>
#include <bsl/convert.hpp>
#include <bsl/discard.hpp>
#include <bsl/dontcare_t.hpp>
#include <bsl/errc_type.hpp>
#include <bsl/safe_integral.hpp>
#include <bsl/ut.hpp>
namespace lib
{
/// @brief defines the page_pool_t used by the microkernel
using page_pool_t = lib::basic_page_pool_t<tls_t>;
/// @brief defines the root_page_table_t used by the microkernel
using root_page_table_t = lib::basic_root_page_table_t<
tls_t,
bsl::dontcare_t,
page_pool_t,
intrinsic_t,
l3e_t,
l2e_t,
l1e_t,
l0e_t>;
/// <!-- description -->
/// @brief Used to execute the actual checks. We put the checks in this
/// function so that we can validate the tests both at compile-time
/// and at run-time. If a bsl::ut_check fails, the tests will either
/// fail fast at run-time, or will produce a compile-time error.
///
/// <!-- inputs/outputs -->
/// @return Always returns bsl::exit_success.
///
[[nodiscard]] constexpr auto
tests() noexcept -> bsl::exit_code
{
bsl::ut_scenario{"initialize allocate fails"} = [&]() noexcept {
bsl::ut_given_at_runtime{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
constexpr auto phys{0x1000_u64};
bsl::ut_when{} = [&]() noexcept {
mut_page_pool.set_allocate<helpers::l3t_t>(nullptr, phys);
mut_tls.test_ret = UNIT_TEST_RPT_FAIL_INITIALIZE;
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(!mut_rpt.initialize(mut_tls, mut_page_pool));
};
};
};
};
bsl::ut_scenario{"initialize success"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(mut_rpt.initialize(mut_tls, mut_page_pool));
bsl::ut_cleanup{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
};
bsl::ut_scenario{"release without initialize"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
bsl::ut_then{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
bsl::ut_scenario{"release success"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(mut_rpt.initialize(mut_tls, mut_page_pool));
bsl::ut_cleanup{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
};
bsl::ut_scenario{"is_initialized"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
bsl::ut_when{} = [&]() noexcept {
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(!mut_rpt.is_initialized());
};
bsl::ut_required_step(mut_rpt.initialize(mut_tls, mut_page_pool));
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(mut_rpt.is_initialized());
};
mut_rpt.release(mut_tls, mut_page_pool);
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(!mut_rpt.is_initialized());
};
};
};
};
bsl::ut_scenario{"activate"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
intrinsic_t mut_intrinsic{};
bsl::ut_when{} = [&]() noexcept {
bsl::ut_required_step(mut_rpt.initialize(mut_tls, mut_page_pool));
mut_rpt.activate(mut_tls, mut_intrinsic);
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(mut_tls.active_rpt == &mut_rpt);
bsl::ut_check(mut_intrinsic.rpt().is_pos());
bsl::ut_cleanup{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
};
};
bsl::ut_scenario{"is_inactive"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
intrinsic_t mut_intrinsic{};
bsl::ut_when{} = [&]() noexcept {
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(mut_rpt.is_inactive(mut_tls));
};
bsl::ut_required_step(mut_rpt.initialize(mut_tls, mut_page_pool));
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(mut_rpt.is_inactive(mut_tls));
};
mut_rpt.activate(mut_tls, mut_intrinsic);
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(!mut_rpt.is_inactive(mut_tls));
};
bsl::ut_cleanup{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
};
bsl::ut_scenario{"spa"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
bsl::ut_when{} = [&]() noexcept {
bsl::ut_required_step(mut_rpt.initialize(mut_tls, mut_page_pool));
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(mut_rpt.spa().is_valid_and_checked());
bsl::ut_check(mut_rpt.spa().is_pos());
};
bsl::ut_cleanup{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
};
bsl::ut_scenario{"map 4k page"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
constexpr auto virt{0x1000_u64};
constexpr auto phys{0x1000_u64};
constexpr auto flgs{0x0_u64};
bool const explicit_unmap{};
bsl::dontcare_t mut_sys{};
bsl::ut_when{} = [&]() noexcept {
bsl::ut_required_step(mut_rpt.initialize(mut_tls, mut_page_pool));
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(mut_rpt.map<l0e_t>(
mut_tls, mut_page_pool, virt, phys, flgs, explicit_unmap, mut_sys));
};
bsl::ut_cleanup{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
};
bsl::ut_scenario{"map 4k page fails"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
constexpr auto virt{0x0_u64};
constexpr auto phys{0x1000_u64};
constexpr auto flgs{0x0_u64};
bool const explicit_unmap{};
bsl::dontcare_t mut_sys{};
bsl::ut_when{} = [&]() noexcept {
bsl::ut_required_step(mut_rpt.initialize(mut_tls, mut_page_pool));
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(!mut_rpt.map<l0e_t>(
mut_tls, mut_page_pool, virt, phys, flgs, explicit_unmap, mut_sys));
};
bsl::ut_cleanup{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
};
bsl::ut_scenario{"map 2m page"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
constexpr auto virt{0x200000_u64};
constexpr auto phys{0x200000_u64};
constexpr auto flgs{0x0_u64};
bool const explicit_unmap{};
bsl::dontcare_t mut_sys{};
bsl::ut_when{} = [&]() noexcept {
bsl::ut_required_step(mut_rpt.initialize(mut_tls, mut_page_pool));
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(mut_rpt.map<l1e_t>(
mut_tls, mut_page_pool, virt, phys, flgs, explicit_unmap, mut_sys));
};
bsl::ut_cleanup{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
};
bsl::ut_scenario{"map 2m page fails"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
constexpr auto virt{0x0_u64};
constexpr auto phys{0x200000_u64};
constexpr auto flgs{0x0_u64};
bool const explicit_unmap{};
bsl::dontcare_t mut_sys{};
bsl::ut_when{} = [&]() noexcept {
bsl::ut_required_step(mut_rpt.initialize(mut_tls, mut_page_pool));
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(!mut_rpt.map<l1e_t>(
mut_tls, mut_page_pool, virt, phys, flgs, explicit_unmap, mut_sys));
};
bsl::ut_cleanup{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
};
bsl::ut_scenario{"map 1g page"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
constexpr auto virt{0x40000000_u64};
constexpr auto phys{0x40000000_u64};
constexpr auto flgs{0x0_u64};
bool const explicit_unmap{};
bsl::dontcare_t mut_sys{};
bsl::ut_when{} = [&]() noexcept {
bsl::ut_required_step(mut_rpt.initialize(mut_tls, mut_page_pool));
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(mut_rpt.map<l2e_t>(
mut_tls, mut_page_pool, virt, phys, flgs, explicit_unmap, mut_sys));
};
bsl::ut_cleanup{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
};
bsl::ut_scenario{"map 1g page fails"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
constexpr auto virt{0x0_u64};
constexpr auto phys{0x40000000_u64};
constexpr auto flgs{0x0_u64};
bool const explicit_unmap{};
bsl::dontcare_t mut_sys{};
bsl::ut_when{} = [&]() noexcept {
bsl::ut_required_step(mut_rpt.initialize(mut_tls, mut_page_pool));
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(!mut_rpt.map<l2e_t>(
mut_tls, mut_page_pool, virt, phys, flgs, explicit_unmap, mut_sys));
};
bsl::ut_cleanup{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
};
bsl::ut_scenario{"allocate_page"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
constexpr auto virt{0x1000_u64};
constexpr auto flgs{0x0_u64};
bsl::dontcare_t mut_sys{};
bsl::ut_when{} = [&]() noexcept {
bsl::ut_required_step(mut_rpt.initialize(mut_tls, mut_page_pool));
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(
nullptr != mut_rpt.allocate_page<basic_page_4k_t>(
mut_tls, mut_page_pool, virt, flgs, mut_sys));
};
bsl::ut_cleanup{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
};
bsl::ut_scenario{"allocate_page fails"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
constexpr auto virt{0x0_u64};
constexpr auto flgs{0x0_u64};
bsl::dontcare_t mut_sys{};
bsl::ut_when{} = [&]() noexcept {
bsl::ut_required_step(mut_rpt.initialize(mut_tls, mut_page_pool));
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(
nullptr == mut_rpt.allocate_page<basic_page_4k_t>(
mut_tls, mut_page_pool, virt, flgs, mut_sys));
};
bsl::ut_cleanup{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
};
bsl::ut_scenario{"allocate_page<offset>"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
constexpr auto offs{0x1000_u64};
bsl::dontcare_t mut_sys{};
bsl::ut_when{} = [&]() noexcept {
bsl::ut_required_step(mut_rpt.initialize(mut_tls, mut_page_pool));
auto const page{
mut_rpt.allocate_page<offs.get()>(mut_tls, mut_page_pool, mut_sys)};
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(page.virt.is_valid());
bsl::ut_check(page.phys.is_valid());
};
bsl::ut_cleanup{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
};
bsl::ut_scenario{"allocate_page<offset> fails"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
constexpr auto offs{0x1000_u64};
bsl::dontcare_t mut_sys{};
bsl::ut_when{} = [&]() noexcept {
bsl::ut_required_step(mut_rpt.initialize(mut_tls, mut_page_pool));
mut_tls.test_virt = bsl::safe_u64::failure();
auto const page{
mut_rpt.allocate_page<offs.get()>(mut_tls, mut_page_pool, mut_sys)};
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(page.virt.is_invalid());
bsl::ut_check(page.phys.is_invalid());
};
bsl::ut_cleanup{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
};
bsl::ut_scenario{"unmap"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
bsl::dontcare_t mut_sys{};
constexpr auto virt1{0x1000_u64};
constexpr auto virt2{0x200000_u64};
constexpr auto virt3{0x40000000_u64};
constexpr auto phys1{0x1000_u64};
constexpr auto phys2{0x200000_u64};
constexpr auto phys3{0x40000000_u64};
bsl::ut_when{} = [&]() noexcept {
bsl::ut_required_step(mut_rpt.initialize(mut_tls, mut_page_pool));
bsl::ut_required_step(
mut_rpt.map<l0e_t>(mut_tls, mut_page_pool, virt1, phys1, {}, {}, mut_sys));
bsl::ut_required_step(
mut_rpt.map<l1e_t>(mut_tls, mut_page_pool, virt2, phys2, {}, {}, mut_sys));
bsl::ut_required_step(
mut_rpt.map<l2e_t>(mut_tls, mut_page_pool, virt3, phys3, {}, {}, mut_sys));
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(mut_rpt.unmap<l0e_t>(mut_tls, mut_page_pool, virt1));
bsl::ut_check(mut_rpt.unmap<l1e_t>(mut_tls, mut_page_pool, virt2));
bsl::ut_check(mut_rpt.unmap<l2e_t>(mut_tls, mut_page_pool, virt3));
};
bsl::ut_cleanup{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
};
bsl::ut_scenario{"unmap fails"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
bsl::dontcare_t mut_sys{};
constexpr auto virt1{0x1000_u64};
constexpr auto virt2{0x200000_u64};
constexpr auto virt3{0x40000000_u64};
constexpr auto phys1{0x1000_u64};
constexpr auto phys2{0x200000_u64};
constexpr auto phys3{0x40000000_u64};
bsl::ut_when{} = [&]() noexcept {
bsl::ut_required_step(mut_rpt.initialize(mut_tls, mut_page_pool));
bsl::ut_required_step(
mut_rpt.map<l0e_t>(mut_tls, mut_page_pool, virt1, phys1, {}, {}, mut_sys));
bsl::ut_required_step(
mut_rpt.map<l1e_t>(mut_tls, mut_page_pool, virt2, phys2, {}, {}, mut_sys));
bsl::ut_required_step(
mut_rpt.map<l2e_t>(mut_tls, mut_page_pool, virt3, phys3, {}, {}, mut_sys));
bsl::ut_then{} = [&]() noexcept {
bsl::ut_check(!mut_rpt.unmap<l0e_t>(mut_tls, mut_page_pool, {}));
bsl::ut_check(!mut_rpt.unmap<l1e_t>(mut_tls, mut_page_pool, {}));
bsl::ut_check(!mut_rpt.unmap<l2e_t>(mut_tls, mut_page_pool, {}));
};
bsl::ut_cleanup{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
};
bsl::ut_scenario{"entries"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
tls_t mut_tls{};
page_pool_t mut_page_pool{};
bsl::dontcare_t mut_sys{};
constexpr auto virt1{0x1000_u64};
constexpr auto virt2{0x200000_u64};
constexpr auto virt3{0x40000000_u64};
constexpr auto phys1{0x1000_u64};
constexpr auto phys2{0x200000_u64};
constexpr auto phys3{0x40000000_u64};
bsl::ut_when{} = [&]() noexcept {
bsl::ut_required_step(mut_rpt.initialize(mut_tls, mut_page_pool));
bsl::ut_required_step(
mut_rpt.map<l0e_t>(mut_tls, mut_page_pool, virt1, phys1, {}, {}, mut_sys));
bsl::ut_required_step(
mut_rpt.map<l1e_t>(mut_tls, mut_page_pool, virt2, phys2, {}, {}, mut_sys));
bsl::ut_required_step(
mut_rpt.map<l2e_t>(mut_tls, mut_page_pool, virt3, phys3, {}, {}, mut_sys));
bsl::ut_then{} = [&]() noexcept {
bsl::discard(mut_rpt.entries<l0e_t>(mut_tls, mut_page_pool, virt1));
bsl::discard(mut_rpt.entries<l1e_t>(mut_tls, mut_page_pool, virt2));
bsl::discard(mut_rpt.entries<l2e_t>(mut_tls, mut_page_pool, virt3));
};
bsl::ut_cleanup{} = [&]() noexcept {
mut_rpt.release(mut_tls, mut_page_pool);
};
};
};
};
bsl::ut_scenario{"add_tables"} = [&]() noexcept {
bsl::ut_given{} = [&]() noexcept {
root_page_table_t mut_rpt{};
root_page_table_t const rpt_src{};
basic_page_table_t<l3e_t> const l3e_src{};
bsl::ut_then{} = [&]() noexcept {
mut_rpt.add_tables({}, rpt_src);
mut_rpt.add_tables({}, &l3e_src);
};
};
};
return bsl::ut_success();
}
}
/// <!-- description -->
/// @brief Main function for this unit test. If a call to bsl::ut_check() fails
/// the application will fast fail. If all calls to bsl::ut_check() pass, this
/// function will successfully return with bsl::exit_success.
///
/// <!-- inputs/outputs -->
/// @return Always returns bsl::exit_success.
///
[[nodiscard]] auto
main() noexcept -> bsl::exit_code
{
bsl::enable_color();
static_assert(lib::tests() == bsl::ut_success());
return lib::tests();
}
| 14,879
|
438
|
{
"DESCRIPTION": "Rétablir le son pour un membre.",
"USAGE": "undeafen <membre>",
"NOT_VC": "Je ne peux pas rétablir le son de quelqu'un qui n'est pas dans un salon vocal.",
"SUCCESS": "*<@{{USER}}> n'est plus en sourdine*."
}
| 100
|
649
|
from aiohttpdemo_blog.forms import validate_login_form
from aiohttpdemo_blog.security import (
generate_password_hash,
check_password_hash
)
def test_security():
user_password = '<PASSWORD>'
hashed = generate_password_hash(user_password)
assert check_password_hash(user_password, hashed)
async def test_index_view(tables_and_data, client):
resp = await client.get('/')
assert resp.status == 200
async def test_login_form(tables_and_data, client):
invalid_form = {
'username': 'Joe',
'password': '<PASSWORD>'
}
valid_form = {
'username': 'Adam',
'password': '<PASSWORD>'
}
async with client.server.app['db_pool'].acquire() as conn:
error = await validate_login_form(conn, invalid_form)
assert error
no_error = await validate_login_form(conn, valid_form)
assert not no_error
async def test_login_view(tables_and_data, client):
invalid_form = {
'username': 'Joe',
'password': '<PASSWORD>'
}
valid_form = {
'username': 'Adam',
'password': '<PASSWORD>'
}
resp = await client.post('/login', data=invalid_form)
assert resp.status == 200
assert 'Invalid username' in await resp.text()
resp = await client.post('/login', data=valid_form)
assert resp.status == 200
assert 'Hi, Adam!' in await resp.text()
| 561
|
1,058
|
<reponame>wiltonlazary/snappydata
package io.snappydata.util.com.clearspring.analytics.stream;
/*
* Copyright (C) 2011 Clearspring Technologies, 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.
*/
/*
* Changes for SnappyData data platform.
*
* Portions Copyright (c) 2017-2019 TIBCO Software Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.clearspring.analytics.util.DoublyLinkedList;
import com.clearspring.analytics.util.ListNode2;
import com.clearspring.analytics.util.Pair;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
/**
* Based on the <i>Space-Saving</i> algorithm and the <i>Stream-Summary</i> data
* structure as described in: <i>Efficient Computation of Frequent and Top-k
* Elements in Data Streams</i> by Metwally, Agrawal, and Abbadi
*
* @param <T> type of data in the stream to be summarized
*/
public class StreamSummary<T> implements ITopK<T> {
protected class Bucket {
protected final DoublyLinkedList<Counter<T>> counterList;
private final long count;
public Bucket(long count) {
this.count = count;
this.counterList = new DoublyLinkedList<>();
}
}
protected final int capacity;
private final HashMap<T, ListNode2<Counter<T>>> counterMap;
protected final DoublyLinkedList<Bucket> bucketList;
/**
* @param capacity maximum size (larger capacities improve accuracy)
*/
public StreamSummary(int capacity) {
this.capacity = capacity;
counterMap = new HashMap<>();
bucketList = new DoublyLinkedList<>();
}
public int getCapacity() {
return capacity;
}
/**
* Algorithm: <i>Space-Saving</i>
*
* @param item stream element (<i>e</i>)
* @return false if item was already in the stream summary, true otherwise
*/
@Override
public boolean offer(T item) {
return offer(item, 1);
}
/**
* Algorithm: <i>Space-Saving</i>
*
* @param item stream element (<i>e</i>)
* @return false if item was already in the stream summary, true otherwise
*/
@Override
public boolean offer(T item, int incrementCount) {
return offerReturnAll(item, incrementCount).left;
}
/**
* @param item stream element (<i>e</i>)
* @return item dropped from summary if an item was dropped, null otherwise
*/
public T offerReturnDropped(T item, int incrementCount) {
return offerReturnAll(item, incrementCount).right;
}
/**
* @param item stream element (<i>e</i>)
* @return Pair<isNewItem, itemDropped> where isNewItem is the return
* value of offer() and itemDropped is null if no item was dropped
*/
public Pair<Boolean, T> offerReturnAll(T item, int incrementCount) {
ListNode2<Counter<T>> counterNode = counterMap.get(item);
boolean isNewItem = (counterNode == null);
T droppedItem = null;
if (isNewItem) {
if (size() < capacity) {
counterNode = bucketList.enqueue(new Bucket(0)).getValue().counterList
.add(new Counter<>(bucketList.tail(), item));
} else {
Bucket min = bucketList.first();
counterNode = min.counterList.tail();
Counter<T> counter = counterNode.getValue();
droppedItem = counter.item;
counterMap.remove(droppedItem);
counter.item = item;
counter.error = min.count;
}
counterMap.put(item, counterNode);
}
incrementCounter(counterNode, incrementCount);
return new Pair<>(isNewItem, droppedItem);
}
protected void incrementCounter(ListNode2<Counter<T>> counterNode,
int incrementCount) {
Counter<T> counter = counterNode.getValue(); // count_i
ListNode2<Bucket> oldNode = counter.bucketNode;
Bucket bucket = oldNode.getValue(); // Let Bucket_i be the bucket of count_i
bucket.counterList.remove(counterNode); // Detach count_i from Bucket_i's
// child-list
counter.count = counter.count + incrementCount;
// Finding the right bucket for count_i
// Because we allow a single call to increment count more than once, this
// may not be the adjacent bucket.
ListNode2<Bucket> bucketNodePrev = oldNode;
ListNode2<Bucket> bucketNodeNext = bucketNodePrev.getNext();
while (bucketNodeNext != null) {
Bucket bucketNext = bucketNodeNext.getValue(); // Let Bucket_i^+ be
// Bucket_i's neighbor of larger value
if (counter.count == bucketNext.count) {
bucketNext.counterList.add(counterNode); // Attach count_i to
// Bucket_i^+'s child-list
break;
} else if (counter.count > bucketNext.count) {
bucketNodePrev = bucketNodeNext;
bucketNodeNext = bucketNodePrev.getNext(); // Continue hunting for an
// appropriate bucket
} else {
// A new bucket has to be created
bucketNodeNext = null;
}
}
if (bucketNodeNext == null) {
Bucket bucketNext = new Bucket(counter.count);
bucketNext.counterList.add(counterNode);
bucketNodeNext = bucketList.addAfter(bucketNodePrev, bucketNext);
}
counter.bucketNode = bucketNodeNext;
// Cleaning up
if (bucket.counterList.isEmpty()) { // If Bucket_i's child-list is empty
bucketList.remove(oldNode); // Detach Bucket_i from the Stream-Summary
}
}
@Override
public List<T> peek(int k) {
List<T> topK = new ArrayList<>(k);
for (ListNode2<Bucket> bNode = bucketList.head(); bNode != null; bNode = bNode
.getPrev()) {
Bucket b = bNode.getValue();
for (Counter<T> c : b.counterList) {
if (topK.size() == k) {
return topK;
}
topK.add(c.item);
}
}
return topK;
}
public List<Counter<T>> topK(int k) {
List<Counter<T>> topK = new ArrayList<>(k);
for (ListNode2<Bucket> bNode = bucketList.head(); bNode != null;
bNode = bNode.getPrev()) {
Bucket b = bNode.getValue();
for (Counter<T> c : b.counterList) {
if (topK.size() == k) {
return topK;
}
topK.add(c);
}
}
return topK;
}
/**
* @return number of items stored
*/
public int size() {
return counterMap.size();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('[');
for (ListNode2<Bucket> bNode = bucketList.head(); bNode != null;
bNode = bNode.getPrev()) {
Bucket b = bNode.getValue();
sb.append('{');
sb.append(b.count);
sb.append(":[");
for (Counter<T> c : b.counterList) {
sb.append('{');
sb.append(c.item);
sb.append(':');
sb.append(c.error);
sb.append("},");
}
if (b.counterList.size() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append("]},");
}
if (bucketList.size() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append(']');
return sb.toString();
}
public static <T> void write(Kryo kryo, Output output, StreamSummary<T> obj) {
output.writeInt(obj.capacity);
output.writeInt(obj.size());
for (ListNode2<StreamSummary<T>.Bucket> bNode = obj.bucketList.tail();
bNode != null; bNode = bNode.getNext()) {
StreamSummary<T>.Bucket b = bNode.getValue();
for (Counter<T> c : b.counterList) {
kryo.writeObject(output, c);
}
}
}
public static <T> StreamSummary<T> read(Kryo kryo, Input input) {
int capacity = input.readInt();
int size = input.readInt();
StreamSummary<T> deser = new StreamSummary<>(capacity);
StreamSummary<T>.Bucket currentBucket = null;
ListNode2<StreamSummary<T>.Bucket> currentBucketNode = null;
for (int i = 0; i < size; i++) {
@SuppressWarnings("unchecked")
Counter<T> c = (Counter<T>)kryo.readObject(input, Counter.class);
if (currentBucket == null || c.count != currentBucket.count) {
currentBucket = deser.new Bucket(c.count);
currentBucketNode = deser.bucketList.add(currentBucket);
}
c.bucketNode = currentBucketNode;
deser.counterMap.put(c.item, currentBucket.counterList.add(c));
}
return deser;
}
}
| 3,473
|
558
|
<reponame>jonfairbanks/rtsp-nvr
from flask import current_app, render_template
from flask_mail import Message
from backend.tasks import send_mail_async_task
def send_mail(subject, recipients, template, sender=None, **ctx):
if not isinstance(recipients, (tuple, list)):
recipients = [recipients]
msg = Message(subject=subject, recipients=recipients, sender=sender)
msg.html = render_template(template, **ctx)
if current_app and current_app.config.get('TESTING'):
return send_mail_async_task.apply([msg])
return send_mail_async_task.delay(msg)
| 207
|
892
|
<reponame>github/advisory-database
{
"schema_version": "1.2.0",
"id": "GHSA-xhfw-wjjc-4j5h",
"modified": "2022-05-13T01:49:13Z",
"published": "2022-05-13T01:49:13Z",
"aliases": [
"CVE-2018-1136"
],
"details": "An issue was discovered in Moodle 3.x. An authenticated user is allowed to add HTML blocks containing scripts to their Dashboard; this is normally not a security issue because a personal dashboard is visible to this user only. Through this security vulnerability, users can move such a block to other pages where they can be viewed by other users.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2018-1136"
},
{
"type": "WEB",
"url": "https://moodle.org/mod/forum/discuss.php?d=371202"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/104307"
}
],
"database_specific": {
"cwe_ids": [
"CWE-79"
],
"severity": "MODERATE",
"github_reviewed": false
}
}
| 513
|
1,189
|
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.api.trace;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link TraceFlags}. */
class TraceFlagsTest {
@Test
void defaultInstances() {
assertThat(TraceFlags.getDefault().asHex()).isEqualTo("00");
assertThat(TraceFlags.getSampled().asHex()).isEqualTo("01");
}
@Test
void isSampled() {
assertThat(TraceFlags.fromByte((byte) 0xff).isSampled()).isTrue();
assertThat(TraceFlags.fromByte((byte) 0x01).isSampled()).isTrue();
assertThat(TraceFlags.fromByte((byte) 0x05).isSampled()).isTrue();
assertThat(TraceFlags.fromByte((byte) 0x00).isSampled()).isFalse();
}
@Test
void toFromHex() {
for (int i = 0; i < 256; i++) {
String hex = Integer.toHexString(i);
if (hex.length() == 1) {
hex = "0" + hex;
}
assertThat(TraceFlags.fromHex(hex, 0).asHex()).isEqualTo(hex);
}
}
@Test
void toFromByte() {
for (int i = 0; i < 256; i++) {
assertThat(TraceFlags.fromByte((byte) i).asByte()).isEqualTo((byte) i);
}
}
}
| 491
|
519
|
<filename>src/cpu-kernels/awkward_NumpyArray_contiguous_copy_from_many.cpp<gh_stars>100-1000
// BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
#define FILENAME(line) FILENAME_FOR_EXCEPTIONS_C("src/cpu-kernels/awkward_NumpyArray_contiguous_copy_from_many.cpp", line)
#include "awkward/kernels.h"
template <typename T>
ERROR awkward_NumpyArray_contiguous_copy_from_many(
uint8_t* toptr,
const uint8_t** fromptrs,
int64_t* fromlens,
int64_t len,
int64_t stride,
const T* pos) {
int64_t k = 0;
int64_t j = 0;
for (int64_t i = 0; i < len; i++) {
memcpy(&toptr[i*stride], &fromptrs[k][pos[j++]], (size_t)stride);
if (j >= fromlens[k]) {
k++;
j = 0;
}
}
return success();
}
ERROR awkward_NumpyArray_contiguous_copy_from_many_64(
uint8_t* toptr,
const uint8_t** fromptrs,
int64_t* fromlens,
int64_t len,
int64_t stride,
const int64_t* pos) {
return awkward_NumpyArray_contiguous_copy_from_many<int64_t>(
toptr,
fromptrs,
fromlens,
len,
stride,
pos);
}
| 490
|
754
|
/*-
* <<
* UAVStack
* ==
* Copyright (C) 2016 - 2017 UAVStack
* ==
* 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.creditease.uav.cache.redis;
import java.util.EnumMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.aredis.cache.AsyncHandler;
import org.aredis.cache.AsyncRedisClient;
import org.aredis.cache.AsyncRedisFactory;
import org.aredis.cache.RedisCommand;
import org.aredis.cache.RedisCommandInfo;
import org.aredis.cache.RedisCommandInfo.CommandStatus;
import com.creditease.agent.helpers.JSONHelper;
import com.creditease.agent.log.SystemLogger;
import com.creditease.agent.log.api.ISystemLogger;
import com.creditease.uav.cache.redis.api.AbstractAsyncHandler;
import com.creditease.uav.cache.redis.api.CacheService;
import com.creditease.uav.cache.redis.api.CommandInfo;
public class AredisAsyncService implements CacheService {
static ISystemLogger logger = SystemLogger.getLogger(AredisAsyncService.class);
private static Map<CommandInfo.RedisCommand, org.aredis.cache.RedisCommand> enumMap = new EnumMap<CommandInfo.RedisCommand, org.aredis.cache.RedisCommand>(
CommandInfo.RedisCommand.class);
static {
enumMap.put(CommandInfo.RedisCommand.SET, RedisCommand.SET);
enumMap.put(CommandInfo.RedisCommand.HSET, RedisCommand.HSET);
enumMap.put(CommandInfo.RedisCommand.GET, RedisCommand.GET);
enumMap.put(CommandInfo.RedisCommand.HGET, RedisCommand.HGET);
enumMap.put(CommandInfo.RedisCommand.HGETALL, RedisCommand.HGETALL);
enumMap.put(CommandInfo.RedisCommand.MGET, RedisCommand.MGET);
enumMap.put(CommandInfo.RedisCommand.MSET, RedisCommand.MSET);
enumMap.put(CommandInfo.RedisCommand.HMSET, RedisCommand.HMSET);
enumMap.put(CommandInfo.RedisCommand.HMGET, RedisCommand.HMGET);
enumMap.put(CommandInfo.RedisCommand.DEL, RedisCommand.DEL);
enumMap.put(CommandInfo.RedisCommand.EXPIRE, RedisCommand.EXPIRE);
enumMap.put(CommandInfo.RedisCommand.EXISTS, RedisCommand.EXISTS);
enumMap.put(CommandInfo.RedisCommand.INCR, RedisCommand.INCR);
enumMap.put(CommandInfo.RedisCommand.DECR, RedisCommand.DECR);
enumMap.put(CommandInfo.RedisCommand.HKEYS, RedisCommand.HKEYS);
enumMap.put(CommandInfo.RedisCommand.HDEL, RedisCommand.HDEL);
// LIST
enumMap.put(CommandInfo.RedisCommand.LPUSH, RedisCommand.LPUSH);
enumMap.put(CommandInfo.RedisCommand.LPOP, RedisCommand.LPOP);
enumMap.put(CommandInfo.RedisCommand.RPUSH, RedisCommand.RPUSH);
enumMap.put(CommandInfo.RedisCommand.RPOP, RedisCommand.RPOP);
enumMap.put(CommandInfo.RedisCommand.LRANGE, RedisCommand.LRANGE);
enumMap.put(CommandInfo.RedisCommand.LINDEX, RedisCommand.LINDEX);
enumMap.put(CommandInfo.RedisCommand.LREM, RedisCommand.LREM);
enumMap.put(CommandInfo.RedisCommand.LSET, RedisCommand.LSET);
enumMap.put(CommandInfo.RedisCommand.LLEN, RedisCommand.LLEN);
}
private AsyncRedisFactory factory;
private String redisServerAddress;
private ThreadPoolExecutor executor;
public AredisAsyncService(String redisServerAddress, int minConcurrent, int maxConcurrent, int queueSize) {
this(redisServerAddress, minConcurrent, maxConcurrent, queueSize, null);
}
public AredisAsyncService(String redisServerAddress, int minConcurrent, int maxConcurrent, int queueSize,
String password) {
if (maxConcurrent <= 0) {
maxConcurrent = 50;
}
if (minConcurrent <= 0) {
minConcurrent = 10;
}
if (queueSize <= 0) {
queueSize = 100;
}
this.redisServerAddress = redisServerAddress;
if (password != null) {
AsyncRedisFactory.setAuth(redisServerAddress, password);
}
/**
* 初始化线程池
*/
executor = new ThreadPoolExecutor(minConcurrent, maxConcurrent, 15, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(queueSize));
executor.allowCoreThreadTimeOut(true);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
if (logger.isTraceEnable()) {
logger.info(this,
"AredisAsyncService线程池设置:min=" + minConcurrent + ",max=" + maxConcurrent + ",queue=" + queueSize);
}
factory = new AsyncRedisFactory(executor);
}
@Override
public Object[] submitCommands(CommandInfo... commands) {
RedisCommandInfo[] commands1 = new RedisCommandInfo[commands.length];
RedisCommandInfo[] futures = null;
Object[] result = null;
for (int i = 0; i < commands.length; i++) {
commands1[i] = new RedisCommandInfo(enumMap.get(commands[i].getCommand()),
Object[].class.cast(commands[i].getParam()));
}
AsyncRedisClient client = getAredisClient();
try {
/**
* 只等待10s,超过则认为Redis不可用
*/
futures = client.submitCommands(commands1).get(10, TimeUnit.SECONDS);
result = new Object[futures.length];
for (int i = 0; i < futures.length; i++) {
result[i] = futures[i].getResult();
}
}
catch (TimeoutException e) {
logger.err(this, "Redis操作" + JSONHelper.toString(commands) + "超时", e);
throw new RuntimeException(e);
}
catch (InterruptedException e) {
logger.err(this, "Redis操作" + JSONHelper.toString(commands) + "失败", e);
}
catch (ExecutionException e) {
logger.err(this, "Redis操作" + JSONHelper.toString(commands) + "失败", e);
}
return result;
}
@Override
public void submitCommands(AbstractAsyncHandler<CommandInfo> handler, CommandInfo... commands) {
RedisCommandInfo[] commands1 = new RedisCommandInfo[commands.length];
for (int i = 0; i < commands.length; i++) {
commands1[i] = new RedisCommandInfo(enumMap.get(commands[i].getCommand()),
Object[].class.cast(commands[i].getParam()));
}
AsyncRedisClient client = getAredisClient();
final AbstractAsyncHandler<CommandInfo> fhandler = handler;
final CommandInfo[] fcommands = commands;
client.submitCommands(commands1, new AsyncHandler<RedisCommandInfo[]>() {
@Override
public void completed(RedisCommandInfo[] redisCommandInfos, Throwable e) {
if (e != null) {
logger.err(this, "Redis操作" + JSONHelper.toString(fcommands) + "异常", e);
}
/**
* 允许AbstractAsyncHandler为空
*/
if (fhandler == null) {
return;
}
Object[] infos = new Object[redisCommandInfos.length];
for (int i = 0; i < redisCommandInfos.length; i++) {
infos[i] = redisCommandInfos[i].getResult();
fcommands[i]
.setState((redisCommandInfos[i].getRunStatus() == CommandStatus.SUCCESS) ? true : false);
}
fhandler.process(fcommands, infos, e);
}
}, true, false);
}
private AsyncRedisClient getAredisClient() {
return factory.getClient(this.redisServerAddress);
}
@Override
public void start() {
// Do nothing but must pass sonar check
}
@Override
public void shutdown() {
this.executor.shutdown();
this.executor.shutdownNow();
try {
this.executor.awaitTermination(5, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
// ignore
}
}
}
| 3,710
|
1,751
|
# SPDX-License-Identifier: MIT OR Apache-2.0
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the MIT License. See the LICENSE file in the root of this
# repository for complete details.
"""
Global state department. Don't reload this module or everything breaks.
"""
import sys
import warnings
from typing import (
Any,
Callable,
Dict,
Iterable,
Optional,
Sequence,
Type,
cast,
)
from ._log_levels import make_filtering_bound_logger
from ._loggers import PrintLoggerFactory
from .dev import ConsoleRenderer, _use_colors, set_exc_info
from .processors import StackInfoRenderer, TimeStamper, add_log_level
from .types import BindableLogger, Context, Processor, WrappedLogger
"""
.. note::
Any changes to these defaults must be reflected in `getting-started`.
"""
_BUILTIN_DEFAULT_PROCESSORS: Sequence[Processor] = [
add_log_level,
StackInfoRenderer(),
set_exc_info,
TimeStamper(fmt="%Y-%m-%d %H:%M.%S", utc=False),
ConsoleRenderer(
colors=_use_colors and sys.stdout is not None and sys.stdout.isatty()
),
]
_BUILTIN_DEFAULT_CONTEXT_CLASS = cast(Type[Context], dict)
_BUILTIN_DEFAULT_WRAPPER_CLASS = make_filtering_bound_logger(0)
_BUILTIN_DEFAULT_LOGGER_FACTORY = PrintLoggerFactory()
_BUILTIN_CACHE_LOGGER_ON_FIRST_USE = False
class _Configuration:
"""
Global defaults.
"""
is_configured: bool = False
default_processors: Iterable[Processor] = _BUILTIN_DEFAULT_PROCESSORS[:]
default_context_class: Type[Context] = _BUILTIN_DEFAULT_CONTEXT_CLASS
default_wrapper_class: Any = _BUILTIN_DEFAULT_WRAPPER_CLASS
logger_factory: Callable[
..., WrappedLogger
] = _BUILTIN_DEFAULT_LOGGER_FACTORY
cache_logger_on_first_use: bool = _BUILTIN_CACHE_LOGGER_ON_FIRST_USE
_CONFIG = _Configuration()
"""
Global defaults used when arguments to `wrap_logger` are omitted.
"""
def is_configured() -> bool:
"""
Return whether ``structlog`` has been configured.
If `False`, ``structlog`` is running with builtin defaults.
.. versionadded: 18.1
"""
return _CONFIG.is_configured
def get_config() -> Dict[str, Any]:
"""
Get a dictionary with the current configuration.
.. note::
Changes to the returned dictionary do *not* affect ``structlog``.
.. versionadded: 18.1
"""
return {
"processors": _CONFIG.default_processors,
"context_class": _CONFIG.default_context_class,
"wrapper_class": _CONFIG.default_wrapper_class,
"logger_factory": _CONFIG.logger_factory,
"cache_logger_on_first_use": _CONFIG.cache_logger_on_first_use,
}
def get_logger(*args: Any, **initial_values: Any) -> Any:
"""
Convenience function that returns a logger according to configuration.
>>> from structlog import get_logger
>>> log = get_logger(y=23)
>>> log.msg("hello", x=42)
y=23 x=42 event='hello'
:param args: *Optional* positional arguments that are passed unmodified to
the logger factory. Therefore it depends on the factory what they
mean.
:param initial_values: Values that are used to pre-populate your contexts.
:returns: A proxy that creates a correctly configured bound logger when
necessary. The type of that bound logger depends on your configuration
and is `structlog.BoundLogger` by default.
See `configuration` for details.
If you prefer CamelCase, there's an alias for your reading pleasure:
`structlog.getLogger`.
.. versionadded:: 0.4.0
*args*
"""
return wrap_logger(None, logger_factory_args=args, **initial_values)
getLogger = get_logger
"""
CamelCase alias for `structlog.get_logger`.
This function is supposed to be in every source file -- we don't want it to
stick out like a sore thumb in frameworks like Twisted or Zope.
"""
def wrap_logger(
logger: WrappedLogger,
processors: Optional[Iterable[Processor]] = None,
wrapper_class: Optional[Type[BindableLogger]] = None,
context_class: Optional[Type[Context]] = None,
cache_logger_on_first_use: Optional[bool] = None,
logger_factory_args: Optional[Iterable[Any]] = None,
**initial_values: Any
) -> Any:
"""
Create a new bound logger for an arbitrary *logger*.
Default values for *processors*, *wrapper_class*, and *context_class* can
be set using `configure`.
If you set an attribute here, `configure` calls have *no* effect for
the *respective* attribute.
In other words: selective overwriting of the defaults while keeping some
*is* possible.
:param initial_values: Values that are used to pre-populate your contexts.
:param logger_factory_args: Values that are passed unmodified as
``*logger_factory_args`` to the logger factory if not `None`.
:returns: A proxy that creates a correctly configured bound logger when
necessary.
See `configure` for the meaning of the rest of the arguments.
.. versionadded:: 0.4.0
*logger_factory_args*
"""
return BoundLoggerLazyProxy(
logger,
wrapper_class=wrapper_class,
processors=processors,
context_class=context_class,
cache_logger_on_first_use=cache_logger_on_first_use,
initial_values=initial_values,
logger_factory_args=logger_factory_args,
)
def configure(
processors: Optional[Iterable[Processor]] = None,
wrapper_class: Optional[Type[BindableLogger]] = None,
context_class: Optional[Type[Context]] = None,
logger_factory: Optional[Callable[..., WrappedLogger]] = None,
cache_logger_on_first_use: Optional[bool] = None,
) -> None:
"""
Configures the **global** defaults.
They are used if `wrap_logger` or `get_logger` are called without
arguments.
Can be called several times, keeping an argument at `None` leaves it
unchanged from the current setting.
After calling for the first time, `is_configured` starts returning
`True`.
Use `reset_defaults` to undo your changes.
:param processors: The processor chain. See :doc:`processors` for details.
:param wrapper_class: Class to use for wrapping loggers instead of
`structlog.BoundLogger`. See `standard-library`, :doc:`twisted`, and
`custom-wrappers`.
:param context_class: Class to be used for internal context keeping.
:param logger_factory: Factory to be called to create a new
logger that shall be wrapped.
:param cache_logger_on_first_use: `wrap_logger` doesn't return an
actual wrapped logger but a proxy that assembles one when it's first
used. If this option is set to `True`, this assembled logger is
cached. See `performance`.
.. versionadded:: 0.3.0
*cache_logger_on_first_use*
"""
_CONFIG.is_configured = True
if processors is not None:
_CONFIG.default_processors = processors
if wrapper_class is not None:
_CONFIG.default_wrapper_class = wrapper_class
if context_class is not None:
_CONFIG.default_context_class = context_class
if logger_factory is not None:
_CONFIG.logger_factory = logger_factory # type: ignore
if cache_logger_on_first_use is not None:
_CONFIG.cache_logger_on_first_use = cache_logger_on_first_use
def configure_once(
processors: Optional[Iterable[Processor]] = None,
wrapper_class: Optional[Type[BindableLogger]] = None,
context_class: Optional[Type[Context]] = None,
logger_factory: Optional[Callable[..., WrappedLogger]] = None,
cache_logger_on_first_use: Optional[bool] = None,
) -> None:
"""
Configures if structlog isn't configured yet.
It does *not* matter whether it was configured using `configure` or
`configure_once` before.
Raises a `RuntimeWarning` if repeated configuration is attempted.
"""
if not _CONFIG.is_configured:
configure(
processors=processors,
wrapper_class=wrapper_class,
context_class=context_class,
logger_factory=logger_factory,
cache_logger_on_first_use=cache_logger_on_first_use,
)
else:
warnings.warn("Repeated configuration attempted.", RuntimeWarning)
def reset_defaults() -> None:
"""
Resets global default values to builtin defaults.
`is_configured` starts returning `False` afterwards.
"""
_CONFIG.is_configured = False
_CONFIG.default_processors = _BUILTIN_DEFAULT_PROCESSORS[:]
_CONFIG.default_wrapper_class = _BUILTIN_DEFAULT_WRAPPER_CLASS
_CONFIG.default_context_class = _BUILTIN_DEFAULT_CONTEXT_CLASS
_CONFIG.logger_factory = _BUILTIN_DEFAULT_LOGGER_FACTORY # type: ignore
_CONFIG.cache_logger_on_first_use = _BUILTIN_CACHE_LOGGER_ON_FIRST_USE
class BoundLoggerLazyProxy:
"""
Instantiates a ``BoundLogger`` on first usage.
Takes both configuration and instantiation parameters into account.
The only points where a BoundLogger changes state are ``bind()``,
``unbind()``, and ``new()`` and that return the actual ``BoundLogger``.
If and only if configuration says so, that actual ``BoundLogger`` is
cached on first usage.
.. versionchanged:: 0.4.0
Added support for *logger_factory_args*.
"""
def __init__(
self,
logger: WrappedLogger,
wrapper_class: Optional[Type[BindableLogger]] = None,
processors: Optional[Iterable[Processor]] = None,
context_class: Optional[Type[Context]] = None,
cache_logger_on_first_use: Optional[bool] = None,
initial_values: Optional[Dict[str, Any]] = None,
logger_factory_args: Any = None,
) -> None:
self._logger = logger
self._wrapper_class = wrapper_class
self._processors = processors
self._context_class = context_class
self._cache_logger_on_first_use = cache_logger_on_first_use
self._initial_values = initial_values or {}
self._logger_factory_args = logger_factory_args or ()
def __repr__(self) -> str:
return (
"<BoundLoggerLazyProxy(logger={0._logger!r}, wrapper_class="
"{0._wrapper_class!r}, processors={0._processors!r}, "
"context_class={0._context_class!r}, "
"initial_values={0._initial_values!r}, "
"logger_factory_args={0._logger_factory_args!r})>".format(self)
)
def bind(self, **new_values: Any) -> BindableLogger:
"""
Assemble a new BoundLogger from arguments and configuration.
"""
if self._context_class:
ctx = self._context_class(self._initial_values)
else:
ctx = _CONFIG.default_context_class(self._initial_values)
_logger = self._logger
if not _logger:
_logger = _CONFIG.logger_factory(*self._logger_factory_args)
if self._processors is None:
procs = _CONFIG.default_processors
else:
procs = self._processors
cls = self._wrapper_class or _CONFIG.default_wrapper_class
# Looks like Protocols ignore definitions of __init__ so we have to
# silence Mypy here.
logger = cls(_logger, processors=procs, context=ctx) # type: ignore
def finalized_bind(**new_values: Any) -> BindableLogger:
"""
Use cached assembled logger to bind potentially new values.
"""
if new_values:
return logger.bind(**new_values)
else:
return logger
if self._cache_logger_on_first_use is True or (
self._cache_logger_on_first_use is None
and _CONFIG.cache_logger_on_first_use is True
):
self.bind = finalized_bind # type: ignore
return finalized_bind(**new_values)
def unbind(self, *keys: str) -> BindableLogger:
"""
Same as bind, except unbind *keys* first.
In our case that could be only initial values.
"""
return self.bind().unbind(*keys)
def try_unbind(self, *keys: str) -> BindableLogger:
return self.bind().try_unbind(*keys)
def new(self, **new_values: Any) -> BindableLogger:
"""
Clear context, then bind.
"""
if self._context_class:
self._context_class().clear()
else:
_CONFIG.default_context_class().clear()
bl = self.bind(**new_values)
return bl
def __getattr__(self, name: str) -> Any:
"""
If a logging method if called on a lazy proxy, we have to create an
ephemeral BoundLogger first.
"""
if name == "__isabstractmethod__":
raise AttributeError
bl = self.bind()
return getattr(bl, name)
def __getstate__(self) -> Dict[str, Any]:
"""
Our __getattr__ magic makes this necessary.
"""
return self.__dict__
def __setstate__(self, state: Dict[str, Any]) -> None:
"""
Our __getattr__ magic makes this necessary.
"""
for k, v in state.items():
setattr(self, k, v)
| 5,134
|
953
|
{"SpecFlowFeature":{"ScenarioDefinitions":[{"Tags":[],"Examples":[],"Location":{"Line":10,"Column":1},"Keyword":"Scenario","Name":"a simple scenario","Description":null,"Steps":[{"ScenarioBlock":1,"StepKeyword":1,"Location":{"Line":11,"Column":1},"Keyword":"Given ","Text":"some precondition","Argument":null},{"ScenarioBlock":2,"StepKeyword":2,"Location":{"Line":12,"Column":1},"Keyword":"When ","Text":"I do something","Argument":null},{"ScenarioBlock":3,"StepKeyword":3,"Location":{"Line":13,"Column":1},"Keyword":"Then ","Text":"something happens","Argument":null}]}],"Background":null,"Tags":[],"Location":{"Line":3,"Column":1},"Language":"en-US","Keyword":"Feature","Name":"Feature header","Description":"but it has also a description...\r\nA long long description\r\n\r\nwith new lines included","Children":[{"Tags":[],"Examples":[],"Location":{"Line":10,"Column":1},"Keyword":"Scenario","Name":"a simple scenario","Description":null,"Steps":[{"ScenarioBlock":1,"StepKeyword":1,"Location":{"Line":11,"Column":1},"Keyword":"Given ","Text":"some precondition","Argument":null},{"ScenarioBlock":2,"StepKeyword":2,"Location":{"Line":12,"Column":1},"Keyword":"When ","Text":"I do something","Argument":null},{"ScenarioBlock":3,"StepKeyword":3,"Location":{"Line":13,"Column":1},"Keyword":"Then ","Text":"something happens","Argument":null}]}]},"DocumentLocation":{"SourceFilePath":"sample.feature","FeatureFolderPath":""},"SourceFilePath":"sample.feature","Feature":{"ScenarioDefinitions":[{"Tags":[],"Examples":[],"Location":{"Line":10,"Column":1},"Keyword":"Scenario","Name":"a simple scenario","Description":null,"Steps":[{"ScenarioBlock":1,"StepKeyword":1,"Location":{"Line":11,"Column":1},"Keyword":"Given ","Text":"some precondition","Argument":null},{"ScenarioBlock":2,"StepKeyword":2,"Location":{"Line":12,"Column":1},"Keyword":"When ","Text":"I do something","Argument":null},{"ScenarioBlock":3,"StepKeyword":3,"Location":{"Line":13,"Column":1},"Keyword":"Then ","Text":"something happens","Argument":null}]}],"Background":null,"Tags":[],"Location":{"Line":3,"Column":1},"Language":"en-US","Keyword":"Feature","Name":"Feature header","Description":"but it has also a description...\r\nA long long description\r\n\r\nwith new lines included","Children":[{"Tags":[],"Examples":[],"Location":{"Line":10,"Column":1},"Keyword":"Scenario","Name":"a simple scenario","Description":null,"Steps":[{"ScenarioBlock":1,"StepKeyword":1,"Location":{"Line":11,"Column":1},"Keyword":"Given ","Text":"some precondition","Argument":null},{"ScenarioBlock":2,"StepKeyword":2,"Location":{"Line":12,"Column":1},"Keyword":"When ","Text":"I do something","Argument":null},{"ScenarioBlock":3,"StepKeyword":3,"Location":{"Line":13,"Column":1},"Keyword":"Then ","Text":"something happens","Argument":null}]}]},"Comments":[]}
| 793
|
575
|
import os
import sys
here = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(here))
sys.path.insert(0, os.path.join(here, "wptserve"))
sys.path.insert(0, os.path.join(here, "third_party", "pywebsocket3"))
sys.path.insert(0, os.path.join(here, "third_party", "atomicwrites"))
sys.path.insert(0, os.path.join(here, "third_party", "attrs", "src"))
sys.path.insert(0, os.path.join(here, "third_party", "funcsigs"))
sys.path.insert(0, os.path.join(here, "third_party", "html5lib"))
sys.path.insert(0, os.path.join(here, "third_party", "zipp"))
sys.path.insert(0, os.path.join(here, "third_party", "more-itertools"))
sys.path.insert(0, os.path.join(here, "third_party", "packaging"))
sys.path.insert(0, os.path.join(here, "third_party", "pathlib2"))
sys.path.insert(0, os.path.join(here, "third_party", "pluggy", "src"))
sys.path.insert(0, os.path.join(here, "third_party", "py"))
sys.path.insert(0, os.path.join(here, "third_party", "pytest"))
sys.path.insert(0, os.path.join(here, "third_party", "pytest", "src"))
sys.path.insert(0, os.path.join(here, "third_party", "pytest-asyncio"))
sys.path.insert(0, os.path.join(here, "third_party", "six"))
sys.path.insert(0, os.path.join(here, "third_party", "webencodings"))
sys.path.insert(0, os.path.join(here, "third_party", "h2"))
sys.path.insert(0, os.path.join(here, "third_party", "hpack"))
sys.path.insert(0, os.path.join(here, "third_party", "hyperframe"))
sys.path.insert(0, os.path.join(here, "third_party", "certifi"))
sys.path.insert(0, os.path.join(here, "third_party", "hyper"))
sys.path.insert(0, os.path.join(here, "third_party", "websockets", "src"))
sys.path.insert(0, os.path.join(here, "third_party", "iniconfig", "src"))
if sys.version_info < (3, 8):
sys.path.insert(0, os.path.join(here, "third_party", "importlib_metadata"))
sys.path.insert(0, os.path.join(here, "webdriver"))
sys.path.insert(0, os.path.join(here, "wptrunner"))
if sys.version_info[0] == 2:
sys.path.insert(0, os.path.join(here, "third_party", "enum"))
# We can't import six until we've set the path above.
from six import ensure_text
repo_root = ensure_text(os.path.abspath(os.path.join(here, os.pardir)))
| 881
|
190,993
|
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for debugger functionalities under multiple (i.e., >1) GPUs."""
import os
import tempfile
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.client import device_lib
from tensorflow.python.client import session
from tensorflow.python.debug.lib import debug_data
from tensorflow.python.debug.lib import debug_utils
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.lib.io import file_io
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import googletest
class SessionDebugMultiGPUTest(test_util.TensorFlowTestCase):
def setUp(self):
self._dump_root = tempfile.mkdtemp()
def tearDown(self):
ops.reset_default_graph()
# Tear down temporary dump directory.
if os.path.isdir(self._dump_root):
file_io.delete_recursively(self._dump_root)
def testMultiGPUSessionRun(self):
local_devices = device_lib.list_local_devices()
gpu_device_names = []
for device in local_devices:
if device.device_type == "GPU":
gpu_device_names.append(device.name)
gpu_device_names = sorted(gpu_device_names)
if len(gpu_device_names) < 2:
self.skipTest(
"This test requires at least 2 GPUs, but only %d is available." %
len(gpu_device_names))
with session.Session() as sess:
v = variables.Variable([10.0, 15.0], dtype=dtypes.float32, name="v")
with ops.device(gpu_device_names[0]):
u0 = math_ops.add(v, v, name="u0")
with ops.device(gpu_device_names[1]):
u1 = math_ops.multiply(v, v, name="u1")
w = math_ops.subtract(u1, u0, name="w")
self.evaluate(v.initializer)
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(run_options, sess.graph,
debug_urls="file://" + self._dump_root)
run_metadata = config_pb2.RunMetadata()
self.assertAllClose(
[80.0, 195.0],
sess.run(w, options=run_options, run_metadata=run_metadata))
debug_dump_dir = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
self.assertEqual(3, len(debug_dump_dir.devices()))
self.assertAllClose(
[10.0, 15.0], debug_dump_dir.get_tensors("v", 0, "DebugIdentity")[0])
self.assertAllClose(
[20.0, 30.0], debug_dump_dir.get_tensors("u0", 0, "DebugIdentity")[0])
self.assertAllClose(
[100.0, 225.0],
debug_dump_dir.get_tensors("u1", 0, "DebugIdentity")[0])
if __name__ == "__main__":
googletest.main()
| 1,280
|
2,466
|
<reponame>Henny20/skija
package org.jetbrains.skija;
import org.jetbrains.annotations.*;
public enum FilterQuality {
/** fastest but lowest quality, typically nearest-neighbor */
NONE,
/** typically bilerp */
LOW,
/** typically bilerp + mipmaps for down-scaling */
MEDIUM,
/** slowest but highest quality, typically bicubic or bett */
HIGH;
@ApiStatus.Internal public static final FilterQuality[] _values = values();
}
| 158
|
625
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* 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 androidx.leanback.leanbackshowcase.app.room.controller.overview;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.leanback.app.BrowseSupportFragment;
import androidx.leanback.leanbackshowcase.R;
import androidx.leanback.leanbackshowcase.app.room.adapter.ListAdapter;
import androidx.leanback.leanbackshowcase.app.room.config.AppConfiguration;
import androidx.leanback.leanbackshowcase.app.room.db.entity.CategoryEntity;
import androidx.leanback.leanbackshowcase.app.room.db.entity.VideoEntity;
import androidx.leanback.leanbackshowcase.app.room.di.adapter.qualifier.ListAdapteWithLiveDataRowPresenterQualifier;
import androidx.leanback.leanbackshowcase.app.room.network.DownloadCompleteBroadcastReceiver;
import androidx.leanback.leanbackshowcase.app.room.network.DownloadingTaskDescription;
import androidx.leanback.leanbackshowcase.app.room.network.NetworkLiveData;
import androidx.leanback.leanbackshowcase.app.room.ui.LiveDataRowPresenter;
import androidx.leanback.leanbackshowcase.app.room.ui.LiveDataRowPresenter.DataLoadedListener;
import androidx.leanback.leanbackshowcase.app.room.ui.VideoCardPresenter;
import androidx.leanback.leanbackshowcase.app.room.viewmodel.VideosViewModel;
import androidx.leanback.widget.HeaderItem;
import androidx.leanback.widget.ListRow;
import androidx.leanback.widget.OnItemViewClickedListener;
import androidx.leanback.widget.OnItemViewSelectedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import dagger.android.support.AndroidSupportInjection;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
// TOOD: why we need injectable interface here
// just like regular class it can specify some component to provide
// but if you don't use the dagger component in the code and call the inject(this) method,
// it is still basically nothing
// so if you don't have injectable interface in the class, no code androidinjection.inject() will
// be instrumented, so still nothing happens
// but dagger is sophisicated, it will check anyway
public class LiveDataFragment extends BrowseSupportFragment
implements DownloadCompleteBroadcastReceiver.DownloadCompleteListener,
LiveDataRowPresenter.DataLoadedListener {
// For debugging purpose
private static final Boolean DEBUG = false;
private static final String TAG = "LiveDataFragment";
// Resource category
private static final String BACKGROUND = "background";
private static final String CARD = "card";
private static final String VIDEO = "video";
@Inject
@ListAdapteWithLiveDataRowPresenterQualifier
ListAdapter<ListRow> mRowsAdapter;
@Inject
Map<Class, OnItemViewClickedListener> viewOnClickListenerMap;
@Inject
Map<Class, OnItemViewSelectedListener> viewOnSelectListenerMap;
@Inject
Map<Class, OnClickListener> onClickListener;
@Inject
ViewModelProvider.Factory viewModelFactory;
@Inject
VideoCardPresenter videoCardPresenter;
public DataLoadedListener getDataLoadedListener(){
return this;
}
private VideosViewModel mViewModel;
@Override
public void onCreate(Bundle savedInstanceState) {
AndroidSupportInjection.inject(this);
super.onCreate(savedInstanceState);
Log.e(TAG, "onCreate: " + " the map is: " + viewOnSelectListenerMap.get(this.getClass()));
// set top level adapter
setAdapter(mRowsAdapter);
// retrive appropriate listener from listener map and set on it
setOnItemViewClickedListener(viewOnClickListenerMap.get(this.getClass()));
setOnItemViewSelectedListener(viewOnSelectListenerMap.get(this.getClass()));
setOnSearchClickedListener(onClickListener.get(this.getClass()));
// register broadcast receiver
DownloadCompleteBroadcastReceiver.getInstance().registerListener(this);
// tweak the ui
setHeadersState(HEADERS_ENABLED);
setHeadersTransitionOnBackEnabled(true);
setTitle(getString(R.string.livedata));
// enable transition
prepareEntranceTransition();
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
subscribeNetworkInfo();
mViewModel = ViewModelProviders.of(getActivity(), viewModelFactory)
.get(VideosViewModel.class);
subscribeUi(mViewModel);
}
@Override
public void onDataLoaded() {
startEntranceTransition();
}
@Override
public void onDownloadingCompleted(final DownloadingTaskDescription desc) {
final VideoEntity videoEntity = desc.getVideo();
switch (desc.getCategory()) {
case VIDEO:
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
if (AppConfiguration.IS_NETWORK_LATENCY_ENABLED) {
addLatency(3000L);
}
mViewModel.updateDatabase(videoEntity, VIDEO, desc.getStoragePath());
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(
getActivity().getApplicationContext(),
"video " + videoEntity.getId() + " " +
"downloaded",
Toast.LENGTH_SHORT).show();
}
}.execute();
break;
case BACKGROUND:
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
if (AppConfiguration.IS_NETWORK_LATENCY_ENABLED) {
addLatency(2000L);
}
mViewModel.updateDatabase(videoEntity, BACKGROUND, desc.getStoragePath());
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(
getActivity().getApplicationContext(),
"background" + videoEntity.getId() + " " +
"downloaded",
Toast.LENGTH_SHORT).show();
}
}.execute();
break;
case CARD:
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
if (AppConfiguration.IS_NETWORK_LATENCY_ENABLED) {
addLatency(1000L);
}
mViewModel.updateDatabase(videoEntity, CARD, desc.getStoragePath());
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(
getActivity().getApplicationContext(),
"card " + videoEntity.getId() + " downloaded",
Toast.LENGTH_SHORT).show();
}
}.execute();
break;
}
}
private void subscribeNetworkInfo() {
NetworkLiveData.sync(getActivity())
.observe((LifecycleOwner) getActivity(), new Observer<Boolean>() {
@Override
public void onChanged(@Nullable Boolean aBoolean) {
if (aBoolean) {
getActivity().findViewById(R.id.no_internet).setVisibility(View.GONE);
// TODO: an appropriate method to re-create the database
} else {
getActivity().findViewById(R.id.no_internet)
.setVisibility(View.VISIBLE);
}
}
});
}
private void subscribeUi(final VideosViewModel viewModel) {
viewModel.getAllCategories().observe((LifecycleOwner) getActivity(),
new Observer<List<CategoryEntity>>() {
@Override
public void onChanged(@Nullable List<CategoryEntity> categoryEntities) {
if (categoryEntities != null) {
List<ListRow> rows = new ArrayList<>();
// The ListRow here cannot be used with dependency injection, since it
// rely on the run time information getCategoryName
for (CategoryEntity categoryEntity : categoryEntities) {
ListRow row = new ListRow(
new HeaderItem(categoryEntity.getCategoryName()),
new ListAdapter<>(videoCardPresenter));
rows.add(row);
}
mRowsAdapter.setItems(rows, new Comparator<ListRow>() {
@Override
public int compare(ListRow o1, ListRow o2) {
return o1.getId() == o2.getId() ? 0 : -1;
}
}, new Comparator<ListRow>() {
@Override
public int compare(ListRow o1, ListRow o2) {
return o1.getHeaderItem().getName()
.equals(o2.getHeaderItem().getName()) ? 0 : -1;
}
});
}
}
});
}
private void addLatency(Long ms) {
try {
// add 1s latency for video downloading, when network latency option
// is enabled.
Thread.sleep(ms);
} catch (InterruptedException e) {
if (DEBUG) {
Log.e(TAG, "doInBackground: ", e);
}
}
}
}
| 5,413
|
488
|
<filename>projects/QtDesignerPlugins/QCodeEditWidgetPlugin.cpp
#include "QCodeEditWidgetPlugin.h"
#include "QCodeEditWidget.h"
#include <QtPlugin>
#include <QDebug>
QCodeEditWidgetPlugin::QCodeEditWidgetPlugin(QObject *par)
: QObject(par)
{
initialized=false;
}
QCodeEditWidgetPlugin::~QCodeEditWidgetPlugin()
{
}
QWidget* QCodeEditWidgetPlugin::createWidget(QWidget * par)
{
QCodeEditWidget * wdg = new QCodeEditWidget(par);
return wdg;
}
void QCodeEditWidgetPlugin::initialize(QDesignerFormEditorInterface * core)
{
if (initialized)
return;
initialized = true;
}
QString QCodeEditWidgetPlugin::domXml() const
{
return "<widget class=\"QCodeEditWidget\" name=\"codeEditWidget\">\n"
" <property name=\"geometry\">\n"
" <rect>\n"
" <x>0</x>\n"
" <y>0</y>\n"
" <width>500</width>\n"
" <height>500</height>\n"
" </rect>\n"
" </property>\n"
"</widget>\n";
}
| 458
|
4,253
|
<filename>20 架构师三期 SpringCloud微服务架构/代码/csrf3 验证码 security注解等/src/main/java/com/mashibing/admin/MyConfig2.java<gh_stars>1000+
package com.mashibing.admin;
import java.io.IOException;
import java.util.Base64;
import java.util.Collections;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import com.mashibing.admin.service.MyAuthProvider;
import com.mashibing.admin.service.MyDetailsService;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true ,prePostEnabled = true)
public class MyConfig2 extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(new CodeFilter(), UsernamePasswordAuthenticationFilter.class);
http.
// 哪些 地址需要登录
authorizeRequests()
// 角色 -> URL
// Role = 角色
// Authority = 权限
// .antMatchers("/admin/**").hasRole("admin")
// .antMatchers("/user/**").hasRole("user")
//
//所有请求都需要验证
// .anyRequest().authenticated()
// 不需要登录 不常用
// .antMatchers("url").hasIpAddress("127.0.0.1")
// ip地址访问的黑白名单,封ip操作
.and()
// 登录界面 和退出界面
.formLogin().loginPage("/login.html")
.loginProcessingUrl("/login").permitAll()
// 登录失败 页面
.failureUrl("/login.html?error")
// 登录成功跳转的页面
.defaultSuccessUrl("/ok",true).permitAll()
// 配置 登录页 的表单name admin -> 分权限 展示页面
.passwordParameter("oo")
.usernameParameter("xx")
// 在登录成功后会被调起
// 用来锁定资源 初始化资源等
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// TODO Auto-generated method stub
Object user = authentication.getPrincipal();
System.out.println(user);
}
})
.failureHandler(new AuthenticationFailureHandler() {
// 登录失败的异常信息
// 分析失败原因,统计失败次数
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
// TODO Auto-generated method stub
// 登录失败异常信息 exception
exception.printStackTrace();
}
})
.and().logout()
// 退出处理器
// 用于清理用户资源
.addLogoutHandler(new LogoutHandler() {
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
// TODO Auto-generated method stub
System.out.println("我滚了。。。");
}
})
.addLogoutHandler(new LogoutHandler() {
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
// TODO Auto-generated method stub
System.out.println("我又滚了");
}
})
.and()
.sessionManagement()
// 允许同时登录的 客户端
.maximumSessions(1)
// 已经有用户登录后, 不允许相同用户再次登录
.maxSessionsPreventsLogin(true).
// cookies 不一定是浏览器 token ,集群 会话 第三方/ 无回话 只在
// .rememberMe()
// .and()
and().and()
.csrf().disable();
}
@Autowired
DataSource dataSource;
// session 登录 并发量高 -> jwt
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.
inMemoryAuthentication()
.withUser("<PASSWORD>").password(new <PASSWORD>Encoder().encode("<PASSWORD>")).roles("admin")
.and()
.withUser("<PASSWORD>").password(new BC<PASSWORD>PasswordEncoder().encode("<PASSWORD>")).roles("user")
.and()
.withUser("<PASSWORD>").password(new BCryptPasswordEncoder().encode("<PASSWORD>")).roles("guest")
.and()
.withUser("<PASSWORD>").password(new BC<PASSWORD>Encoder().encode("<PASSWORD>")).roles("admin","user")
;
}
@Bean
RoleHierarchy roleHierarchy() {
RoleHierarchyImpl impl = new RoleHierarchyImpl();
impl.setHierarchy("ROLE_admin > ROLE_user");
return impl;
}
@Bean
HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
public static void main(String[] args) {
byte[] decode = Base64.getDecoder().decode("MTIzOjE1OTA3NjA2NjkxMTQ6YTc4OGNhOTJhMGE4MzYyN2MzNjhkNzkxZjA5ZGVmZDM");
//123:1590760669114:a788ca92a0a83627c368d791f09defd3*(前面两个 值 对不对) sign
//用户名+ 权限 + 欢乐豆 + 过期时间 + secret = 摘要 首次登录(服务器端有 客户端没有)
System.out.println(new String(decode));
// 好处 不需要任何和数据源的校验
}
}
| 2,848
|
806
|
<filename>src/main/java/com/github/davidmoten/rx/package-info.java<gh_stars>100-1000
/**
* Utilities for use with RxJava.
*/
package com.github.davidmoten.rx;
| 59
|
5,035
|
#include "epoll.h"
#include <sys/epoll.h>
#include <errno.h>
#include "threadpool.h"
struct epoll_event* events;
int epoll_init()
{
int epoll_fd = epoll_create(LISTENQ + 1);
if(epoll_fd == -1)
return -1;
//events = (struct epoll_event*)malloc(sizeof(struct epoll_event) * MAXEVENTS);
events = new epoll_event[MAXEVENTS];
return epoll_fd;
}
// 注册新描述符
int epoll_add(int epoll_fd, int fd, void *request, __uint32_t events)
{
struct epoll_event event;
event.data.ptr = request;
event.events = events;
//printf("add to epoll %d\n", fd);
if(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &event) < 0)
{
perror("epoll_add error");
return -1;
}
return 0;
}
// 修改描述符状态
int epoll_mod(int epoll_fd, int fd, void *request, __uint32_t events)
{
struct epoll_event event;
event.data.ptr = request;
event.events = events;
if(epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, &event) < 0)
{
perror("epoll_mod error");
return -1;
}
return 0;
}
// 从epoll中删除描述符
int epoll_del(int epoll_fd, int fd, void *request, __uint32_t events)
{
struct epoll_event event;
event.data.ptr = request;
event.events = events;
if(epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, &event) < 0)
{
perror("epoll_del error");
return -1;
}
return 0;
}
// 返回活跃事件数
int my_epoll_wait(int epoll_fd, struct epoll_event* events, int max_events, int timeout)
{
int ret_count = epoll_wait(epoll_fd, events, max_events, timeout);
if (ret_count < 0)
{
perror("epoll wait error");
}
return ret_count;
}
| 879
|
3,807
|
#!/usr/bin/env python
# Copyright 2019 Google
#
# 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.
import textwrap
from google.protobuf.descriptor_pb2 import FieldDescriptorProto
import nanopb_generator as nanopb
LINE_WIDTH = 80
def _indent(level):
"""Returns leading whitespace corresponding to the given indentation `level`.
"""
indent_per_level = 4
return ' ' * (indent_per_level * level)
class FilePrettyPrinting:
"""Allows generating pretty-printing support for a proto file.
Because two files (header and source) are generated for each proto file, this
class doesn't generate the necessary code directly. Use `messages` and `enums`
properties to generate the declarations and definitions separately and insert
them to the appropriate locations within the generated files.
"""
def __init__(self, file_desc):
"""Args:
file_desc: nanopb.ProtoFile describing this proto file.
"""
self.messages = [MessagePrettyPrinting(m) for m in
file_desc.messages]
self.enums = [EnumPrettyPrinting(e) for e in file_desc.enums]
class MessagePrettyPrinting:
"""Generates pretty-printing support for a message.
Adds the following member function to the Nanopb generated class:
std::string ToString(int indent = 0) const;
Because the generated code is split between a header and a source, the
declaration and definition are generated separately. Definition has the
out-of-class form.
The output of the generated function represents the proto in its text form,
suitable for parsing, and with proper indentation. The top-level message
additionally displays message name and the value of the pointer to `this`.
"""
def __init__(self, message_desc):
"""Args:
message_desc: nanopb.Message describing this message.
"""
self.full_classname = str(message_desc.name)
self._short_classname = message_desc.name.parts[-1]
self._fields = [self._create_field(f, message_desc) for f in
message_desc.fields]
# Make sure fields are printed ordered by tag, for consistency with official
# proto libraries.
self._fields.sort(key=lambda f: f.tag)
def _create_field(self, field_desc, message_desc):
if isinstance(field_desc, nanopb.OneOf):
return OneOfPrettyPrinting(field_desc, message_desc)
else:
return FieldPrettyPrinting(field_desc, message_desc)
def generate_declaration(self):
"""Generates the declaration of a `ToString()` member function.
"""
return '\n' + _indent(1) + 'std::string ToString(int indent = 0) const;\n'
def generate_definition(self):
"""Generates the out-of-class definition of a `ToString()` member function.
"""
result = '''\
std::string %s::ToString(int indent) const {
std::string header = PrintHeader(indent, "%s", this);
std::string result;\n\n''' % (
self.full_classname, self._short_classname)
for field in self._fields:
result += str(field)
can_be_empty = all(f.is_primitive or f.is_repeated for f in self._fields)
if can_be_empty:
result += '''
bool is_root = indent == 0;
if (!result.empty() || is_root) {
std::string tail = PrintTail(indent);
return header + result + tail;
} else {
return "";
}
}\n\n'''
else:
result += '''
std::string tail = PrintTail(indent);
return header + result + tail;
}\n\n'''
return result
class FieldPrettyPrinting:
"""Generates pretty-printing support for a field.
The generated C++ code will output the field name and value; the output format
is the proto text format, suitable for parsing. Unset fields are not printed.
Repeated and optional fields are supported.
Oneofs are not supported; use `OneOfPrettyPrinting` instead.
The actual output will be delegated to a C++ function called
`PrintPrimitiveField()`, `PrintEnumField()`, or `PrintMessageField()`,
according to the field type; the function is expected to be visible at the
point of definition.
"""
def __init__(self, field_desc, message_desc):
"""Args:
field_desc: nanopb.Field describing this field.
message_desc: nanopb.Message describing the message containing this field.
"""
self.name = field_desc.name
self.tag = field_desc.tag
self.is_optional = (field_desc.rules == 'OPTIONAL' and field_desc.allocation == 'STATIC')
self.is_repeated = field_desc.rules == 'REPEATED'
self.is_primitive = field_desc.pbtype != 'MESSAGE'
self.is_enum = field_desc.pbtype in ['ENUM', 'UENUM']
def __str__(self):
"""Generates a C++ statement that prints the field according to its type.
"""
if self.is_optional:
return self._generate_for_optional()
elif self.is_repeated:
return self._generate_for_repeated()
else:
return self._generate_for_leaf()
def _generate_for_repeated(self):
"""Generates a C++ statement that prints the repeated field, if non-empty.
"""
count = self.name + '_count'
result = '''\
for (pb_size_t i = 0; i != %s; ++i) {\n''' % count
# If the repeated field is non-empty, print all its members, even if they are
# zero or empty (otherwise, an array of zeroes would be indistinguishable from
# an empty array).
result += self._generate_for_leaf(indent=2, always_print=True)
result += '''\
}\n'''
return result
def _generate_for_optional(self):
"""Generates a C++ statement that prints the optional field, if set.
"""
name = self.name
result = '''\
if (has_%s) {\n''' % name
# If an optional field is set, always print the value, even if it's zero or
# empty.
result += self._generate_for_leaf(indent=2, always_print=True)
result += '''\
}\n'''
return result
def _generate_for_leaf(self, indent=1, always_print=False, parent_oneof=None):
"""Generates a C++ statement that prints the "leaf" field.
"Leaf" is to indicate that this function is non-recursive. If the field is
a message type, the generated code will delegate printing to its
`ToString()` member function.
Args:
indent: The indentation level of the generated statement.
always_print: If `False`, the field will not be printed if it has the
default value, or for a message, if each field it contains has the
default value.
parent_oneof: If the field is a member of a oneof, a reference to the
corresponding `OneOfPrettyPrinting`
"""
always_print = 'true' if always_print else 'false'
display_name = self.name
if self.is_primitive:
display_name += ':'
cc_name = self._get_cc_name(parent_oneof)
function_name = self._get_printer_function_name()
return self._generate(indent, display_name, cc_name, function_name,
always_print)
def _get_cc_name(self, parent_oneof):
"""Gets the name of the field to use in the generated C++ code:
- for repeated fields, appends indexing in the form of `[i]`;
- for named union members, prepends the name of the enclosing union;
- ensures the name isn't a C++ keyword by appending an underscore
(currently, only for keyword `delete`).
"""
cc_name = self.name
# If a proto field is named `delete`, it is renamed to `delete_` by our script
# because `delete` is a keyword in C++. Unfortunately, the renaming mechanism
# runs separately from generating pretty printers; consequently, when pretty
# printers are being generated, all proto fields still have their unmodified
# names.
if cc_name == 'delete':
cc_name = 'delete_'
if self.is_repeated:
cc_name += '[i]'
if parent_oneof and not parent_oneof.is_anonymous:
cc_name = parent_oneof.name + '.' + cc_name
return cc_name
def _get_printer_function_name(self):
"""Gets the name of the C++ function to delegate printing to.
"""
if self.is_enum:
return 'PrintEnumField'
elif self.is_primitive:
return 'PrintPrimitiveField'
else:
return 'PrintMessageField'
def _generate(self, indent_level, display_name, cc_name, function_name,
always_print):
"""Generates the C++ statement that prints the field.
Args:
indent_level: The indentation level of the generated statement.
display_name: The name of the field to display in the output.
cc_name: The name of the field to use in the generated C++ code; may
differ from `display_name`.
function_name: The C++ function to delegate printing the value to.
always_print: Whether to print the field if it has its default value.
"""
format_str = '%sresult += %s("%s ",%s%s, indent + 1, %s);\n'
for maybe_linebreak in [' ', '\n' + _indent(indent_level + 1)]:
args = (
_indent(indent_level), function_name, display_name, maybe_linebreak,
cc_name,
always_print)
result = format_str % args
# Best-effort attempt to fit within the expected line width.
if len(result) <= LINE_WIDTH:
break
return result
class OneOfPrettyPrinting(FieldPrettyPrinting):
"""Generates pretty-printing support for a oneof field.
This class represents the "whole" oneof, with all of its members nested, not
a single oneof member.
Note that all members of the oneof are nested (in `_fields` property).
"""
def __init__(self, field_desc, message_desc):
"""Args:
field_desc: nanopb.Field describing this oneof field.
message_desc: nanopb.Message describing the message containing this field.
"""
FieldPrettyPrinting.__init__(self, field_desc, message_desc)
self._full_classname = str(message_desc.name)
self._which = 'which_' + field_desc.name
self.is_anonymous = field_desc.anonymous
self._fields = [FieldPrettyPrinting(f, message_desc) for f in
field_desc.fields]
def __str__(self):
"""Generates a C++ statement that prints the oneof field, if it is set.
"""
which = self._which
result = '''\
switch (%s) {\n''' % which
for f in self._fields:
tag_name = '%s_%s_tag' % (self._full_classname, f.name)
result += '''\
case %s:\n''' % tag_name
# If oneof is set, always print that member, even if it's zero or empty.
result += f._generate_for_leaf(indent=2, parent_oneof=self,
always_print=True)
result += '''\
break;\n'''
result += '''\
}\n'''
return result
class EnumPrettyPrinting:
"""Generates pretty-printing support for an enumeration.
Adds the following free function to the file:
const char* EnumToString(SomeEnumType value);
Because the generated code is split between a header and a source, the
declaration and definition are generated separately.
The output of the generated function represents the string value of the given
enum constant. If the given value is not part of the enum, a string
representing an error is returned.
"""
def __init__(self, enum_desc):
"""Args:
enum_desc: nanopb.Enum describing this enumeration.
"""
self.name = str(enum_desc.names)
self._members = [str(n) for n in enum_desc.value_longnames]
def generate_declaration(self):
"""Generates the declaration of a `EnumToString()` free function.
"""
# Best-effort attempt to fit within the expected line width.
format_str = 'const char* EnumToString(%s%s value);\n'
for maybe_linebreak in ['', '\n' + _indent(1)]:
args = (maybe_linebreak, self.name)
result = format_str % args
# Best-effort attempt to fit within the expected line width.
if len(result) <= LINE_WIDTH:
break
return result
def generate_definition(self):
"""Generates the definition of a `EnumToString()` free function.
"""
result = '''\
const char* EnumToString(
%s value) {
switch (value) {\n''' % self.name
for full_name in self._members:
short_name = full_name.replace('%s_' % self.name, '')
result += '''\
case %s:
return "%s";\n''' % (full_name, short_name)
result += '''\
}
return "<unknown enum value>";
}\n\n'''
return result
| 4,443
|
511
|
<filename>framework/src/media/demux/mpeg2ts/PATParser.cpp
/******************************************************************
*
* Copyright 2019 Samsung Electronics 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.
*
******************************************************************/
#include <debug.h>
#include "Mpeg2TsTypes.h"
#include "PATParser.h"
#define PAT_UNTIL_LAST_SECTION_NUMBER_LEN (9)
#define PAT_PROG_NUM_PID_LEN (4)
#define PAT_PROGRAM_NUMBER(buffer,idx) ((buffer[4 * (idx)] << 8) + buffer[4 * (idx) + 1])
#define PAT_PROGRAM_NUMBER_PID(buffer,idx) (((buffer[4 * (idx) + 2] << 8) + buffer[4 * (idx) + 3]) & 0x1FFF)
PATParser::PATParser()
: SectionParser(TABLE_ID)
, mTransportStreamId(0)
, mNetworkPID(INVALID_PID)
{
}
PATParser::~PATParser()
{
clearParser();
}
void PATParser::clearParser(void)
{
TableBase::resetTable();
deleteInfo();
}
void PATParser::deleteInfo(void)
{
mTransportStreamId = 0;
mNetworkPID = INVALID_PID;
mProgramMap.clear();
}
bool PATParser::parseInfo(uint8_t *pData, uint32_t size)
{
auto sectionState = checkSection(mVersionNumber, mSectionNumber, mLastSectionNumber, mCrc32);
switch (sectionState) {
case SECTION_INITIAL: // fall through
case SECTION_CHANGE: // fall through
case SECTION_APPEND: {
mTransportStreamId = mTableIdExtension;
int i;
for (i = 0; i < ((mSectionLength - PAT_UNTIL_LAST_SECTION_NUMBER_LEN) / PAT_PROG_NUM_PID_LEN); i++) {
addProgram(PAT_PROGRAM_NUMBER(pData, i), PAT_PROGRAM_NUMBER_PID(pData, i));
}
return isCompleted();
}
case SECTION_IGNORE: // fall through
case SECTION_PRESENT: // fall through
default:
medvdbg("PAT section state : %d\n", sectionState);
return false;
}
}
size_t PATParser::sizeOfProgram(void)
{
return mProgramMap.size();
}
prog_num_t PATParser::getProgramNumber(uint32_t index)
{
if (index >= mProgramMap.size()) {
return INVALID_PN;
}
uint32_t curr = 0;
auto it = mProgramMap.begin();
while (it != mProgramMap.end()) {
if (index == curr++) {
return (prog_num_t)it->first;
}
it++;
}
return INVALID_PN;
}
ts_pid_t PATParser::getProgramMapPID(prog_num_t programNumber)
{
auto it = mProgramMap.find(programNumber);
if (it == mProgramMap.end()) {
meddbg("[getProgramMapPID] pn %d -> INVALID_PID\n", programNumber);
return INVALID_PID;
}
medvdbg("[getProgramMapPID] pn %d -> pmt pid 0x%x\n", programNumber, it->second);
return it->second;
}
void PATParser::addProgram(prog_num_t programNumber, ts_pid_t programPID)
{
// program number 0 is reserved to specify the network PID
if (programNumber == PATParser::NETWORK_PID_PN) {
medvdbg("NIT table pid 0x%04x\n", programPID);
mNetworkPID = programPID;
return ;
}
medvdbg("program %d pid 0x%x\n", programNumber, programPID);
mProgramMap[programNumber] = programPID;
}
bool PATParser::isRecv(void)
{
if (SectionParser::isRecv()) {
return isCompleted();
}
return false;
}
| 1,316
|
1,796
|
package nisrulz.github.sample.usingroomorm;
import androidx.room.Database;
import androidx.room.RoomDatabase;
@Database(entities = {
Person.class /*, AnotherEntityType.class, AThirdEntityType.class */
}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract PersonDao getPersonDao();
}
| 96
|
17,702
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
#pragma once
#include "stdafx.h"
#include "CNTKLibrary.h"
#include <fstream>
namespace CNTK
{
struct VariableFields final : public std::enable_shared_from_this<VariableFields>
{
friend class CompositeFunction;
NDShape m_shape;
VariableKind m_varKind;
::CNTK::DataType m_dataType;
std::weak_ptr<Function> m_ownerFunction;
std::unique_ptr<std::once_flag> m_initValueFlag;
NDArrayViewPtr m_value;
std::unique_ptr<ParameterInitializer> m_valueInitializer;
std::unique_ptr<DeviceDescriptor> m_valueInitializationDevice;
bool m_needsGradient;
std::wstring m_name;
std::vector<Axis> m_dynamicAxes;
bool m_isSparse;
std::wstring m_uid;
std::atomic<size_t> m_valueTimeStamp;
Variable m_blockFunctionVariableMapping;
VariableFields(const NDShape& shape, VariableKind varType, ::CNTK::DataType type, const std::weak_ptr<Function>& ownerFunction, const NDArrayViewPtr& value, bool needsGradient, const std::vector<Axis>& dynamicAxes, bool isSparse, const std::wstring& name, const std::wstring& uid)
: m_shape(shape), m_varKind(varType), m_dataType(type), m_ownerFunction(ownerFunction), m_value(value), m_needsGradient(needsGradient), m_dynamicAxes(dynamicAxes), m_isSparse(isSparse), m_name(name), m_uid(uid), m_valueTimeStamp(0)
{
if (value && (type != value->GetDataType()))
InvalidArgument("The DataType of the Parameter/Constant Variable '%S' does not match the DataType of the associated Value", AsString().c_str());
// Validate that each of the dynamic axes are unique
std::unordered_set<Axis> uniqueDynamicAxis;
for (auto& currentDynamicAxis : dynamicAxes)
{
auto retVal = uniqueDynamicAxis.insert(currentDynamicAxis);
if (!retVal.second)
InvalidArgument("Dynamic axis named %S is specified more than once for Variable '%S'", currentDynamicAxis.Name().c_str(), AsString().c_str());
}
if (m_varKind == VariableKind::Input)
{
for (auto dim : m_shape.Dimensions())
{
if (dim == 0)
InvalidArgument("Variable '%S' has invalid shape '%S'.", AsString().c_str(), m_shape.AsString().c_str());
}
}
if ((m_varKind == VariableKind::Parameter) || (m_varKind == VariableKind::Constant))
{
if (m_shape.HasFreeDimension())
InvalidArgument("Parameter/Constant '%S' has invalid shape '%S'; it is illegal for a Parameter/Constant to have a FreeDimension.", AsString().c_str(), m_shape.AsString().c_str());
}
}
std::wstring AsString() const;
std::shared_ptr<VariableFields> Clone() const;
FunctionPtr Owner() const;
CNTK_API void SetValueInitialization(const ParameterInitializer& initializationConfig, const DeviceDescriptor& device);
private:
// Disallow copy and move construction and assignment
VariableFields(const VariableFields&) = delete; VariableFields& operator=(const VariableFields& other) = delete; VariableFields(VariableFields&&) = delete; VariableFields& operator=(VariableFields&&) = delete;
};
}
| 1,462
|
808
|
<filename>benchmarks/symbench.cpp
#include <iostream>
#include <chrono>
#include <iomanip>
#include <symengine/basic.h>
#include <symengine/add.h>
#include <symengine/symbol.h>
#include <symengine/integer.h>
#include <symengine/mul.h>
#include <symengine/pow.h>
#include <symengine/constants.h>
#include <symengine/real_double.h>
#include <symengine/functions.h>
using SymEngine::add;
using SymEngine::Basic;
using SymEngine::cos;
using SymEngine::div;
using SymEngine::expand;
using SymEngine::I;
using SymEngine::iaddnum;
using SymEngine::integer;
using SymEngine::Integer;
using SymEngine::mul;
using SymEngine::Number;
using SymEngine::one;
using SymEngine::pi;
using SymEngine::pow;
using SymEngine::RCP;
using SymEngine::rcp_static_cast;
using SymEngine::RCPBasicKeyLess;
using SymEngine::real_double;
using SymEngine::sin;
using SymEngine::sub;
using SymEngine::symbol;
using SymEngine::Symbol;
using SymEngine::vec_basic;
using SymEngine::zero;
double R1();
double R2();
double R3();
double R5();
double R7();
double R8();
double S1();
double S2();
double S3();
double S3a();
int main(int argc, char *argv[])
{
SymEngine::print_stack_on_segfault();
std::cout << "Time for R1 : \t " << std::setw(15) << std::setprecision(9)
<< std::fixed << R1() << std::endl;
std::cout << "Time for R2 : \t " << std::setw(15) << std::setprecision(9)
<< std::fixed << R2() << std::endl;
std::cout << "Time for R3 : \t " << std::setw(15) << std::setprecision(9)
<< std::fixed << R3() << std::endl;
std::cout << "Time for R5 : \t " << std::setw(15) << std::setprecision(9)
<< std::fixed << R5() << std::endl;
std::cout << "Time for R7 : \t " << std::setw(15) << std::setprecision(9)
<< std::fixed << R7() << std::endl;
std::cout << "Time for R8 : \t " << std::setw(15) << std::setprecision(9)
<< std::fixed << R8() << std::endl;
std::cout << "Time for S1 : \t " << std::setw(15) << std::setprecision(9)
<< std::fixed << S1() << std::endl;
std::cout << "Time for S2 : \t " << std::setw(15) << std::setprecision(9)
<< std::fixed << S2() << std::endl;
std::cout << "Time for S3 : \t " << std::setw(15) << std::setprecision(9)
<< std::fixed << S3() << std::endl;
std::cout << "Time for S3a : \t " << std::setw(15) << std::setprecision(9)
<< std::fixed << S3a() << std::endl;
return 0;
}
RCP<const Basic> f(RCP<const Basic> z)
{
return add(mul(sqrt(div(one, integer(3))), pow(z, integer(2))),
div(I, integer(3)));
}
double R1()
{
RCP<const Basic> g;
RCP<const Basic> h = div(I, integer(2));
auto t1 = std::chrono::high_resolution_clock::now();
RCP<const Basic> real, imag;
as_real_imag(f(f(f(f(f(f(f(f(f(f(h)))))))))), outArg(real), outArg(imag));
auto t2 = std::chrono::high_resolution_clock::now();
return std::chrono::duration<double>(t2 - t1).count();
}
RCP<const Basic> hermite(RCP<const Integer> n, RCP<const Basic> y)
{
if (eq(*n, *one))
return mul(y, integer(2));
if (eq(*n, *zero))
return one;
return expand(
sub(mul(mul(integer(2), y), hermite(n->subint(*one), y)),
mul(integer(2),
mul(n->subint(*one), hermite(n->subint(*integer(2)), y)))));
}
double R2()
{
RCP<const Basic> g;
RCP<const Integer> n = integer(15);
RCP<const Basic> y = symbol("y");
auto t1 = std::chrono::high_resolution_clock::now();
g = hermite(n, y);
auto t2 = std::chrono::high_resolution_clock::now();
return std::chrono::duration<double>(t2 - t1).count();
}
double R3()
{
RCP<const Basic> x = symbol("x");
RCP<const Basic> y = symbol("y");
RCP<const Basic> z = symbol("z");
RCP<const Basic> f = add(x, add(y, z));
std::vector<bool> vec;
vec.reserve(10);
auto t1 = std::chrono::high_resolution_clock::now();
for (int i = 0; i < 10; i++) {
vec.push_back(eq(*f, *f));
}
auto t2 = std::chrono::high_resolution_clock::now();
return std::chrono::duration<double>(t2 - t1).count();
}
double R5()
{
RCP<const Basic> x = symbol("x");
RCP<const Basic> y = symbol("y");
RCP<const Basic> z = symbol("z");
RCP<const Basic> f = add(x, add(y, z));
vec_basic v;
v.push_back(x);
v.push_back(y);
v.push_back(z);
for (int i = 0; i < 8; i++) {
v.push_back(add(v[i], add(v[i + 1], v[i + 2])));
}
auto t1 = std::chrono::high_resolution_clock::now();
std::set<RCP<const Basic>, RCPBasicKeyLess> s(v.begin(), v.end());
auto t2 = std::chrono::high_resolution_clock::now();
return std::chrono::duration<double>(t2 - t1).count();
}
double R7()
{
RCP<const Basic> x = symbol("x");
RCP<const Basic> f
= add(pow(x, integer(24)),
add(mul(integer(34), pow(x, integer(12))),
add(mul(integer(45), pow(x, integer(3))),
add(mul(integer(9), pow(x, integer(18))),
add(mul(integer(34), pow(x, integer(10))),
mul(integer(32), pow(x, integer(21))))))));
vec_basic v;
auto t1 = std::chrono::high_resolution_clock::now();
for (int i = 0; i < 10000; ++i) {
v.push_back(f->subs({{x, real_double(0.5)}}));
}
auto t2 = std::chrono::high_resolution_clock::now();
return std::chrono::duration<double>(t2 - t1).count();
}
RCP<const Basic> right(const RCP<const Basic> &f, const RCP<const Number> &a,
const RCP<const Number> &b, const RCP<const Basic> &x,
int n)
{
RCP<const Number> Deltax = b->sub(*a)->div(*integer(n));
RCP<const Number> c = a;
RCP<const Number> est = integer(0);
for (int i = 0; i < n; i++) {
iaddnum(outArg(c), Deltax);
iaddnum(outArg(est), rcp_static_cast<const Number>(f->subs({{x, c}})));
}
return mulnum(est, Deltax);
}
double R8()
{
RCP<const Basic> x = symbol("x");
auto t1 = std::chrono::high_resolution_clock::now();
x = right(pow(x, integer(2)), integer(0), integer(5), x, 10000);
auto t2 = std::chrono::high_resolution_clock::now();
return std::chrono::duration<double>(t2 - t1).count();
}
double S1()
{
RCP<const Basic> x = symbol("x");
RCP<const Basic> y = symbol("y");
RCP<const Basic> z = symbol("z");
RCP<const Basic> e;
RCP<const Basic> f;
e = pow(add(x, add(y, add(z, one))), integer(7));
f = mul(e, add(e, one));
auto t1 = std::chrono::high_resolution_clock::now();
f = expand(f);
auto t2 = std::chrono::high_resolution_clock::now();
return std::chrono::duration<double>(t2 - t1).count();
}
double S2()
{
RCP<const Basic> x = symbol("x");
RCP<const Basic> y = symbol("y");
RCP<const Basic> z = symbol("z");
RCP<const Basic> e;
RCP<const Basic> f;
e = pow(add(pow(x, sin(x)), add(pow(y, cos(y)), pow(z, add(x, y)))),
integer(100));
auto t1 = std::chrono::high_resolution_clock::now();
f = expand(e);
auto t2 = std::chrono::high_resolution_clock::now();
return std::chrono::duration<double>(t2 - t1).count();
}
double S3()
{
RCP<const Basic> x = symbol("x");
RCP<const Basic> y = symbol("y");
RCP<const Basic> z = symbol("z");
RCP<const Basic> e;
RCP<const Basic> f;
e = pow(add(pow(x, y), add(pow(y, z), pow(z, x))), integer(50));
e = expand(e);
auto t1 = std::chrono::high_resolution_clock::now();
f = e->diff(rcp_static_cast<const Symbol>(x));
auto t2 = std::chrono::high_resolution_clock::now();
return std::chrono::duration<double>(t2 - t1).count();
}
double S3a()
{
RCP<const Basic> x = symbol("x");
RCP<const Basic> y = symbol("y");
RCP<const Basic> z = symbol("z");
RCP<const Basic> e;
RCP<const Basic> f;
e = pow(add(pow(x, y), add(pow(y, z), pow(z, x))), integer(500));
e = expand(e);
auto t1 = std::chrono::high_resolution_clock::now();
f = e->diff(rcp_static_cast<const Symbol>(x));
auto t2 = std::chrono::high_resolution_clock::now();
return std::chrono::duration<double>(t2 - t1).count();
}
| 3,709
|
406
|
<filename>src/data_layer/ft_layer_tid2013.py
import cv2
import caffe
import numpy as np
import multiprocessing as mtp
import pdb
import os.path as osp
class DataLayer(caffe.Layer):
def setup(self, bottom, top):
self._name_to_top_map = {}
self._name_to_top_map['data'] = 0
self._name_to_top_map['label'] = 1
# === Read input parameters ===
self.workers= mtp.Pool(10)
# params is a python dictionary with layer parameters.
params = eval(self.param_str)
# Check the paramameters for validity.
check_params(params)
# store input as class variables
self.batch_size = params['batch_size']
self.pascal_root = params['pascal_root']
self.im_shape = params['im_shape']
# get list of image indexes.
list_file = params['split'] + '.txt'
filename = [line.rstrip('\n') for line in open(
osp.join(self.pascal_root, list_file))]
self._roidb = []
self.scores =[]
for i in filename:
self._roidb.append(i.split()[0])
self.scores.append(float(i.split()[1]))
self._perm = None
self._cur = 0
self._shuffle_roidb_inds()
top[0].reshape(
self.batch_size, 3, params['im_shape'][0], params['im_shape'][1])
top[1].reshape(self.batch_size, 1)
def _shuffle_roidb_inds(self):
"""Randomly permute the training roidb."""
self._perm = np.random.permutation(np.arange(len(self._roidb)))
self._cur = 0
def _get_next_minibatch_inds(self):
"""Return the roidb indices for the next minibatch."""
# TODO(rbg): remove duplicated code
if self._cur + self.batch_size >= len(self._roidb):
self._shuffle_roidb_inds()
db_inds = self._perm[self._cur:self._cur + self.batch_size ]
self._cur += self.batch_size
return db_inds
def get_minibatch(self,minibatch_db):
"""Given a roidb, construct a minibatch sampled from it."""
jobs =self.workers.map(preprocess,minibatch_db)
#print len(jobs)
index = 0
images_train = np.zeros([self.batch_size,3,224,224],np.float32)
#pdb.set_trace()
for index_job in range(len(jobs)):
images_train[index,:,:,:] = jobs[index_job]
index += 1
blobs = {'data': images_train}
return blobs
def forward(self, bottom, top):
"""Get blobs and copy them into this layer's top blob vector."""
db_inds = self._get_next_minibatch_inds()
minibatch_db = []
for i in range(len(db_inds)):
minibatch_db.append(self._roidb[int(db_inds[i])])
#minibatch_db = [self._roidb[i] for i in db_inds]
#print minibatch_db
scores = []
for i in range(len(db_inds)):
scores.append(self.scores[int(db_inds[i])])
ind = np.argsort(scores)
ind_minibatch_db = []
for i in range(len(ind)-1,-1,-1):
ind_minibatch_db.append(minibatch_db[ind[i]])
blobs = self.get_minibatch(ind_minibatch_db)
blobs ['label'] =np.asarray(sorted(scores,reverse=True))
for blob_name, blob in blobs.iteritems():
top_ind = self._name_to_top_map[blob_name]
# Reshape net's input blobs
top[top_ind].reshape(*(blob.shape))
# Copy data into net's input blobs
top[top_ind].data[...] = blob.astype(np.float32, copy=False)
def backward(self, top, propagate_down, bottom):
"""This layer does not propagate gradients."""
pass
def reshape(self, bottom, top):
"""Reshaping happens during the call to forward."""
pass
def preprocess(data):
im = np.asarray(cv2.imread(data))
x = im.shape[0]
y = im.shape[1]
x_p = np.random.randint(x-224,size=1)[0]
y_p = np.random.randint(y-224,size=1)[0]
#print x_p,y_p
images = im[x_p:x_p+224,y_p:y_p+224,:].transpose([2,0,1])
#print images.shape
return images
def check_params(params):
"""
A utility function to check the parameters for the data layers.
"""
assert 'split' in params.keys(
), 'Params must include split (train, val, or test).'
required = ['batch_size', 'pascal_root', 'im_shape']
for r in required:
assert r in params.keys(), 'Params must include {}'.format(r)
| 2,118
|
7,158
|
<reponame>Nondzu/opencv_contrib
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include "precomp.hpp"
#include "hfs_core.hpp"
#include <vector>
using namespace std;
namespace cv{ namespace hfs{
const Point DIRECTION4[5] =
{
Point(-1, 0),
Point(0, -1),
Point(1, 0),
Point(0, 1),
Point(0, 0)
};
const Point CIRCLE2[13] =
{
Point(0, 1), Point(0, 2), Point(1, 1),
Point(1, 0), Point(2, 0), Point(1, -1),
Point(0, -1), Point(0, -2), Point(-1, -1),
Point(-1, 0), Point(-2, 0), Point(-1, 1),
Point(0, 0)
};
HfsCore::HfsCore(int height, int width,
float segThresholdI, int minRegionSizeI, float segThresholdII, int minRegionSizeII,
float spatialWeight, int spixelSize, int numIter)
{
hfsSettings.egbThresholdI = segThresholdI;
hfsSettings.minRegionSizeI = minRegionSizeI;
hfsSettings.egbThresholdII = segThresholdII;
hfsSettings.minRegionSizeII = minRegionSizeII;
hfsSettings.slicSettings.img_size.y = height;
hfsSettings.slicSettings.img_size.x = width;
hfsSettings.slicSettings.coh_weight = spatialWeight;
hfsSettings.slicSettings.spixel_size = spixelSize;
hfsSettings.slicSettings.num_iters = numIter;
constructEngine();
float weight1[] = { -0.0024710407f, 0.00608298f,
0.0047505307f, 0.0051097558f, 0.00089799752f };
float weight2[] = { -0.0040629096f, 0.010430338f,
0.0092625152f, 0.004976281f, 0.0037279273f };
w1.resize(sizeof(weight1) / sizeof(weight1[0]));
w2.resize(sizeof(weight2) / sizeof(weight2[0]));
memcpy(w1.data(), weight1, sizeof(weight1));
memcpy(w2.data(), weight2, sizeof(weight2));
}
void HfsCore::constructEngine()
{
mag_engine = Ptr<Magnitude>(
new Magnitude(hfsSettings.slicSettings.img_size.y,
hfsSettings.slicSettings.img_size.x));
#ifdef _HFS_CUDA_ON_
gslic_engine = Ptr<slic::engines::CoreEngine>(
new slic::engines::CoreEngine(hfsSettings.slicSettings));
in_img = Ptr<UChar4Image>(
new UChar4Image(hfsSettings.slicSettings.img_size));
out_img = Ptr<UChar4Image>(
new UChar4Image(hfsSettings.slicSettings.img_size));
#endif
}
void HfsCore::reconstructEngine()
{
#ifdef _HFS_CUDA_ON_
gslic_engine = Ptr<slic::engines::CoreEngine>(
new slic::engines::CoreEngine(hfsSettings.slicSettings));
#endif
}
HfsCore::~HfsCore(){}
void HfsCore::loadImage( const Mat& inimg, Ptr<UChar4Image> outimg )
{
Vector4u* outimg_ptr = outimg->getCpuData();
for ( int y = 0; y < inimg.rows; y++ )
{
const Vec3b *ptr = inimg.ptr<Vec3b>(y);
for ( int x = 0; x < inimg.cols; x++ )
{
int idx = x + y * inimg.cols;
outimg_ptr[idx].z = ptr[x][0];
outimg_ptr[idx].y = ptr[x][1];
outimg_ptr[idx].x = ptr[x][2];
}
}
}
Mat HfsCore::getSLICIdxCpu(const Mat& img3u, int &num_css)
{
const int _h = img3u.rows;
const int _w = img3u.cols;
const int _s = _h*_w;
slic::cSLIC cslic;
vector<int> idx_img = cslic.generate_superpixels(img3u,
hfsSettings.slicSettings.spixel_size, hfsSettings.slicSettings.coh_weight);
num_css = 0;
int _max =
(int)ceil((float)_w / 8.0f)*(int)ceil((float)_h / 8.0f);
vector<int> indexes(_max, 0);
for (int i = 0; i < _s; i++)
indexes[idx_img[i]]++;
for (int i = 0; i < _max; i++)
indexes[i] = (indexes[i] != 0) ? num_css++ : 0;
for (int i = 0; i < _s; i++)
idx_img[i] = indexes[idx_img[i]];
Mat idx_mat(_h, _w, CV_32S, idx_img.data());
idx_mat.convertTo(idx_mat, CV_16U);
return idx_mat;
}
Vec4f HfsCore::getColorFeature( const Vec3f& in1, const Vec3f& in2 )
{
Vec4f feature;
Vec3f diff = (in1 - in2);
feature[0] = abs(diff[0]);
feature[1] = abs(diff[1]);
feature[2] = abs(diff[2]);
feature[3] = getEulerDistance( in1, in2 );
return feature;
}
int HfsCore::getAvgGradientBdry( const Mat& idx_mat,
const vector<Mat>& mag1us, int num_css, Mat& bd_num,
vector<Mat>& gradients )
{
const int _h = idx_mat.rows;
const int _w = idx_mat.cols;
const int size = (int)mag1us.size();
gradients.resize(size);
for (int i = 0; i < size; i++)
{
gradients[i].create(num_css, num_css, CV_32F);
gradients[i] = Scalar::all(0);
}
bd_num.create(num_css, num_css, CV_32F);
bd_num = Scalar::all(0);
for (int r = 1; r < _h - 1; r++)
for (int c = 1; c < _w - 1; c++)
{
ushort curr = idx_mat.at<ushort>(r, c);
ushort pre, tmp = 0, v[4];
Point p1(c, r), p2;
for (int k = 0; k < 4; k++)
{
p2 = p1 + DIRECTION4[k];
pre = idx_mat.at<ushort>(p2);
if (pre != curr)
{
bool flag = true;
for (int t = 0; t < tmp; t++)
{
if (v[t] == pre)
flag = false;
}
if (flag)
v[tmp++] = pre;
}
}
if (tmp > 0)
{
for (int n = 0; n < size; n++)
{
int u[13]; float m[13];
for (int k = 0; k < 13; k++)
{
p2 = p1 + CIRCLE2[k];
if (!(p2.x >= 0 && p2.x < _w && p2.y >= 0 && p2.y < _h))
{
u[k] = -1, m[k] = 0;
continue;
}
u[k] = idx_mat.at<ushort>(p2);
m[k] = mag1us[n].at<uchar>(p2);
}
for (int t = 0; t < tmp; t++)
{
float m_max = 0;
for (int k = 0; k < 13; k++)
{
if ((u[k] == curr || u[k] == v[t]) && m[k] > m_max)
m_max = m[k];
}
gradients[n].at<float>(curr, v[t]) += m_max;
gradients[n].at<float>(v[t], curr) += m_max;
bd_num.at<float>(curr, v[t])++;
bd_num.at<float>(v[t], curr)++;
}
}
}
}
int num = 0;
for (int r_ = 0; r_ < num_css; r_++)
for (int c_ = 0; c_ < num_css; c_++)
{
if (abs(bd_num.at<float>(r_, c_)) > DOUBLE_EPS)
{
for (int i = 0; i < size; i++)
gradients[i].at<float>(r_, c_) /= bd_num.at<float>(r_, c_);
num++;
}
}
return num;
}
void HfsCore::getSegmentationI( const Mat &lab3u, const Mat &mag1u,
const Mat &idx_mat, float c, int min_size, Mat &seg, int &num_css)
{
const int _h = lab3u.rows;
const int _w = lab3u.cols;
vector<vector<int> > adjacent(num_css), bdPixNum(num_css);
vector<vector<float> > bdGradient(num_css);
for (int r_ = 1; r_ < _h - 1; r_++)
for (int c_ = 1; c_ < _w - 1; c_++)
{
ushort curr = idx_mat.at<ushort>(r_, c_);
for (int k = 0; k < 4; k++)
{
Point p = Point(c_, r_) + DIRECTION4[k];
ushort pre = idx_mat.at<ushort>(p);
if (curr > pre)
{
float maxG = max(mag1u.at<uchar>(p), mag1u.at<uchar>(r_, c_));
vector<int>::iterator iter =
find(adjacent[curr].begin(), adjacent[curr].end(), pre);
if (iter == adjacent[curr].end())
{
adjacent[curr].push_back(pre);
bdGradient[curr].push_back(maxG);
bdPixNum[curr].push_back(1);
}
else
{
int temp = (int)(iter - adjacent[curr].begin());
bdGradient[curr][temp] += maxG;
bdPixNum[curr][temp] += 1;
}
}
}
}
for (size_t i = 0; i < (size_t)num_css; i++)
for (size_t j = 0; j < adjacent[i].size(); j++)
bdGradient[i][j] /= bdPixNum[i][j];
int num = 0;
for (int i = 0; i < num_css; i++)
num += (int)adjacent[i].size();
vector<int> numR(num_css, 0);
vector<Vec3f> avg_color(num_css, Vec3f(0, 0, 0));
for (int r_ = 0; r_ < _h; r_++)
{
const ushort *iP = idx_mat.ptr<ushort>(r_);
const Vec3b *cP = lab3u.ptr<Vec3b>(r_);
for (int c_ = 0; c_ < _w; c_++)
avg_color[iP[c_]] += cP[c_], numR[iP[c_]]++;
}
for (int i = 0; i < num_css; i++)
avg_color[i] /= numR[i];
vector<Edge> edges(num);
int index = 0;
for (int i = 0; i < num_css; i++)
{
int adjaNum = (int)adjacent[i].size();
for (int j = 0; j < adjaNum; j++)
{
edges[index].a = i;
edges[index].b = adjacent[i][j];
Vec4f fcolor =
getColorFeature(avg_color[i], avg_color[adjacent[i][j]]);
edges[index++].w =
fcolor[0] * w1[0] + fcolor[1] * w1[1]+
fcolor[2] * w1[2] + fcolor[3] * w1[3]+
bdGradient[i][j] * w1[4];
}
}
CV_Assert(num == index);
Ptr<RegionSet> regions = egb_merge(num_css, num, edges, c, numR);
for (int i = 0; i < num; i++)
{
int a = regions->find(edges[i].a);
int b = regions->find(edges[i].b);
if ((a != b) && ((regions->numPix(a) < min_size) || (regions->numPix(b) < min_size)))
regions->join(a, b);
}
int idx = 1; vector<int> reg2ind(num_css), indexes(num_css);
std::memset(indexes.data(), 0, num_css*sizeof(int));
for (int i = 0; i < num_css; i++)
{
int comp = regions->find(i);
if (!indexes[comp])
indexes[comp] = idx++;
reg2ind[i] = indexes[comp];
}
CV_Assert(regions->num_sets() == idx - 1);
seg.create(_h, _w, CV_16U);
for (int r_ = 0; r_ < _h; r_++)
{
ushort *sP = seg.ptr<ushort>(r_);
const ushort *iP = idx_mat.ptr<ushort>(r_);
for (int c_ = 0; c_ < _w; c_++)
sP[c_] = (ushort)reg2ind[iP[c_]];
}
num_css = idx;
}
void HfsCore::getSegmentationII(
const Mat &lab3u, const Mat &mag1u, const Mat &idx_mat,
float c, int min_size, Mat &seg, int &num_css)
{
const int _h = lab3u.rows;
const int _w = lab3u.cols;
vector<Mat> mag1us, gradients;
Mat bd_num, texture;
mag1us.push_back(mag1u);
int num = getAvgGradientBdry(idx_mat, mag1us,
num_css, bd_num, gradients);
// const int size = (int)gradients.size();
CV_Assert(num % 2 == 0);
num /= 2;
vector<int> num_pix(num_css, 0);
vector<Vec3f> avg_color(num_css, Vec3f(0, 0, 0));
for (int r_ = 0; r_ < _h; r_++)
{
const ushort *idx_ptr = idx_mat.ptr<ushort>(r_);
const Vec3b *clr_ptr = lab3u.ptr<Vec3b>(r_);
for (int c_ = 0; c_ < _w; c_++)
num_pix[idx_ptr[c_]]++, avg_color[idx_ptr[c_]] += clr_ptr[c_];
}
for (int i = 1; i < num_css; i++)
avg_color[i] /= num_pix[i];
vector<Edge> edges(num);
int index = 0;
for (int r_ = 0; r_ < num_css; r_++)
for (int c_ = 0; c_ < r_; c_++)
{
if (bd_num.at<int>(r_, c_) == 0) continue;
edges[index].a = r_;
edges[index].b = c_;
Vec4f fcolor = getColorFeature(avg_color[r_], avg_color[c_]);
edges[index].w =
fcolor[0] * w2[0] + fcolor[1] * w2[1]+
fcolor[2] * w2[2] + fcolor[3] * w2[3];
edges[index].w += gradients[0].at<float>(r_, c_)*w2[4];
index++;
}
CV_Assert(num == index);
Ptr<RegionSet> regions = egb_merge(num_css, num, edges, c, num_pix);
for (int i = 0; i < num; i++)
{
int a = regions->find(edges[i].a);
int b = regions->find(edges[i].b);
if ((a != b) && ((regions->numPix(a) < min_size)
|| (regions->numPix(b) < min_size)))
regions->join(a, b);
}
int idx = 1;
vector<int> reg2ind(num_css), indexes(num_css, 0);
for (int i = 1; i < num_css; i++)
{
int comp = regions->find(i);
if (!indexes[comp])
indexes[comp] = idx++;
reg2ind[i] = indexes[comp];
}
CV_Assert(regions->num_sets() == idx);
seg.create(_h, _w, CV_16U);
for (int r_ = 0; r_ < _h; r_++)
{
ushort *sP = seg.ptr<ushort>(r_);
const ushort *iP = idx_mat.ptr<ushort>(r_);
for (int c_ = 0; c_ < _w; c_++)
sP[c_] = (ushort)reg2ind[iP[c_]];
}
num_css = idx - 1;
}
void HfsCore::drawSegmentationRes( const Mat& seg,
const Mat& img3u, int num_css, Mat &show )
{
const int _h = img3u.rows;
const int _w = img3u.cols;
vector<int> region_size(num_css, 0);
vector<Vec3f> avg_color(num_css, Vec3f(0, 0, 0));
for (int r = 0; r < _h; r++)
{
const Vec3b* imP = img3u.ptr<Vec3b>(r);
const ushort* segP = seg.ptr<ushort>(r);
for (int c = 0; c < _w; c++)
{
avg_color[segP[c] - 1] += imP[c];
region_size[segP[c] - 1]++;
}
}
for (int i = 0; i < num_css; i++)
avg_color[i] /= region_size[i];
show.create(img3u.size(), img3u.type());
for (int r = 0; r < _h; r++)
{
Vec3b *data = show.ptr<Vec3b>(r);
const ushort* seg_ptr = seg.ptr<ushort>(r);
for (int c = 0; c < _w; c++)
data[c] = avg_color[seg_ptr[c] - 1];
}
}
int HfsCore::processImageCpu(const Mat &img3u, Mat &seg)
{
Mat idx_mat, lab3u, mag1u, tmp;
int num_css;
idx_mat = getSLICIdxCpu(img3u, num_css);
cv::cvtColor(img3u, lab3u, COLOR_BGR2Lab);
mag_engine->processImgCpu(img3u, mag1u);
getSegmentationI( lab3u, mag1u, idx_mat,
hfsSettings.egbThresholdI, hfsSettings.minRegionSizeI, tmp, num_css );
getSegmentationII(lab3u, mag1u, tmp,
hfsSettings.egbThresholdII, hfsSettings.minRegionSizeII, seg, num_css);
return num_css;
}
int HfsCore::processImageGpu(const Mat &img3u, Mat &seg)
{
#ifdef _HFS_CUDA_ON_
Mat idx_mat, lab3u, mag1u, tmp;
int num_css;
idx_mat = getSLICIdxGpu(img3u, num_css);
cv::cvtColor(img3u, lab3u, COLOR_BGR2Lab);
mag_engine->processImgGpu(img3u, mag1u);
getSegmentationI(lab3u, mag1u, idx_mat,
hfsSettings.egbThresholdI, hfsSettings.minRegionSizeI, tmp, num_css);
getSegmentationII(lab3u, mag1u, tmp,
hfsSettings.egbThresholdII, hfsSettings.minRegionSizeII, seg, num_css);
return num_css;
#else
return processImageCpu(img3u, seg);
#endif
}
#ifdef _HFS_CUDA_ON_
Mat HfsCore::getSLICIdxGpu(const Mat& img3u, int &num_css)
{
const int _h = img3u.rows;
const int _w = img3u.cols;
const int _s = _h*_w;
loadImage(img3u, in_img);
gslic_engine->setImageSize(img3u.cols, img3u.rows);
gslic_engine->processFrame(in_img);
const IntImage *idx_img = gslic_engine->getSegRes();
int* idx_img_ptr = (int*)idx_img->getCpuData();
num_css = 0;
int _max =
(int)ceil((float)_w / 8.0f)*(int)ceil((float)_h / 8.0f);
vector<int> indexes(_max, 0);
for (int i = 0; i < _s; i++)
indexes[idx_img_ptr[i]]++;
for (int i = 0; i < _max; i++)
indexes[i] = (indexes[i] != 0) ? num_css++ : 0;
for (int i = 0; i < _s; i++)
idx_img_ptr[i] = indexes[idx_img_ptr[i]];
Mat idx_mat(_h, _w, CV_32S, idx_img_ptr);
idx_mat.convertTo(idx_mat, CV_16U);
return idx_mat;
}
#endif
}}
| 8,463
|
897
|
<filename>C/cp/first_missing_positive_integer.c
#include <stdio.h>
#include <stdlib.h>
int main(){
int n;
printf("Enter the value of n: ");
scanf("%d\n",&n);
printf("Enter the array:\n");
int *arr = (int*)malloc(n * sizeof(int));
for (int i = 1; i <= n; ++i)
{
scanf("%d", &arr[i]);
}
if (arr == NULL) {
printf("Memory not allocated.\n");
return 0;
}
else {
for (int i = 1; i <= n; i++) {
if (arr[i] <= 0 || arr[i] > n)
continue;
int x = arr[i];
while (arr[x] != x) {
int next_ele = arr[x];
arr[x] = x;
x = next_ele;
if (x <= 0 || x > n)
break;
}
}
int ans = n + 1;
for (int i = 1; i <= n; i++) {
if (arr[i] != i) {
ans = i;
break;
}
}
printf("%d", ans);
}
return 0;
}
/*
Time Complexity: O(N)
Space Complexity: O(1)
OUTPUT
Enter the value of n: 4
Enter the array:
3 4 -1 1
2
*/
| 671
|
505
|
<filename>lib/samtools/htslib-1.5/realn.c
/* realn.c -- BAQ calculation and realignment.
Copyright (C) 2009-2011, 2014-2015 Genome Research Ltd.
Portions copyright (C) 2009-2011 Broad Institute.
Author: <NAME> <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. */
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "htslib/hts.h"
#include "htslib/sam.h"
int sam_cap_mapq(bam1_t *b, const char *ref, int ref_len, int thres)
{
uint8_t *seq = bam_get_seq(b), *qual = bam_get_qual(b);
uint32_t *cigar = bam_get_cigar(b);
bam1_core_t *c = &b->core;
int i, x, y, mm, q, len, clip_l, clip_q;
double t;
if (thres < 0) thres = 40; // set the default
mm = q = len = clip_l = clip_q = 0;
for (i = y = 0, x = c->pos; i < c->n_cigar; ++i) {
int j, l = cigar[i]>>4, op = cigar[i]&0xf;
if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) {
for (j = 0; j < l; ++j) {
int c1, c2, z = y + j;
if (x+j >= ref_len || ref[x+j] == '\0') break; // out of bounds
c1 = bam_seqi(seq, z), c2 = seq_nt16_table[(int)ref[x+j]];
if (c2 != 15 && c1 != 15 && qual[z] >= 13) { // not ambiguous
++len;
if (c1 && c1 != c2 && qual[z] >= 13) { // mismatch
++mm;
q += qual[z] > 33? 33 : qual[z];
}
}
}
if (j < l) break;
x += l; y += l; len += l;
} else if (op == BAM_CDEL) {
for (j = 0; j < l; ++j)
if (x+j >= ref_len || ref[x+j] == '\0') break;
if (j < l) break;
x += l;
} else if (op == BAM_CSOFT_CLIP) {
for (j = 0; j < l; ++j) clip_q += qual[y+j];
clip_l += l;
y += l;
} else if (op == BAM_CHARD_CLIP) {
clip_q += 13 * l;
clip_l += l;
} else if (op == BAM_CINS) y += l;
else if (op == BAM_CREF_SKIP) x += l;
}
for (i = 0, t = 1; i < mm; ++i)
t *= (double)len / (i+1);
t = q - 4.343 * log(t) + clip_q / 5.;
if (t > thres) return -1;
if (t < 0) t = 0;
t = sqrt((thres - t) / thres) * thres;
// fprintf(stderr, "%s %lf %d\n", bam_get_qname(b), t, q);
return (int)(t + .499);
}
int sam_prob_realn(bam1_t *b, const char *ref, int ref_len, int flag)
{
int k, i, bw, x, y, yb, ye, xb, xe, apply_baq = flag&1, extend_baq = flag>>1&1, redo_baq = flag&4;
uint32_t *cigar = bam_get_cigar(b);
bam1_core_t *c = &b->core;
probaln_par_t conf = { 0.001, 0.1, 10 };
uint8_t *bq = 0, *zq = 0, *qual = bam_get_qual(b);
if ((c->flag & BAM_FUNMAP) || b->core.l_qseq == 0 || qual[0] == (uint8_t)-1)
return -1; // do nothing
// test if BQ or ZQ is present
if ((bq = bam_aux_get(b, "BQ")) != 0) ++bq;
if ((zq = bam_aux_get(b, "ZQ")) != 0 && *zq == 'Z') ++zq;
if (bq && redo_baq)
{
bam_aux_del(b, bq-1);
bq = 0;
}
if (bq && zq) { // remove the ZQ tag
bam_aux_del(b, zq-1);
zq = 0;
}
if (bq || zq) {
if ((apply_baq && zq) || (!apply_baq && bq)) return -3; // in both cases, do nothing
if (bq && apply_baq) { // then convert BQ to ZQ
for (i = 0; i < c->l_qseq; ++i)
qual[i] = qual[i] + 64 < bq[i]? 0 : qual[i] - ((int)bq[i] - 64);
*(bq - 3) = 'Z';
} else if (zq && !apply_baq) { // then convert ZQ to BQ
for (i = 0; i < c->l_qseq; ++i)
qual[i] += (int)zq[i] - 64;
*(zq - 3) = 'B';
}
return 0;
}
// find the start and end of the alignment
x = c->pos, y = 0, yb = ye = xb = xe = -1;
for (k = 0; k < c->n_cigar; ++k) {
int op, l;
op = cigar[k]&0xf; l = cigar[k]>>4;
if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) {
if (yb < 0) yb = y;
if (xb < 0) xb = x;
ye = y + l; xe = x + l;
x += l; y += l;
} else if (op == BAM_CSOFT_CLIP || op == BAM_CINS) y += l;
else if (op == BAM_CDEL) x += l;
else if (op == BAM_CREF_SKIP) return -1; // do nothing if there is a reference skip
}
// set bandwidth and the start and the end
bw = 7;
if (abs((xe - xb) - (ye - yb)) > bw)
bw = abs((xe - xb) - (ye - yb)) + 3;
conf.bw = bw;
xb -= yb + bw/2; if (xb < 0) xb = 0;
xe += c->l_qseq - ye + bw/2;
if (xe - xb - c->l_qseq > bw)
xb += (xe - xb - c->l_qseq - bw) / 2, xe -= (xe - xb - c->l_qseq - bw) / 2;
{ // glocal
uint8_t *s, *r, *q, *seq = bam_get_seq(b), *bq;
int *state;
bq = calloc(c->l_qseq + 1, 1);
memcpy(bq, qual, c->l_qseq);
s = calloc(c->l_qseq, 1);
for (i = 0; i < c->l_qseq; ++i) s[i] = seq_nt16_int[bam_seqi(seq, i)];
r = calloc(xe - xb, 1);
for (i = xb; i < xe; ++i) {
if (i >= ref_len || ref[i] == '\0') { xe = i; break; }
r[i-xb] = seq_nt16_int[seq_nt16_table[(int)ref[i]]];
}
state = calloc(c->l_qseq, sizeof(int));
q = calloc(c->l_qseq, 1);
probaln_glocal(r, xe-xb, s, c->l_qseq, qual, &conf, state, q);
if (!extend_baq) { // in this block, bq[] is capped by base quality qual[]
for (k = 0, x = c->pos, y = 0; k < c->n_cigar; ++k) {
int op = cigar[k]&0xf, l = cigar[k]>>4;
if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) {
for (i = y; i < y + l; ++i) {
if ((state[i]&3) != 0 || state[i]>>2 != x - xb + (i - y)) bq[i] = 0;
else bq[i] = bq[i] < q[i]? bq[i] : q[i];
}
x += l; y += l;
} else if (op == BAM_CSOFT_CLIP || op == BAM_CINS) y += l;
else if (op == BAM_CDEL) x += l;
}
for (i = 0; i < c->l_qseq; ++i) bq[i] = qual[i] - bq[i] + 64; // finalize BQ
} else { // in this block, bq[] is BAQ that can be larger than qual[] (different from the above!)
uint8_t *left, *rght;
left = calloc(c->l_qseq, 1); rght = calloc(c->l_qseq, 1);
for (k = 0, x = c->pos, y = 0; k < c->n_cigar; ++k) {
int op = cigar[k]&0xf, l = cigar[k]>>4;
if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) {
for (i = y; i < y + l; ++i)
bq[i] = ((state[i]&3) != 0 || state[i]>>2 != x - xb + (i - y))? 0 : q[i];
for (left[y] = bq[y], i = y + 1; i < y + l; ++i)
left[i] = bq[i] > left[i-1]? bq[i] : left[i-1];
for (rght[y+l-1] = bq[y+l-1], i = y + l - 2; i >= y; --i)
rght[i] = bq[i] > rght[i+1]? bq[i] : rght[i+1];
for (i = y; i < y + l; ++i)
bq[i] = left[i] < rght[i]? left[i] : rght[i];
x += l; y += l;
} else if (op == BAM_CSOFT_CLIP || op == BAM_CINS) y += l;
else if (op == BAM_CDEL) x += l;
}
for (i = 0; i < c->l_qseq; ++i) bq[i] = 64 + (qual[i] <= bq[i]? 0 : qual[i] - bq[i]); // finalize BQ
free(left); free(rght);
}
if (apply_baq) {
for (i = 0; i < c->l_qseq; ++i) qual[i] -= bq[i] - 64; // modify qual
bam_aux_append(b, "ZQ", 'Z', c->l_qseq + 1, bq);
} else bam_aux_append(b, "BQ", 'Z', c->l_qseq + 1, bq);
free(bq); free(s); free(r); free(q); free(state);
}
return 0;
}
| 4,805
|
324
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.googlecloudstorage.blobstore;
import static com.google.common.base.Preconditions.checkNotNull;
import java.net.URI;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
import java.util.Map;
import javax.annotation.Resource;
import javax.inject.Provider;
import org.jclouds.Constants;
import org.jclouds.blobstore.BlobRequestSigner;
import org.jclouds.blobstore.domain.Blob;
import org.jclouds.blobstore.functions.BlobToHttpGetOptions;
import org.jclouds.date.TimeStamp;
import org.jclouds.domain.Credentials;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpUtils;
import org.jclouds.http.Uris;
import org.jclouds.http.options.GetOptions;
import org.jclouds.logging.Logger;
import org.jclouds.oauth.v2.config.Authorization;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import com.google.common.io.BaseEncoding;
import com.google.common.net.HttpHeaders;
import com.google.inject.Inject;
import com.google.inject.name.Named;
public final class GoogleCloudStorageBlobRequestSigner implements BlobRequestSigner {
private static final int DEFAULT_EXPIRY_SECONDS = 15 * 60;
private static final URI STORAGE_URL = URI.create("http://storage.googleapis.com/");
private final Supplier<Credentials> creds;
private final Supplier<PrivateKey> privateKey;
private final Provider<Long> timestamp;
private final HttpUtils utils;
private final BlobToHttpGetOptions toGetOptions = new BlobToHttpGetOptions();
@Resource
@Named(Constants.LOGGER_SIGNATURE)
protected Logger signatureLog = Logger.NULL;
@Inject
protected GoogleCloudStorageBlobRequestSigner(@org.jclouds.location.Provider Supplier<Credentials> creds,
@Authorization Supplier<PrivateKey> privateKey, @TimeStamp Provider<Long> timestamp, HttpUtils utils) {
this.creds = creds;
this.privateKey = privateKey;
this.timestamp = timestamp;
this.utils = utils;
}
@Override
public HttpRequest signGetBlob(String container, String name) {
return signGetBlob(container, name, DEFAULT_EXPIRY_SECONDS);
}
@Override
public HttpRequest signGetBlob(String container, String name, long timeInSeconds) {
return sign("GET", container, name, GetOptions.NONE, timestamp.get() + timeInSeconds, null);
}
@Override
public HttpRequest signGetBlob(String container, String name, org.jclouds.blobstore.options.GetOptions options) {
return sign("GET", container, name, toGetOptions.apply(options), timestamp.get() + DEFAULT_EXPIRY_SECONDS, null);
}
@Override
public HttpRequest signPutBlob(String container, Blob blob) {
return signPutBlob(container, blob, DEFAULT_EXPIRY_SECONDS);
}
@Override
public HttpRequest signPutBlob(String container, Blob blob, long timeInSeconds) {
return sign("PUT", container, blob.getMetadata().getName(), GetOptions.NONE, timestamp.get() + timeInSeconds,
blob.getMetadata().getContentMetadata().getContentType());
}
private HttpRequest sign(String method, String container, String name, GetOptions options, long expires, String contentType) {
checkNotNull(container, "container");
checkNotNull(name, "name");
HttpRequest.Builder request = HttpRequest.builder()
.method(method)
.endpoint(Uris.uriBuilder(STORAGE_URL).appendPath(container).appendPath(name).build());
if (contentType != null) {
request.replaceHeader(HttpHeaders.CONTENT_TYPE, contentType);
}
String stringToSign = createStringToSign(request.build(), expires);
byte[] rawSignature;
try {
Signature signer = Signature.getInstance("SHA256withRSA");
signer.initSign(privateKey.get());
signer.update(stringToSign.getBytes(Charsets.UTF_8));
rawSignature = signer.sign();
} catch (InvalidKeyException ike) {
throw new RuntimeException(ike);
} catch (NoSuchAlgorithmException nsae) {
throw new RuntimeException(nsae);
} catch (SignatureException se) {
throw new RuntimeException(se);
}
String signature = BaseEncoding.base64().encode(rawSignature);
for (Map.Entry<String, String> entry : options.buildRequestHeaders().entries()) {
request.addHeader(entry.getKey(), entry.getValue());
}
return (HttpRequest) request
.addQueryParam("Expires", String.valueOf(expires))
.addQueryParam("GoogleAccessId", creds.get().identity)
.addQueryParam("Signature", signature)
.build();
}
private String createStringToSign(HttpRequest request, long expires) {
utils.logRequest(signatureLog, request, ">>");
StringBuilder buffer = new StringBuilder();
buffer.append(request.getMethod()).append("\n");
buffer.append(Strings.nullToEmpty(request.getFirstHeaderOrNull(HttpHeaders.CONTENT_MD5))).append("\n");
buffer.append(Strings.nullToEmpty(request.getFirstHeaderOrNull(HttpHeaders.CONTENT_TYPE))).append("\n");
buffer.append(String.valueOf(expires)).append("\n");
// TODO: extension headers
buffer.append(request.getEndpoint().getPath());
return buffer.toString();
}
}
| 2,118
|
20,995
|
// Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "include/cppgc/source-location.h"
#include "src/base/macros.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace cppgc {
namespace internal {
namespace {
constexpr char kFileName[] = "source-location-unittest.cc";
bool Contains(const std::string& base_string, const std::string& substring) {
return base_string.find(substring) != std::string::npos;
}
} // namespace
TEST(SourceLocationTest, DefaultCtor) {
constexpr SourceLocation loc;
EXPECT_EQ(nullptr, loc.Function());
EXPECT_EQ(nullptr, loc.FileName());
EXPECT_EQ(0u, loc.Line());
}
void TestSourceLocationCurrent() {
static constexpr char kFunctionName[] = "TestSourceLocationCurrent";
static constexpr size_t kNextLine = __LINE__ + 1;
constexpr auto loc = SourceLocation::Current();
#if !CPPGC_SUPPORTS_SOURCE_LOCATION
EXPECT_EQ(nullptr, loc.Function());
EXPECT_EQ(nullptr, loc.FileName());
EXPECT_EQ(0u, loc.Line());
USE(kNextLine);
return;
#endif
EXPECT_EQ(kNextLine, loc.Line());
EXPECT_TRUE(Contains(loc.FileName(), kFileName));
EXPECT_TRUE(Contains(loc.Function(), kFunctionName));
}
TEST(SourceLocationTest, Current) { TestSourceLocationCurrent(); }
void TestToString() {
static const std::string kDescriptor = std::string(__func__) + "@" +
__FILE__ + ":" +
std::to_string(__LINE__ + 1);
constexpr auto loc = SourceLocation::Current();
const auto string = loc.ToString();
EXPECT_EQ(kDescriptor, string);
}
#if CPPGC_SUPPORTS_SOURCE_LOCATION
TEST(SourceLocationTest, ToString) { TestToString(); }
#endif
} // namespace internal
} // namespace cppgc
| 682
|
1,178
|
# Copyright 2020 Makani Technologies LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
"""Contains the formulation of the SSAM model.
Summary:
This code calculates the local angle of attack and sideslip on the kite
aerodynamic surfaces assuming rigid body mechanics about the c.g. of the
kite.
"""
from makani.analysis.aero.hover_model import hover_model
import numpy as np
class SSAMModel(object):
"""Class used to determine local angles of attack on kite sections."""
def __init__(self, wing_model, wing_serial):
"""Initializes the SSAM model.
Args:
wing_model: Wing model (e.g. 'm600').
wing_serial: String giving the desired wing serial number (e.g. '01').
"""
# Use the hover model to obtain the kite main wing panels.
self._kite_params = hover_model.GetParams(wing_model, wing_serial,
use_wake_model=False)
# Rigid body mechanics require understanding of the c.g. location as the
# wing is defined to rotate about the body c.g. and the freestream velocity
# is assumed uniform everywhere.
self._cg_loc_b = self._kite_params['center_of_mass_pos']
def GetMainWingAlphas(self, angular_rate_b, apparent_wind_b):
"""Computes the local alpha values on the main wing.
Args:
angular_rate_b: Array of shape (n,3) containing kite body rates.
apparent_wind_b: Array of shape (n,3) containing apparent wind velocity
components.
Returns:
main_wing_alphas_deg: Array of shape (n, x) containing the kite main wing
local alpha values, where x is the number of kite
main wing panels.
"""
assert len(np.shape(angular_rate_b)) == 2
assert np.shape(angular_rate_b)[1]
assert np.shape(angular_rate_b) == np.shape(apparent_wind_b)
# Pitch rate is ignored as it does not participate in the heaving motion of
# any of the wing airfoils.
angular_rate_b[:, 1] = 0.0
# Compute alpha values for each plane contained in the hover model where the
# panel is located on the main wing.
main_wing_alphas_deg = np.array([])
for panel in self._kite_params['panels']:
if panel['name'].startswith('Wing'):
panel_ac_pos_b = panel['pos_b']
panel_relative_incidence_deg = np.rad2deg(panel['relative_incidence'])
# It is assumed that the kite rotates about its c.g.
r_panel = panel_ac_pos_b - self._cg_loc_b
# Expand the stationary r-position and reorient to match the omega
# array size to enable the cross product.
r_panel = np.repeat(np.expand_dims(r_panel, axis=1).transpose(),
np.shape(angular_rate_b)[0], axis=0)
panel_alpha_deg, _ = _ComputeRelativeAlphaBeta(angular_rate_b, r_panel,
apparent_wind_b)
# Account for washout if necessary.
panel_alpha_deg += panel_relative_incidence_deg
panel_alpha_deg = np.expand_dims(panel_alpha_deg, axis=1)
if np.shape(main_wing_alphas_deg)[0] != np.shape(panel_alpha_deg)[0]:
main_wing_alphas_deg = panel_alpha_deg
else:
main_wing_alphas_deg = np.concatenate((main_wing_alphas_deg,
panel_alpha_deg), axis=1)
return main_wing_alphas_deg
def _ComputeRelativeAlphaBeta(omega_b, position_b, apparent_wind_b):
"""Computes the relative alpha and beta values, in degrees, from kinematics.
Args:
omega_b: Array of size (n, 3). Body rates of the kite [rad/s].
position_b: Array of size (1, 3). Position of the surface to compute local
alpha/beta [m].
apparent_wind_b: Array of size (n,3). Apparent wind vector from the state
estimator [m/s].
Returns:
local_alpha_deg, local_beta_deg: The values of local alpha and beta.
The math for a relative angle of attack at a given section is as follows:
(1) Kinematically:
v_section_b = apparent_wind_b - omega_b X position_b
(2) By definition:
alpha_rad = atan2(-v_section_b_z, -v_section_b_x)
beta_rad = asin(-v_section_b_y, mag(v_section_b))
where _x, _y, _z denote the unit basis vectors in the body coordinates.
"""
assert np.shape(omega_b) == np.shape(apparent_wind_b)
# The subtraction is because the cross product is the rigid body motion
# but the reference frame for the aero has the opposite effect of the
# motion of the rigid body motion frame.
local_vel = apparent_wind_b - np.cross(omega_b, position_b, axisa=1,
axisb=1)
local_vel_mag = np.linalg.norm(local_vel, axis=1)
local_alpha_deg = np.rad2deg(np.arctan2(-1.0 * local_vel[:, 2],
-1.0 * local_vel[:, 0]))
local_beta_deg = np.rad2deg(np.arcsin(-1.0 * local_vel[:, 1]
/ local_vel_mag))
return local_alpha_deg, local_beta_deg
| 2,224
|
348
|
{"nom":"Ecutigny","circ":"5ème circonscription","dpt":"Côte-d'Or","inscrits":88,"abs":47,"votants":41,"blancs":3,"nuls":0,"exp":38,"res":[{"nuance":"REM","nom":"<NAME>","voix":23},{"nuance":"LR","nom":"<NAME>","voix":15}]}
| 94
|
700
|
from skidl import SKIDL, TEMPLATE, Part, Pin, SchLib
SKIDL_lib_version = '0.0.1'
digital_audio = SchLib(tool=SKIDL).add_parts(*[
Part(name='AK5392VS',dest=TEMPLATE,tool=SKIDL,keywords='24bit Sigma Delta Audio ADC 2ch',description='AK5392-VS, Enhanced Audio ADC, 2 channels Sigma Delta, 24bit, SO28',ref_prefix='U',num_units=1,fplist=['SO*'],do_erc=True,pins=[
Pin(num='1',name='VREFL',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='GNDL',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='VCOML',func=Pin.OUTPUT,do_erc=True),
Pin(num='4',name='AINL+',do_erc=True),
Pin(num='5',name='AINL-',do_erc=True),
Pin(num='6',name='ZCAL',do_erc=True),
Pin(num='7',name='VD',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='DGND',func=Pin.PWRIN,do_erc=True),
Pin(num='9',name='CAL',func=Pin.OUTPUT,do_erc=True),
Pin(num='10',name='~RST~',do_erc=True),
Pin(num='20',name='TEST',do_erc=True),
Pin(num='11',name='SMODE2',do_erc=True),
Pin(num='21',name='BGND',func=Pin.PWRIN,do_erc=True),
Pin(num='12',name='SMODE1',do_erc=True),
Pin(num='22',name='AGND',func=Pin.PWRIN,do_erc=True),
Pin(num='13',name='LRCK',func=Pin.BIDIR,do_erc=True),
Pin(num='23',name='VA',func=Pin.PWRIN,do_erc=True),
Pin(num='14',name='SCLK',func=Pin.BIDIR,do_erc=True),
Pin(num='24',name='AINR-',do_erc=True),
Pin(num='15',name='SDATA',func=Pin.OUTPUT,do_erc=True),
Pin(num='25',name='AINR+',do_erc=True),
Pin(num='16',name='FSYNC',func=Pin.BIDIR,do_erc=True),
Pin(num='26',name='VCOMR',func=Pin.OUTPUT,do_erc=True),
Pin(num='17',name='CLK',do_erc=True),
Pin(num='27',name='GNDR',func=Pin.OUTPUT,do_erc=True),
Pin(num='18',name='CMODE',do_erc=True),
Pin(num='28',name='VREFR',func=Pin.OUTPUT,do_erc=True),
Pin(num='19',name='HPFE',do_erc=True)]),
Part(name='AK5393VS',dest=TEMPLATE,tool=SKIDL,keywords='96kHz 24bit Sigma Delta Audio ADC 2ch',description='Enhanced Audio ADC, 2 channels Sigma Delta, 24bit 96kHz, SO28',ref_prefix='U',num_units=1,fplist=['SO*'],do_erc=True,pins=[
Pin(num='1',name='VREFL',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='GNDL',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='VCOML',func=Pin.OUTPUT,do_erc=True),
Pin(num='4',name='AINL+',do_erc=True),
Pin(num='5',name='AINL-',do_erc=True),
Pin(num='6',name='ZCAL',do_erc=True),
Pin(num='7',name='VD',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='DGND',func=Pin.PWRIN,do_erc=True),
Pin(num='9',name='CAL',func=Pin.OUTPUT,do_erc=True),
Pin(num='10',name='~RST~',do_erc=True),
Pin(num='20',name='TEST',do_erc=True),
Pin(num='11',name='SMODE2',do_erc=True),
Pin(num='21',name='BGND',func=Pin.PWRIN,do_erc=True),
Pin(num='12',name='SMODE1',do_erc=True),
Pin(num='22',name='AGND',func=Pin.PWRIN,do_erc=True),
Pin(num='13',name='LRCK',func=Pin.BIDIR,do_erc=True),
Pin(num='23',name='VA',func=Pin.PWRIN,do_erc=True),
Pin(num='14',name='SCLK',func=Pin.BIDIR,do_erc=True),
Pin(num='24',name='AINR-',do_erc=True),
Pin(num='15',name='SDATA',func=Pin.OUTPUT,do_erc=True),
Pin(num='25',name='AINR+',do_erc=True),
Pin(num='16',name='FSYNC',func=Pin.BIDIR,do_erc=True),
Pin(num='26',name='VCOMR',func=Pin.OUTPUT,do_erc=True),
Pin(num='17',name='MCLK',do_erc=True),
Pin(num='27',name='GNDR',func=Pin.OUTPUT,do_erc=True),
Pin(num='18',name='DFS',do_erc=True),
Pin(num='28',name='VREFR',func=Pin.OUTPUT,do_erc=True),
Pin(num='19',name='HPFE',do_erc=True)]),
Part(name='AK5394AVS',dest=TEMPLATE,tool=SKIDL,keywords='192kHz 24bit Sigma Delta Audio ADC 2ch',description='Super High Performance Audio ADC, 2 channels Sigma Delta, 24bit 192kHz, SO28',ref_prefix='U',num_units=1,fplist=['SO*'],do_erc=True,pins=[
Pin(num='1',name='VREFL+',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='VREFL-',func=Pin.OUTPUT,do_erc=True),
Pin(num='3',name='VCOML',func=Pin.OUTPUT,do_erc=True),
Pin(num='4',name='AINL+',do_erc=True),
Pin(num='5',name='AINL-',do_erc=True),
Pin(num='6',name='ZCAL',do_erc=True),
Pin(num='7',name='VD',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='DGND',func=Pin.PWRIN,do_erc=True),
Pin(num='9',name='CAL',func=Pin.OUTPUT,do_erc=True),
Pin(num='10',name='~RST~',do_erc=True),
Pin(num='20',name='DFS1',do_erc=True),
Pin(num='11',name='SMODE2',do_erc=True),
Pin(num='21',name='BGND',func=Pin.PWRIN,do_erc=True),
Pin(num='12',name='SMODE1',do_erc=True),
Pin(num='22',name='AGND',func=Pin.PWRIN,do_erc=True),
Pin(num='13',name='LRCK',func=Pin.BIDIR,do_erc=True),
Pin(num='23',name='VA',func=Pin.PWRIN,do_erc=True),
Pin(num='14',name='SCLK',func=Pin.BIDIR,do_erc=True),
Pin(num='24',name='AINR-',do_erc=True),
Pin(num='15',name='SDATA',func=Pin.OUTPUT,do_erc=True),
Pin(num='25',name='AINR+',do_erc=True),
Pin(num='16',name='FSYNC',func=Pin.BIDIR,do_erc=True),
Pin(num='26',name='VCOMR',func=Pin.OUTPUT,do_erc=True),
Pin(num='17',name='MCLK',do_erc=True),
Pin(num='27',name='VREFR-',func=Pin.OUTPUT,do_erc=True),
Pin(num='18',name='DFS0',do_erc=True),
Pin(num='28',name='VREFR+',func=Pin.OUTPUT,do_erc=True),
Pin(num='19',name='HPFE',do_erc=True)]),
Part(name='CS4245',dest=TEMPLATE,tool=SKIDL,keywords='CS4245 stereo audio codec',description='Stereo Audio CODEC, 104 dB, 24-Bit, 192 kHz',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='SDA/CDOUT',func=Pin.BIDIR,do_erc=True),
Pin(num='2',name='SCL/CCLK',do_erc=True),
Pin(num='3',name='AD0/~CS',do_erc=True),
Pin(num='4',name='AD1/CDIN',do_erc=True),
Pin(num='5',name='VLC',do_erc=True),
Pin(num='6',name='~RESET',do_erc=True),
Pin(num='7',name='AIN3A',do_erc=True),
Pin(num='8',name='AIN3B',do_erc=True),
Pin(num='9',name='AIN2A',do_erc=True),
Pin(num='10',name='AIN2B',do_erc=True),
Pin(num='20',name='FILT2+',func=Pin.OUTPUT,do_erc=True),
Pin(num='30',name='VA',func=Pin.PWRIN,do_erc=True),
Pin(num='40',name='MCLK2',do_erc=True),
Pin(num='11',name='AIN1A',do_erc=True),
Pin(num='21',name='AIN4A/MICIN1',do_erc=True),
Pin(num='31',name='AGND',func=Pin.PWRIN,do_erc=True),
Pin(num='41',name='SDOUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='12',name='AIN1B',do_erc=True),
Pin(num='22',name='AIN4B/MICIN2',do_erc=True),
Pin(num='32',name='AGND',func=Pin.PWRIN,do_erc=True),
Pin(num='42',name='SCLK1',func=Pin.BIDIR,do_erc=True),
Pin(num='13',name='AGND',func=Pin.PWRIN,do_erc=True),
Pin(num='23',name='AIN5A',do_erc=True),
Pin(num='33',name='AOUTA',func=Pin.OUTPUT,do_erc=True),
Pin(num='43',name='LRCK1',func=Pin.BIDIR,do_erc=True),
Pin(num='14',name='VA',func=Pin.PWRIN,do_erc=True),
Pin(num='24',name='AIN5B',do_erc=True),
Pin(num='34',name='AOUTB',func=Pin.OUTPUT,do_erc=True),
Pin(num='44',name='MCLK1',do_erc=True),
Pin(num='15',name='AFILTA',func=Pin.OUTPUT,do_erc=True),
Pin(num='25',name='MICBIAS',func=Pin.OUTPUT,do_erc=True),
Pin(num='35',name='~MUTEC',func=Pin.OUTPUT,do_erc=True),
Pin(num='45',name='DGND',func=Pin.PWRIN,do_erc=True),
Pin(num='16',name='AFILTB',func=Pin.OUTPUT,do_erc=True),
Pin(num='26',name='AIN6A',do_erc=True),
Pin(num='36',name='VLS',func=Pin.PWRIN,do_erc=True),
Pin(num='46',name='VD',func=Pin.PWRIN,do_erc=True),
Pin(num='17',name='VQ1',func=Pin.OUTPUT,do_erc=True),
Pin(num='27',name='AIN6B',do_erc=True),
Pin(num='37',name='SDIN',do_erc=True),
Pin(num='47',name='INT',func=Pin.OUTPUT,do_erc=True),
Pin(num='18',name='VQ2',func=Pin.OUTPUT,do_erc=True),
Pin(num='28',name='AUXOUTA',func=Pin.OUTPUT,do_erc=True),
Pin(num='38',name='SCLK2',func=Pin.BIDIR,do_erc=True),
Pin(num='48',name='OVFL',func=Pin.OUTPUT,do_erc=True),
Pin(num='19',name='FILT1+',func=Pin.OUTPUT,do_erc=True),
Pin(num='29',name='AUXOUTB',func=Pin.OUTPUT,do_erc=True),
Pin(num='39',name='LRCK2',func=Pin.BIDIR,do_erc=True)]),
Part(name='CS43L21',dest=TEMPLATE,tool=SKIDL,keywords='stereo audio dac',description='Stereo Audio DAC, 24-bit, 96 kHz, 98 dB',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='LRCK',func=Pin.BIDIR,do_erc=True),
Pin(num='2',name='SDA/MCLKDIV2',func=Pin.BIDIR,do_erc=True),
Pin(num='3',name='SCL/CCLK/I2S/~LJ',do_erc=True),
Pin(num='4',name='AD0/~CS~/DEM',do_erc=True),
Pin(num='5',name='VA_HP',do_erc=True),
Pin(num='6',name='FLYP',do_erc=True),
Pin(num='7',name='GND_HP',do_erc=True),
Pin(num='8',name='FLYN',do_erc=True),
Pin(num='9',name='VSS_HP',func=Pin.OUTPUT,do_erc=True),
Pin(num='10',name='AOUTB',func=Pin.OUTPUT,do_erc=True),
Pin(num='30',name='MCLK',do_erc=True),
Pin(num='11',name='AOUTA',func=Pin.OUTPUT,do_erc=True),
Pin(num='31',name='SCLK',do_erc=True),
Pin(num='12',name='VA',do_erc=True),
Pin(num='32',name='SDIN',do_erc=True),
Pin(num='13',name='AGND',do_erc=True),
Pin(num='14',name='FILT+',func=Pin.OUTPUT,do_erc=True),
Pin(num='15',name='VQ',func=Pin.OUTPUT,do_erc=True),
Pin(num='25',name='~RESET',do_erc=True),
Pin(num='26',name='VL',do_erc=True),
Pin(num='27',name='VD',func=Pin.PWRIN,do_erc=True),
Pin(num='28',name='DGND',func=Pin.PWRIN,do_erc=True),
Pin(num='29',name='TESTO/M/~S',do_erc=True)]),
Part(name='CS5361',dest=TEMPLATE,tool=SKIDL,keywords='stereo audio adc',description='Stereo Audio ADC, 24 bits, 192 kHz, 114 dB',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='RST',do_erc=True),
Pin(num='2',name='M/~S',do_erc=True),
Pin(num='3',name='LRCK',func=Pin.BIDIR,do_erc=True),
Pin(num='4',name='SCLK',func=Pin.BIDIR,do_erc=True),
Pin(num='5',name='MCLK',do_erc=True),
Pin(num='6',name='VD',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='VL',func=Pin.PWRIN,do_erc=True),
Pin(num='9',name='SDOUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='10',name='MDIV',do_erc=True),
Pin(num='20',name='AINR-',do_erc=True),
Pin(num='11',name='~HPF',do_erc=True),
Pin(num='21',name='AINR+',do_erc=True),
Pin(num='12',name='I2S/~LJ',do_erc=True),
Pin(num='22',name='VQ',func=Pin.PWROUT,do_erc=True),
Pin(num='13',name='M0',do_erc=True),
Pin(num='23',name='REFGND',func=Pin.PWRIN,do_erc=True),
Pin(num='14',name='M1',do_erc=True),
Pin(num='24',name='FILT+',func=Pin.PWROUT,do_erc=True),
Pin(num='15',name='~OVFL',do_erc=True),
Pin(num='16',name='AINL+',do_erc=True),
Pin(num='17',name='AINL-',do_erc=True),
Pin(num='18',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='19',name='VA',func=Pin.PWRIN,do_erc=True)]),
Part(name='CS8406',dest=TEMPLATE,tool=SKIDL,keywords='digital audio interface transmitter spdif',description='192 kHz Digital Audio Interface Transmitter (SOIC-28)',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='6',name='VD',func=Pin.PWRIN,do_erc=True),
Pin(num='9',name='~RST',do_erc=True),
Pin(num='21',name='OMCK',do_erc=True),
Pin(num='12',name='ILRCK',func=Pin.BIDIR,do_erc=True),
Pin(num='22',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='13',name='ISCLK',func=Pin.BIDIR,do_erc=True),
Pin(num='23',name='VL',func=Pin.PWRIN,do_erc=True),
Pin(num='14',name='SDIN',do_erc=True),
Pin(num='24',name='H/~S',do_erc=True),
Pin(num='25',name='TXN',func=Pin.OUTPUT,do_erc=True),
Pin(num='26',name='TXP',func=Pin.OUTPUT,do_erc=True),
Pin(num='1',name='COPY/C',do_erc=True),
Pin(num='3',name='~EMPH',do_erc=True),
Pin(num='4',name='SFMT0',do_erc=True),
Pin(num='5',name='SFMT1',do_erc=True),
Pin(num='10',name='APMS',do_erc=True),
Pin(num='20',name='HWCK0',do_erc=True),
Pin(num='11',name='TCBLD',do_erc=True),
Pin(num='15',name='TCBL',func=Pin.BIDIR,do_erc=True),
Pin(num='16',name='CEN',do_erc=True),
Pin(num='17',name='U',do_erc=True),
Pin(num='27',name='HWCK1',do_erc=True),
Pin(num='18',name='V',do_erc=True),
Pin(num='28',name='ORIG',do_erc=True),
Pin(num='19',name='~AUDIO',func=Pin.OUTPUT,do_erc=True),
Pin(num='1',name='SDA/CDOUT',do_erc=True),
Pin(num='2',name='AD0/CS',do_erc=True),
Pin(num='3',name='AD2',do_erc=True),
Pin(num='4',name='RXP',do_erc=True),
Pin(num='5',name='TEST',do_erc=True),
Pin(num='10',name='TEST',do_erc=True),
Pin(num='20',name='Bit_User',do_erc=True),
Pin(num='11',name='TEST',do_erc=True),
Pin(num='15',name='TCBL',func=Pin.BIDIR,do_erc=True),
Pin(num='16',name='TEST',do_erc=True),
Pin(num='17',name='TEST',do_erc=True),
Pin(num='27',name='AD1/CDIN',do_erc=True),
Pin(num='18',name='TEST',do_erc=True),
Pin(num='28',name='SCL/CCLK',do_erc=True),
Pin(num='19',name='INT',func=Pin.OUTPUT,do_erc=True)]),
Part(name='CS8414',dest=TEMPLATE,tool=SKIDL,keywords='digital audio interface receiver spdif',description='96KHz Digital Audio Receiver',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='C',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='CD/F1',func=Pin.OUTPUT,do_erc=True),
Pin(num='3',name='CC/F0',func=Pin.OUTPUT,do_erc=True),
Pin(num='4',name='CB/E2',func=Pin.OUTPUT,do_erc=True),
Pin(num='5',name='CA/E1',func=Pin.OUTPUT,do_erc=True),
Pin(num='6',name='C0/E0',func=Pin.OUTPUT,do_erc=True),
Pin(num='7',name='VD',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='DGND',func=Pin.PWRIN,do_erc=True),
Pin(num='9',name='RXP',do_erc=True),
Pin(num='10',name='RXN',do_erc=True),
Pin(num='20',name='FILT',do_erc=True),
Pin(num='11',name='FSYNC',func=Pin.BIDIR,do_erc=True),
Pin(num='21',name='AGND',func=Pin.PWRIN,do_erc=True),
Pin(num='12',name='SCK',func=Pin.BIDIR,do_erc=True),
Pin(num='22',name='VA',func=Pin.PWRIN,do_erc=True),
Pin(num='13',name='CS12/FCK',do_erc=True),
Pin(num='23',name='M0',do_erc=True),
Pin(num='14',name='U',func=Pin.OUTPUT,do_erc=True),
Pin(num='24',name='M1',do_erc=True),
Pin(num='15',name='CBL',func=Pin.OUTPUT,do_erc=True),
Pin(num='25',name='ERF',func=Pin.OUTPUT,do_erc=True),
Pin(num='16',name='SEL',do_erc=True),
Pin(num='26',name='SDATA',func=Pin.OUTPUT,do_erc=True),
Pin(num='17',name='M3',do_erc=True),
Pin(num='27',name='CE/F2',func=Pin.OUTPUT,do_erc=True),
Pin(num='18',name='M2',do_erc=True),
Pin(num='28',name='VERF',func=Pin.OUTPUT,do_erc=True),
Pin(num='19',name='MCK',func=Pin.OUTPUT,do_erc=True)]),
Part(name='CS8416-N',dest=TEMPLATE,tool=SKIDL,keywords='digital audio interface receiver spdif',description='192 kHz Digital Audio Interface Receiver (QFN-28)',ref_prefix='U',num_units=1,fplist=['QFN*28*'],do_erc=True,pins=[
Pin(num='1',name='RXP0',do_erc=True),
Pin(num='2',name='RXN',do_erc=True),
Pin(num='3',name='VA',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='AGND',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='FILT',func=Pin.PASSIVE,do_erc=True),
Pin(num='6',name='~RESET',do_erc=True),
Pin(num='7',name='RXP4/RXSEL1',do_erc=True),
Pin(num='8',name='RXP5/RXSEL0',do_erc=True),
Pin(num='9',name='RXP6/TXSEL1',do_erc=True),
Pin(num='10',name='RXP7/TXSEL0',do_erc=True),
Pin(num='20',name='VD',func=Pin.PWRIN,do_erc=True),
Pin(num='11',name='AD0/~CS~/NV/RERR',do_erc=True),
Pin(num='21',name='RMCK',func=Pin.OUTPUT,do_erc=True),
Pin(num='12',name='AD1/CDIN/~AUDIO',do_erc=True),
Pin(num='22',name='OMCK',do_erc=True),
Pin(num='13',name='SCL/CCLK/96KHZ',do_erc=True),
Pin(num='23',name='SDOUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='14',name='SDA/CDOUT/RCBL',func=Pin.BIDIR,do_erc=True),
Pin(num='24',name='OSCLK',func=Pin.BIDIR,do_erc=True),
Pin(num='15',name='U/AD2/GPO2',func=Pin.OUTPUT,do_erc=True),
Pin(num='25',name='OLRCK',func=Pin.BIDIR,do_erc=True),
Pin(num='16',name='C/GPO1',func=Pin.OUTPUT,do_erc=True),
Pin(num='26',name='RXP3',do_erc=True),
Pin(num='17',name='TX/GPO0',func=Pin.OUTPUT,do_erc=True),
Pin(num='27',name='RXP2',do_erc=True),
Pin(num='18',name='VL',func=Pin.PWRIN,do_erc=True),
Pin(num='28',name='RXP1',do_erc=True),
Pin(num='19',name='DGND',func=Pin.PWRIN,do_erc=True)]),
Part(name='CS8416-Z',dest=TEMPLATE,tool=SKIDL,keywords='digital audio interface receiver spdif',description='192 kHz Digital Audio Interface Receiver (TSSOP-28)',ref_prefix='U',num_units=1,fplist=['SOIC*28*', '*SSOP*28*'],do_erc=True,aliases=['CS8416-S', 'CS8416'],pins=[
Pin(num='1',name='RXP3',do_erc=True),
Pin(num='2',name='RXP2',do_erc=True),
Pin(num='3',name='RXP1',do_erc=True),
Pin(num='4',name='RXP0',do_erc=True),
Pin(num='5',name='RXN',do_erc=True),
Pin(num='6',name='VA',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='AGND',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='FILT',func=Pin.PASSIVE,do_erc=True),
Pin(num='9',name='~RESET',do_erc=True),
Pin(num='10',name='RXP4/RXSEL1',do_erc=True),
Pin(num='20',name='TX/GPO0',func=Pin.OUTPUT,do_erc=True),
Pin(num='11',name='RXP5/RXSEL0',do_erc=True),
Pin(num='21',name='VL',func=Pin.PWRIN,do_erc=True),
Pin(num='12',name='RXP6/TXSEL1',do_erc=True),
Pin(num='22',name='DGND',func=Pin.PWRIN,do_erc=True),
Pin(num='13',name='RXP7/TXSEL0',do_erc=True),
Pin(num='23',name='VD',func=Pin.PWRIN,do_erc=True),
Pin(num='14',name='AD0/~CS~/NV/RERR',do_erc=True),
Pin(num='24',name='RMCK',func=Pin.OUTPUT,do_erc=True),
Pin(num='15',name='AD1/CDIN/~AUDIO',do_erc=True),
Pin(num='25',name='OMCK',do_erc=True),
Pin(num='16',name='SCL/CCLK/96KHZ',do_erc=True),
Pin(num='26',name='SDOUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='17',name='SDA/CDOUT/RCBL',func=Pin.BIDIR,do_erc=True),
Pin(num='27',name='OSCLK',func=Pin.BIDIR,do_erc=True),
Pin(num='18',name='U/AD2/GPO2',func=Pin.OUTPUT,do_erc=True),
Pin(num='28',name='OLRCK',func=Pin.BIDIR,do_erc=True),
Pin(num='19',name='C/GPO1',func=Pin.OUTPUT,do_erc=True)]),
Part(name='CS8420_SOFT',dest=TEMPLATE,tool=SKIDL,keywords='digital audio sample rate converter transceiver',description='Digital Audio Sample Rate Converter and Transceiver',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='SDA/CDOUT',func=Pin.BIDIR,do_erc=True),
Pin(num='2',name='AD0/CS-',do_erc=True),
Pin(num='3',name='EMPH-/AD2',func=Pin.OUTPUT,do_erc=True),
Pin(num='4',name='RXP',do_erc=True),
Pin(num='5',name='RXN',do_erc=True),
Pin(num='6',name='VA',do_erc=True),
Pin(num='7',name='AGND',do_erc=True),
Pin(num='8',name='FILT',do_erc=True),
Pin(num='9',name='RST',do_erc=True),
Pin(num='10',name='RMCK',func=Pin.BIDIR,do_erc=True),
Pin(num='20',name='U',func=Pin.BIDIR,do_erc=True),
Pin(num='11',name='RERR',func=Pin.OUTPUT,do_erc=True),
Pin(num='21',name='OMCK',do_erc=True),
Pin(num='12',name='ILRCK',func=Pin.BIDIR,do_erc=True),
Pin(num='22',name='DGND',do_erc=True),
Pin(num='13',name='ISCLK',func=Pin.BIDIR,do_erc=True),
Pin(num='23',name='VD',do_erc=True),
Pin(num='14',name='SDIN',do_erc=True),
Pin(num='24',name='H/S-',do_erc=True),
Pin(num='15',name='TCBL',func=Pin.BIDIR,do_erc=True),
Pin(num='25',name='TXN',func=Pin.OUTPUT,do_erc=True),
Pin(num='16',name='OSCLK',func=Pin.BIDIR,do_erc=True),
Pin(num='26',name='TXP',func=Pin.OUTPUT,do_erc=True),
Pin(num='17',name='OLRCK',func=Pin.BIDIR,do_erc=True),
Pin(num='27',name='AD1/CDIN',do_erc=True),
Pin(num='18',name='SDOUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='28',name='SCL/CCLK',func=Pin.BIDIR,do_erc=True),
Pin(num='19',name='INT',func=Pin.OPENCOLL,do_erc=True)]),
Part(name='LM4811',dest=TEMPLATE,tool=SKIDL,keywords='headphone amplifier digital volume',description='Dual105mW Headphone Amplifier, Digital Volume Control, Shutdown Mode',ref_prefix='U',num_units=1,fplist=['VSSOP*', 'WSON*', 'SON*'],do_erc=True,pins=[
Pin(num='1',name='VOUT1',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='VIN1',do_erc=True),
Pin(num='3',name='BYPASS',func=Pin.PASSIVE,do_erc=True),
Pin(num='4',name='CLOCK',do_erc=True),
Pin(num='5',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='UP/DN',do_erc=True),
Pin(num='7',name='SHDN',do_erc=True),
Pin(num='8',name='VIN2',do_erc=True),
Pin(num='9',name='VOUT2',func=Pin.OUTPUT,do_erc=True),
Pin(num='10',name='VDD',func=Pin.PWRIN,do_erc=True)]),
Part(name='TLV320AIC23BPW',dest=TEMPLATE,tool=SKIDL,keywords='Stero Audio CODEC 96kHz Headphone',description='8-96kHz Stero Audio CODEC w/ Headphone Amp, TSSOP28',ref_prefix='U',num_units=1,fplist=['TSSOP*'],do_erc=True,pins=[
Pin(num='1',name='BVDD',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='CLKOUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='3',name='BCLK',func=Pin.BIDIR,do_erc=True),
Pin(num='4',name='DIN',do_erc=True),
Pin(num='5',name='LRCIN',do_erc=True),
Pin(num='6',name='DOUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='7',name='LRCOUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='HPVDD',func=Pin.PWRIN,do_erc=True),
Pin(num='9',name='LHPOUT',func=Pin.PASSIVE,do_erc=True),
Pin(num='10',name='RHPOUT',func=Pin.PASSIVE,do_erc=True),
Pin(num='20',name='LLINEIN',func=Pin.PASSIVE,do_erc=True),
Pin(num='11',name='HPGND',func=Pin.PWRIN,do_erc=True),
Pin(num='21',name='~CS~',do_erc=True),
Pin(num='12',name='LOUT',func=Pin.PASSIVE,do_erc=True),
Pin(num='22',name='MODE',do_erc=True),
Pin(num='13',name='ROUT',func=Pin.PASSIVE,do_erc=True),
Pin(num='23',name='SDIN',do_erc=True),
Pin(num='14',name='AVDD',func=Pin.PWRIN,do_erc=True),
Pin(num='24',name='SCLK',do_erc=True),
Pin(num='15',name='AGND',func=Pin.PWRIN,do_erc=True),
Pin(num='25',name='XTI/MCK',func=Pin.PASSIVE,do_erc=True),
Pin(num='16',name='VMID',func=Pin.PASSIVE,do_erc=True),
Pin(num='26',name='XTO',func=Pin.PASSIVE,do_erc=True),
Pin(num='17',name='MICBIAS',func=Pin.PASSIVE,do_erc=True),
Pin(num='27',name='DVDD',func=Pin.PWRIN,do_erc=True),
Pin(num='18',name='MICIN',func=Pin.PASSIVE,do_erc=True),
Pin(num='28',name='DGND',func=Pin.PWRIN,do_erc=True),
Pin(num='19',name='RLINEIN',func=Pin.PASSIVE,do_erc=True)]),
Part(name='TLV320AIC23BRHD',dest=TEMPLATE,tool=SKIDL,keywords='Stero Audio CODEC 96kHz Headphone',description='8-96kHz Stero Audio CODEC w/ Headphone Amp, QFN28',ref_prefix='U',num_units=1,fplist=['QFN*'],do_erc=True,pins=[
Pin(num='1',name='DIN',do_erc=True),
Pin(num='2',name='LRCIN',do_erc=True),
Pin(num='3',name='DOUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='4',name='LRCOUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='5',name='HPVDD',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='LHPOUT',func=Pin.PASSIVE,do_erc=True),
Pin(num='7',name='RHPOUT',func=Pin.PASSIVE,do_erc=True),
Pin(num='8',name='HPGND',func=Pin.PWRIN,do_erc=True),
Pin(num='9',name='LOUT',func=Pin.PASSIVE,do_erc=True),
Pin(num='10',name='ROUT',func=Pin.PASSIVE,do_erc=True),
Pin(num='20',name='SDIN',do_erc=True),
Pin(num='11',name='AVDD',func=Pin.PWRIN,do_erc=True),
Pin(num='21',name='SCLK',do_erc=True),
Pin(num='12',name='AGND',func=Pin.PWRIN,do_erc=True),
Pin(num='22',name='XTI/MCK',func=Pin.PASSIVE,do_erc=True),
Pin(num='13',name='VMID',func=Pin.PASSIVE,do_erc=True),
Pin(num='23',name='XTO',func=Pin.PASSIVE,do_erc=True),
Pin(num='14',name='MICBIAS',func=Pin.PASSIVE,do_erc=True),
Pin(num='24',name='DVDD',func=Pin.PWRIN,do_erc=True),
Pin(num='15',name='MICIN',func=Pin.PASSIVE,do_erc=True),
Pin(num='25',name='DGND',func=Pin.PWRIN,do_erc=True),
Pin(num='16',name='RLINEIN',func=Pin.PASSIVE,do_erc=True),
Pin(num='26',name='BVDD',func=Pin.PWRIN,do_erc=True),
Pin(num='17',name='LLINEIN',func=Pin.PASSIVE,do_erc=True),
Pin(num='27',name='CLKOUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='18',name='~CS~',do_erc=True),
Pin(num='28',name='BCLK',func=Pin.BIDIR,do_erc=True),
Pin(num='19',name='MODE',do_erc=True)]),
Part(name='TPA5050',dest=TEMPLATE,tool=SKIDL,keywords='AUDIO',description='Stereo Digital Audio Delay Processor With I2C Control',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='LRCLK',do_erc=True),
Pin(num='2',name='DATA',do_erc=True),
Pin(num='3',name='SCL',do_erc=True),
Pin(num='4',name='SDA',func=Pin.BIDIR,do_erc=True),
Pin(num='5',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='9',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='10',name='ADD0',do_erc=True),
Pin(num='11',name='ADD1',do_erc=True),
Pin(num='12',name='ADD2',do_erc=True),
Pin(num='13',name='VDD',func=Pin.PWRIN,do_erc=True),
Pin(num='14',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='15',name='DATA_OUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='16',name='BCLK',do_erc=True)])])
| 15,581
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.