repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
interserver/mailbaby-api-samples | swagger-client/jaxrs-resteasy/src/gen/java/io/swagger/api/MailApiService.java | package io.swagger.api;
import io.swagger.api.*;
import io.swagger.model.*;
import io.swagger.model.GenericResponse;
import io.swagger.model.InlineResponse401;
import io.swagger.model.MailAttachment;
import io.swagger.model.MailContact;
import io.swagger.model.MailLog;
import io.swagger.model.MailOrder;
import io.swagger.model.MailOrders;
import io.swagger.model.SendMail;
import io.swagger.model.SendMailAdv;
import io.swagger.model.SendMailAdvFrom;
import java.util.List;
import io.swagger.api.NotFoundException;
import java.io.InputStream;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.JavaResteasyServerCodegen", date = "2021-05-10T11:17:20.680905-04:00[America/New_York]")public interface MailApiService {
Response getMailOrders(SecurityContext securityContext)
throws NotFoundException;
Response placeMailOrder(MailOrder body,SecurityContext securityContext)
throws NotFoundException;
Response sendAdvMail(SendMailAdv body,SecurityContext securityContext)
throws NotFoundException;
Response sendAdvMail(String subject,String body,List<SendMailAdvFrom> from,List<MailContact> to,Long id,List<MailContact> replyto,List<MailContact> cc,List<MailContact> bcc,List<MailAttachment> attachments,SecurityContext securityContext)
throws NotFoundException;
Response sendMail(String to,String from,String subject,String body,SecurityContext securityContext)
throws NotFoundException;
Response sendMail(SendMail body,SecurityContext securityContext)
throws NotFoundException;
Response validateMailOrder(SecurityContext securityContext)
throws NotFoundException;
Response viewMailLog(Long id,String searchString,Integer skip,Integer limit,SecurityContext securityContext)
throws NotFoundException;
}
|
iteaj/iot | iot-client/src/main/java/com/iteaj/iot/client/mqtt/api/impl/MqttConsumerProcessImpl.java | package com.iteaj.iot.client.mqtt.api.impl;
import com.iteaj.iot.client.IotNettyClient;
import com.iteaj.iot.client.mqtt.api.ClientProcess;
import com.iteaj.iot.client.mqtt.api.MqttConsumer;
import com.iteaj.iot.client.mqtt.api.MqttConsumerListener;
import com.iteaj.iot.client.mqtt.api.MqttConsumerProcess;
import com.iteaj.iot.client.mqtt.common.MessageData;
import com.iteaj.iot.client.mqtt.common.MessageStatus;
import com.iteaj.iot.client.mqtt.common.NettyLog;
import com.iteaj.iot.client.mqtt.common.SubscribeMessage;
import com.iteaj.iot.client.mqtt.protocol.ClientProtocolUtil;
import com.iteaj.iot.client.mqtt.common.core.CacheList;
import com.iteaj.iot.client.mqtt.common.core.CacheListLocalMemory;
import io.netty.handler.codec.mqtt.MqttQoS;
import java.util.ArrayList;
import java.util.List;
/**
* @author ben
* @Title: basic
* @Description:
**/
public class MqttConsumerProcessImpl extends ClientProcess implements MqttConsumerProcess, MqttConsumer {
private List<MqttConsumerListener> listeners;
private CacheList<MessageData> msgListCache;
public MqttConsumerProcessImpl(IotNettyClient client) {
this(client, new CacheListLocalMemory<>());
}
public MqttConsumerProcessImpl(IotNettyClient client, CacheList<MessageData> msgListCache) {
super(client);
this.msgListCache = msgListCache;
}
@Override
public void subscribe(String topic, int qosValue) {
SubscribeMessage msgObj = SubscribeMessage.builder().topic(topic).qos(qosValue);
subscribe(msgObj);
}
@Override
public void setConsumerListener(List<MqttConsumerListener> listeners) {
this.listeners = listeners;
}
public void subscribe(SubscribeMessage info) {
NettyLog.debug("subscribe: {} ", info);
subscribe(new SubscribeMessage[] { info });
}
private void subscribe(SubscribeMessage... info) {
if (info != null) {
int messageId = messageId().getNextMessageId(this.getClientId());
if (!channel().isActive()) {
NettyLog.debug("channel is close");
return;
}
channel().writeAndFlush(ClientProtocolUtil.subscribeMessage(messageId, info));
}
}
public void unSubscribe(String topic) {
List<String> topics = new ArrayList<String>();
topics.add(topic);
unSubscribe(topics);
}
public void unSubscribe(List<String> topics) {
if (topics != null) {
int messageId = messageId().getNextMessageId(this.getClientId());
channel().writeAndFlush(ClientProtocolUtil.unSubscribeMessage(topics, messageId));
}
}
@Override
public void saveMesage(MessageData recviceMessage) {
//if (msgListCache == null) {return;}
if ((recviceMessage != null) && (recviceMessage.getMessageId() > 0)) {
NettyLog.debug("saveMessage: {}", recviceMessage.getMessageId());
msgListCache.put(String.valueOf(recviceMessage.getMessageId()), recviceMessage);
}
}
@Override
public void delMesage(int messageId) {
if (msgListCache == null) {return;}
if (messageId > 0) {
NettyLog.debug("delMesage: {}", messageId);
msgListCache.remove(String.valueOf(messageId));
}
}
public MessageData changeMessageStatus(int messageId, MessageStatus status) {
if (msgListCache == null) {return null;}
NettyLog.debug("changeMessageStatus: {}", status.name());
MessageData msgObj = msgListCache.get(String.valueOf(messageId));
if (msgObj != null) {
msgObj.status(status);
msgListCache.put(String.valueOf(messageId), msgObj);
}
return msgObj;
}
@Override
public void processPubRel(int messageId) {
MessageData msgObj = changeMessageStatus(messageId, MessageStatus.PUBREL);
if ((msgObj != null) && (getListeners() != null)) {
if (msgObj.getQos() == MqttQoS.EXACTLY_ONCE.value()) {
getListeners().stream().filter(item -> item.matcher(msgObj.getTopic())).forEach(listener -> {
listener.receiveMessage(msgObj.getMessageId(), msgObj.getTopic(), msgObj);
});
}
}
NettyLog.debug("process Pub-rel: messageId - {} ", messageId);
}
@Override
public void processSubAck(int messageId) {
NettyLog.debug("process Sub-ack: messageId - {} ", messageId);
}
@Override
public void processUnSubBack(int messageId) {
NettyLog.debug("process Un-sub-back: messageId - {} ", messageId);
}
@Override
public void processPublish(MessageData msg) {
NettyLog.info("process Publish: {} ", msg);
if (getListeners() != null) {
getListeners().stream().filter(item -> item.matcher(msg.getTopic())).forEach(listener -> {
listener.receiveMessageByAny(msg.getMessageId(), msg.getTopic(), msg);
if (msg.getQos() == MqttQoS.AT_MOST_ONCE.value() ||
msg.getQos() == MqttQoS.EXACTLY_ONCE.value()) {
listener.receiveMessage(msg.getMessageId(), msg.getTopic(), null);
}
});
}
}
@Override
public void sendPubRecMessage(int messageId) {
NettyLog.debug("send Pub-rec: messageId - {} ", messageId);
channel().writeAndFlush(ClientProtocolUtil.pubRecMessage(messageId));
}
@Override
public void sendPubAckMessage(int messageId) {
NettyLog.debug("send Pub-ack: messageId - {} ", messageId);
channel().writeAndFlush(ClientProtocolUtil.pubAckMessage(messageId));
}
@Override
public void sendPubCompMessage(int messageId) {
NettyLog.debug("send Pub-comp: messageId - {} ", messageId);
channel().writeAndFlush(ClientProtocolUtil.pubCompMessage(messageId));
}
public List<MqttConsumerListener> getListeners() {
return listeners;
}
public void setListeners(List<MqttConsumerListener> listeners) {
this.listeners = listeners;
}
@Override
public void setCacheList(CacheList<MessageData> msgList) {
if (msgList != null) {
this.msgListCache = msgList;
}
}
}
|
urandom/webfw | middleware/error.go | package middleware
import (
"fmt"
"net/http"
"runtime/debug"
"time"
"github.com/urandom/webfw"
"github.com/urandom/webfw/context"
)
// The Error middleware provides basic panic recovery for a request. For
// this reason, it should be at the botton of the middleware chain, to
// catch any raised panics along the way. If such occurs, the response
// writer will contain the 'Internal Server Error' message, and the
// stack trace will be written to the error log. It also has a ShowStack
// option, which will cause the stack trace to be written to the response
// writer if true. It is set to true if the global configuration is set to
// "devel".
type Error struct {
ShowStack bool
}
func (emw Error) Handler(ph http.Handler, c context.Context) http.Handler {
logger := webfw.GetLogger(c)
handler := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
stack := debug.Stack()
timestamp := time.Now().Format(dateFormat)
message := fmt.Sprintf("%s - %s\n%s\n", timestamp, rec, stack)
logger.Print(message)
w.WriteHeader(http.StatusInternalServerError)
if !emw.ShowStack {
message = "Internal Server Error"
}
w.Write([]byte(message))
c.DeleteAll(r)
}
}()
ph.ServeHTTP(w, r)
}
return http.HandlerFunc(handler)
}
|
theumang100/tutorials-1 | core-python/Core_Python/algorithms/BubbleSort.py | <reponame>theumang100/tutorials-1<gh_stars>1-10
def bubbleSort(lst):
for i in range(0,len(lst)):
for j in range(i):
if lst[j] > lst[j+1]:
temp = lst[j]
lst[j] = lst[j+1]
lst[j+1] = temp
return lst
if __name__ == "__main__":
lst = [23,45,12,5,6,32,54,20]
print("Before Sorting : ",lst)
print("After Sorting (ASC Order) : ",bubbleSort(lst))
print("After Sorting (DEC Order) : ",bubbleSort(lst)[::-1]) |
afialapis/calustra | packages/orm/src/util/index.js | import merge from './merge'
import filterObj from './filterObj'
import objToTuple from './objToTuple'
export {merge, filterObj, objToTuple} |
codyseibert/ef-cms | web-client/src/presenter/sequences/submitUpdatePractitionerUserSequence.js | import { checkEmailAvailabilityAction } from '../actions/checkEmailAvailabilityAction';
import { clearAlertsAction } from '../actions/clearAlertsAction';
import { clearScreenMetadataAction } from '../actions/clearScreenMetadataAction';
import { getComputedAdmissionsDateAction } from '../actions/getComputedAdmissionsDateAction';
import { hasUpdatedEmailFactoryAction } from '../actions/hasUpdatedEmailFactoryAction';
import { setAlertErrorAction } from '../actions/setAlertErrorAction';
import { setPractitionerDetailAction } from '../actions/setPractitionerDetailAction';
import { setValidationAlertErrorsAction } from '../actions/setValidationAlertErrorsAction';
import { setValidationErrorsAction } from '../actions/setValidationErrorsAction';
import { setWaitingForResponseAction } from '../actions/setWaitingForResponseAction';
import { startShowValidationAction } from '../actions/startShowValidationAction';
import { stopShowValidationAction } from '../actions/stopShowValidationAction';
import { unsetWaitingForResponseAction } from '../actions/unsetWaitingForResponseAction';
import { updatePractitionerUserAction } from '../actions/updatePractitionerUserAction';
import { validatePractitionerAction } from '../actions/validatePractitionerAction';
const afterSuccess = [
updatePractitionerUserAction,
{
error: [setAlertErrorAction, unsetWaitingForResponseAction],
success: [setPractitionerDetailAction, clearScreenMetadataAction],
},
];
export const submitUpdatePractitionerUserSequence = [
clearAlertsAction,
startShowValidationAction,
getComputedAdmissionsDateAction,
validatePractitionerAction,
{
error: [setValidationErrorsAction, setValidationAlertErrorsAction],
success: [
setWaitingForResponseAction,
hasUpdatedEmailFactoryAction('updatedEmail'),
{
no: afterSuccess,
yes: [
checkEmailAvailabilityAction,
{
emailAvailable: afterSuccess,
emailInUse: [
unsetWaitingForResponseAction,
clearAlertsAction,
setAlertErrorAction,
setValidationErrorsAction,
setValidationAlertErrorsAction,
stopShowValidationAction,
],
},
],
},
],
},
];
|
dphaener/ramda-extension | packages/ramda-extension/src/equalsLength.js | <reponame>dphaener/ramda-extension
import { equals } from 'ramda';
import { compareLength } from './internal/lengthUtils';
/**
* Returns true if length of array equals first argument
*
* @func
* @category List
*
* @example
*
* const lengthEqualsOne = R_.equalsLength(1)
* lengthEqualsOne([{}]) // true
* lengthEqualsOne([]) // false
*
* @sig Number -> [a] -> Boolean
*/
const equalsLength = compareLength(equals);
export default equalsLength;
|
burningrain/libGDX-book-gameDelopmentByExample | chapter4/libgdx-simple-console/src/com/github/br/gdx/simple/console/Command.java | <filename>chapter4/libgdx-simple-console/src/com/github/br/gdx/simple/console/Command.java
package com.github.br.gdx.simple.console;
import com.github.br.gdx.simple.console.exception.CommandExecutionException;
/**
* Created by user on 23.12.2018.
*/
public interface Command {
String execute(String[] args) throws CommandExecutionException;
String getTitle();
String help();
}
|
evelynejuliet/main | src/test/java/seedu/ifridge/logic/commands/wastelist/FeedbackWasteCommandTest.java | <reponame>evelynejuliet/main
package seedu.ifridge.logic.commands.wastelist;
import static seedu.ifridge.logic.commands.CommandTestUtil.assertCommandSuccess;
import static seedu.ifridge.testutil.TypicalBoughtList.getTypicalBoughtList;
import static seedu.ifridge.testutil.TypicalGroceryItems.getTypicalGroceryList;
import static seedu.ifridge.testutil.TypicalShoppingList.getTypicalShoppingList;
import static seedu.ifridge.testutil.TypicalTemplateList.getTypicalTemplateList;
import static seedu.ifridge.testutil.TypicalWasteArchive.WASTE_LIST_CURRENT_MONTH;
import static seedu.ifridge.testutil.TypicalWasteArchive.WASTE_LIST_LAST_MONTH;
import static seedu.ifridge.testutil.TypicalWasteArchive.WASTE_LIST_THREE_MONTHS_AGO;
import static seedu.ifridge.testutil.TypicalWasteArchive.WASTE_LIST_TWO_MONTHS_AGO;
import static seedu.ifridge.testutil.TypicalWasteArchive.getTypicalWasteArchive;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;
import org.junit.jupiter.api.Test;
import seedu.ifridge.model.Model;
import seedu.ifridge.model.ModelManager;
import seedu.ifridge.model.ReadOnlyWasteList;
import seedu.ifridge.model.UnitDictionary;
import seedu.ifridge.model.UserPrefs;
import seedu.ifridge.model.WasteList;
import seedu.ifridge.model.waste.WasteMonth;
import seedu.ifridge.model.waste.WasteStatistic;
public class FeedbackWasteCommandTest {
@Test
public void execute_withFourMonths_success() {
TreeMap<WasteMonth, WasteList> wasteArchiveFourMonths = getTypicalWasteArchive();
Model model = new ModelManager(getTypicalGroceryList(), new UserPrefs(), getTypicalTemplateList(),
wasteArchiveFourMonths, getTypicalShoppingList(), getTypicalBoughtList(),
new UnitDictionary(new HashMap<String, String>()));
Model expectedModel = new ModelManager(model.getGroceryList(), new UserPrefs(), model.getTemplateList(),
model.getWasteArchive(), model.getShoppingList(), model.getBoughtList(),
new UnitDictionary(new HashMap<String, String>()));
String currentWastage = String.format(FeedbackWasteCommand.MESSAGE_CURRENT_WASTAGE, 0.000f, 0.000f, 14);
List<ReadOnlyWasteList> pastWasteLists = List.of(
WASTE_LIST_LAST_MONTH,
WASTE_LIST_TWO_MONTHS_AGO,
WASTE_LIST_THREE_MONTHS_AGO);
WasteStatistic predictedWastageStats = WasteStatistic
.getWeightedStatistics(WASTE_LIST_CURRENT_MONTH, pastWasteLists);
String predictedWastage = String.format(FeedbackWasteCommand.MESSAGE_PREDICTED_WASTAGE,
predictedWastageStats.getTotalWeight(),
predictedWastageStats.getTotalVolume(),
(int) Math.ceil(predictedWastageStats.getTotalQuantity()));
assertCommandSuccess(new FeedbackWasteCommand(), model, currentWastage + predictedWastage, expectedModel);
}
}
|
alishenli/heterogeneity-aware-lowering-and-optimization | lib/target/generic_llvmir/gemm.cc | //===- gemm.cc ------------------------------------------------------------===//
//
// Copyright (C) 2019-2020 Alibaba Group Holding Limited.
//
// 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 <cstdio>
#include "halo/lib/ir/ir_builder.h"
#include "halo/lib/target/generic_llvmir/generic_llvmir_codegen.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/IRBuilder.h"
namespace halo {
void GenericLLVMIRCodeGen::RunOnInstruction(GemmInst* inst) {
llvm::IRBuilder<>* ir_builder = current_llvm_builder_;
const Def& lhs = inst->GetOperand(0);
const Def& rhs = inst->GetOperand(1);
const Def& bias = inst->GetOperand(2);
llvm::Value* op0 = ir_mapping_[lhs];
llvm::Value* op1 = ir_mapping_[rhs];
llvm::Value* op2 = ir_mapping_[bias];
std::string fname = GetRTLibFuncName(*inst, lhs.GetType().GetDataType());
auto llvm_module = ir_builder->GetInsertBlock()->getParent()->getParent();
llvm::PointerType* ptr_type =
SNTypeToLLVMType(lhs.GetType().GetDataType())->getPointerTo();
llvm::Type* bool_type = ir_builder->getInt1Ty();
llvm::Type* int64_type = ir_builder->getInt64Ty();
llvm::Type* fp32_type = ir_builder->getFloatTy();
llvm::FunctionType* ftype = llvm::FunctionType::get(
ir_builder->getVoidTy(),
{ptr_type, ptr_type, ptr_type, ptr_type, int64_type, int64_type,
int64_type, int64_type, int64_type, bool_type, bool_type, fp32_type,
fp32_type},
false);
llvm::FunctionCallee callee = llvm_module->getOrInsertFunction(fname, ftype);
llvm::Value* param0 = ir_builder->CreateBitCast(op0, ptr_type);
llvm::Value* param1 = ir_builder->CreateBitCast(op1, ptr_type);
llvm::Value* param2 = ir_builder->CreateBitCast(op2, ptr_type);
llvm::Value* dim_lhs_0 =
ir_builder->getInt64(lhs.GetType().GetNumOfElementsInDim(0));
llvm::Value* dim_lhs_1 =
ir_builder->getInt64(lhs.GetType().GetNumOfElementsInDim(1));
llvm::Value* dim_rhs_0 =
ir_builder->getInt64(rhs.GetType().GetNumOfElementsInDim(0));
llvm::Value* dim_rhs_1 =
ir_builder->getInt64(rhs.GetType().GetNumOfElementsInDim(1));
llvm::Value* num_bias =
ir_builder->getInt64(bias.GetType().GetTotalNumOfElements());
llvm::Value* transpose_a = ir_builder->getInt1(inst->GetTransposeA());
llvm::Value* transpose_b = ir_builder->getInt1(inst->GetTransposeB());
llvm::Value* alpha = llvm::ConstantFP::get(fp32_type, inst->GetAlpha());
llvm::Value* beta = llvm::ConstantFP::get(fp32_type, inst->GetBeta());
llvm::Value* ret_buf = ir_builder->CreateAlloca(
TensorTypeToLLVMType(inst->GetResultType(), false), nullptr,
inst->GetName());
llvm::Value* ret_buf_ptr = ir_builder->CreateBitCast(ret_buf, ptr_type);
CreateCall(&callee, {ret_buf_ptr, param0, param1, param2, dim_lhs_0,
dim_lhs_1, dim_rhs_0, dim_rhs_1, num_bias, transpose_a,
transpose_b, alpha, beta});
ir_mapping_[*inst] = ret_buf;
}
} // namespace halo |
nextbreakpoint/example-online-shop | common/modules/core/src/main/java/com/nextbreakpoint/blueprint/common/core/TilesBitmap.java | package com.nextbreakpoint.blueprint.common.core;
import lombok.Data;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@Data
public class TilesBitmap {
private byte[] bitmap;
private static List<Integer> COUNT_TABLE = IntStream.range(0, 256)
.mapToObj(TilesBitmap::countBits)
.collect(Collectors.toList());
private static List<Integer> OFFSET_TABLE = IntStream.range(0, 8)
.mapToObj(TilesBitmap::levelOffset)
.collect(Collectors.toList());
private static int countBits(int value) {
return IntStream.range(0, 8)
.map(shift -> value & (1 << shift))
.map(mask -> mask != 0 ? 1 : 0)
.sum();
}
private static int levelOffset(int level) {
if (level == 0) {
return 0;
}
if (level == 1) {
return 1;
}
return IntStream.range(2, level)
.map(l -> 2 * (int) Math.pow(Math.pow(2, l) / 4, 2))
.sum() + 2;
}
private TilesBitmap(ByteBuffer bitmap) {
this.bitmap = bitmap.array();
}
public static TilesBitmap of(ByteBuffer bitmap) {
return new TilesBitmap(bitmap);
}
public static TilesBitmap empty() {
int size = IntStream.range(2, 8)
.map(level -> 2 * (int) Math.pow(Math.pow(2, level) / 4, 2))
.sum() + 2;
return new TilesBitmap(ByteBuffer.wrap(new byte[size]));
}
public ByteBuffer getBitmap() {
return ByteBuffer.wrap(bitmap);
}
public void reset() {
IntStream.range(0, bitmap.length)
.forEach(index -> bitmap[index] = (byte) 0);
}
public void putTile(int level, int row, int col) {
int levelOffset = OFFSET_TABLE.get(level);
if (level >= 2) {
int stride = (int) Math.pow(2, level) / 4;
int cellRow = row / 4;
int cellCol = col / 4;
int cellOffset = 2 * (cellRow * stride + cellCol);
int tileRow = row % 4;
int tileCol = col % 4;
int tileOffset = 4 * tileRow + tileCol;
int offset = tileOffset / 8;
int index = tileOffset % 8;
byte data = bitmap[levelOffset + cellOffset + offset];
bitmap[levelOffset + cellOffset + offset] = (byte) (data | (1 << index));
} else {
int tileOffset = 4 * row + col;
int index = tileOffset % 8;
byte data = bitmap[levelOffset];
bitmap[levelOffset] = (byte) (data | (1 << index));
}
}
public boolean hasTile(int level, int row, int col) {
int levelOffset = OFFSET_TABLE.get(level);
if (level >= 2) {
int stride = (int) Math.pow(2, level) / 4;
int cellRow = row / 4;
int cellCol = col / 4;
int cellOffset = 2 * (cellRow * stride + cellCol);
int tileRow = row % 4;
int tileCol = col % 4;
int tileOffset = 4 * tileRow + tileCol;
int offset = tileOffset / 8;
int index = tileOffset % 8;
byte data = bitmap[levelOffset + cellOffset + offset];
return (byte) (data & (1 << index)) != 0;
} else {
int tileOffset = 4 * row + col;
int index = tileOffset % 8;
byte data = bitmap[levelOffset];
return (byte) (data & (1 << index)) != 0;
}
}
public String dump(int level) {
StringBuilder builder = new StringBuilder();
int size = (int) Math.pow(2, level);
IntStream.range(0, size).forEach(row -> IntStream.range(0, size).forEach(col -> {
if (hasTile(level, row, col)) {
builder.append("X");
} else {
builder.append("O");
}
if (col % size == size - 1) {
builder.append("\n");
}
}));
return builder.toString();
}
public Tiles toTiles(int level) {
final int total = (int) Math.rint(Math.pow(2, level * 2));
return Tiles.builder()
.withLevel(level)
.withTotal(total)
.withCompleted(countTiles(level))
.build();
}
private int countTiles(int level) {
int levelOffset = OFFSET_TABLE.get(level);
if (level < 2) {
return COUNT_TABLE.get(bitmap[levelOffset]);
}
int size = 2 * (int) Math.pow(Math.pow(2, level) / 4, 2);
return IntStream.range(0, size)
.map(index -> COUNT_TABLE.get(0xFF & ((int) bitmap[levelOffset + index]))).sum();
}
}
|
tupamba/kardex | node_modules/firebase/firestore/core/target_id_generator.js | <reponame>tupamba/kardex<gh_stars>0
/*! @license Firebase v4.5.0
Build: rev-f49c8b5
Terms: https://firebase.google.com/terms/ */
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var RESERVED_BITS = 1;
var GeneratorIds;
(function (GeneratorIds) {
GeneratorIds[GeneratorIds["LocalStore"] = 0] = "LocalStore";
GeneratorIds[GeneratorIds["SyncEngine"] = 1] = "SyncEngine";
})(GeneratorIds || (GeneratorIds = {}));
/**
* TargetIdGenerator generates monotonically increasing integer IDs. There are
* separate generators for different scopes. While these generators will operate
* independently of each other, they are scoped, such that no two generators
* will ever produce the same ID. This is useful, because sometimes the backend
* may group IDs from separate parts of the client into the same ID space.
*/
var TargetIdGenerator = /** @class */function () {
function TargetIdGenerator(generatorId, initAfter) {
if (initAfter === void 0) {
initAfter = 0;
}
this.generatorId = generatorId;
// Replace the generator part of initAfter with this generator's ID.
var afterWithoutGenerator = initAfter >> RESERVED_BITS << RESERVED_BITS;
var afterGenerator = initAfter - afterWithoutGenerator;
if (afterGenerator >= generatorId) {
// For example, if:
// this.generatorId = 0b0000
// after = 0b1011
// afterGenerator = 0b0001
// Then:
// previous = 0b1010
// next = 0b1100
this.previousId = afterWithoutGenerator | this.generatorId;
} else {
// For example, if:
// this.generatorId = 0b0001
// after = 0b1010
// afterGenerator = 0b0000
// Then:
// previous = 0b1001
// next = 0b1011
this.previousId = (afterWithoutGenerator | this.generatorId) - (1 << RESERVED_BITS);
}
}
TargetIdGenerator.prototype.next = function () {
this.previousId += 1 << RESERVED_BITS;
return this.previousId;
};
TargetIdGenerator.forLocalStore = function (initAfter) {
if (initAfter === void 0) {
initAfter = 0;
}
return new TargetIdGenerator(GeneratorIds.LocalStore, initAfter);
};
TargetIdGenerator.forSyncEngine = function () {
return new TargetIdGenerator(GeneratorIds.SyncEngine);
};
return TargetIdGenerator;
}();
exports.TargetIdGenerator = TargetIdGenerator;
//# sourceMappingURL=target_id_generator.js.map
|
mjtomlinson/CNE330_Python_1_Final_Project | pythonProject1/venv/Lib/site-packages/jsonlog/tests/test_config.py | import logging
import logging.config
import pathlib
import sys
import tempfile
import pytest
import jsonlog
import jsonlog.tests.capture
def test_basic_config(capture: jsonlog.tests.capture.Capture):
jsonlog.basicConfig()
jsonlog.warning("Hello world")
assert '"message": "Hello world"' in capture
def test_already_configured():
with pytest.warns(UserWarning):
logging.basicConfig()
jsonlog.basicConfig()
def test_basic_config_filename():
with tempfile.TemporaryDirectory() as tempdir:
jsonlog.basicConfig(filename=pathlib.Path(tempdir) / "test.log")
def test_basic_config_kwargs():
with pytest.raises(ValueError):
jsonlog.basicConfig(stream=sys.stderr, filename="test.log")
def test_ensure_config(capture: jsonlog.tests.capture.Capture):
jsonlog.warning("Hello world")
assert '"message": "Hello world"' in capture
def test_dict_config(capture: jsonlog.tests.capture.Capture):
logging.config.dictConfig(
{
"version": 1,
"disable_existing_loggers": True,
"formatters": {"json": {"()": "jsonlog.JSONFormatter"}},
"handlers": {
"stream": {
"class": "logging.StreamHandler",
"formatter": "json",
"level": "DEBUG",
}
},
"loggers": {"": {"handlers": ["stream"], "level": "DEBUG"}},
}
)
logging.warning("Hello world")
assert '"message": "Hello world"' in capture
|
dpak96/VOOGASalad | src/startscreen/NewGameDialog.java | <reponame>dpak96/VOOGASalad
package startscreen;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.layout.GridPane;
import javafx.util.Callback;
public class NewGameDialog extends Dialog {
protected GridPane myGridPane;
protected ButtonType myOKer;
protected TextField myGameName;
public NewGameDialog(){
this.setTitle("New Game");
this.setResizable(true);
myGameName = new TextField();
Label gameName = new Label("Game Name: ");
myGridPane = new GridPane();
myGridPane.add(gameName, 1, 1);
myGridPane.add(myGameName, 2, 1);
myOKer = new ButtonType("OK",ButtonData.OK_DONE);
this.getDialogPane().getButtonTypes().add(myOKer);
this.getDialogPane().setContent(myGridPane);
this.setResultConverter(new Callback<ButtonType,String>(){
public String call(ButtonType ok){
if(ok == myOKer){
return (String) myGameName.getText();
}
return "";
}
});
}
}
|
francescozoccheddu/cinolib | include/cinolib/grid_projector.tpp | /********************************************************************************
* This file is part of CinoLib *
* Copyright(C) 2016: <NAME> *
* *
* The MIT License *
* *
* 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 NON INFRINGEMENT. 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. *
* *
* Author(s): *
* *
* <NAME> (<EMAIL>) *
* http://pers.ge.imati.cnr.it/livesu/ *
* *
* Italian National Research Council (CNR) *
* Institute for Applied Mathematics and Information Technologies (IMATI) *
* Via de Marini, 6 *
* 16149 Genoa, *
* Italy *
*********************************************************************************/
#include <cinolib/grid_projector.h>
#include <cinolib/octree.h>
namespace cinolib
{
template<class M1, class V1, class E1, class F1, class P1,
class M2, class V2, class E2, class P2>
CINO_INLINE
double grid_projector( Hexmesh<M1,V1,E1,F1,P1> & m,
const Trimesh<M2,V2,E2,P2> & srf,
const GridProjectorOptions & opt)
{
struct Proj
{
unsigned int vid;
vec3d target;
double dist;
};
std::vector<Proj> targets;
// prepare octrees for projection
Octree o_srf;
Octree o_corners;
Octree o_lines;
for(unsigned int vid=0; vid<srf.num_verts(); ++vid)
{
unsigned int count = 0;
for(unsigned int eid : srf.adj_v2e(vid))
{
if(srf.edge_data(eid).flags[CREASE]) ++count;
}
switch(count)
{
case 0 : break;
case 2 : break;
default : o_corners.push_point(vid, srf.vert(vid));
}
}
for(unsigned int eid=0; eid<srf.num_edges(); ++eid)
{
if(srf.edge_data(eid).flags[CREASE])
{
o_lines.push_segment(eid, srf.edge_verts(eid));
}
}
o_srf.build_from_mesh_polys(srf);
o_corners.build();
o_lines.build();
// lavel mesh elements to set the target octree for projection
enum { CORNER, LINE, REGULAR };
m.vert_apply_label(REGULAR);
for(unsigned int vid=0; vid<m.num_verts(); ++vid)
{
if(!m.vert_is_on_srf(vid)) continue;
unsigned int count = 0;
for(unsigned int eid : m.adj_v2e(vid))
{
if(m.edge_data(eid).flags[CREASE]) ++count;
}
switch(count)
{
case 0 : m.vert_data(vid).label = REGULAR; break;
case 1 : m.vert_data(vid).label = CORNER; break;
case 2 : m.vert_data(vid).label = LINE; break;
default : m.vert_data(vid).label = CORNER;
}
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::: LAMBDA UTILITIES :::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
// for each surface point, find the closest point on srf
auto update_targets = [&](const unsigned int smooth_iters, const bool sort_by_dist)
{
// pre smooth the surface
std::vector<vec3d> verts = m.vector_verts();
for(unsigned int i=0; i<smooth_iters; ++i)
{
PARALLEL_FOR(0, m.num_verts(), 1000,[&](const unsigned int vid)
{
vec3d p;
if(m.vert_is_on_srf(vid))
{
for(unsigned int nbr : m.vert_adj_srf_verts(vid)) p += verts.at(nbr);
p /= static_cast<double>(m.vert_adj_srf_verts(vid).size());
}
else
{
double sum = 0.0;
for(unsigned int nbr : m.adj_v2v(vid))
{
double w = (m.vert_is_on_srf(nbr)) ? 2.0 : 0.5;
p += w * verts.at(nbr);
sum += w;
}
p /= sum;
}
verts.at(vid) = p;
});
}
targets.clear();
for(unsigned int vid=0; vid<m.num_verts(); ++vid)
{
Proj proj;
proj.vid = vid;
switch(m.vert_data(vid).label)
{
case REGULAR : proj.target = (m.vert_is_on_srf(vid)) ? o_srf.closest_point(verts.at(vid)) : verts.at(vid); break;
case CORNER : proj.target = o_corners.closest_point(verts.at(vid)); break;
case LINE : proj.target = o_lines.closest_point(verts.at(vid)); break;
}
proj.dist = (m.vert_is_on_srf(vid)) ? 1/verts.at(vid).dist(proj.target) : -verts.at(vid).dist(proj.target);
targets.push_back(proj);
}
if(sort_by_dist)
{
std::sort(targets.begin(), targets.end(), [](const Proj & p1,const Proj & p2) -> bool { return p1.dist>p2.dist; } );
}
};
// scaled jacobian
auto SJ_OK = [&](const unsigned int pid, const unsigned int vid, const vec3d & pos) -> bool
{
std::vector<vec3d> h = m.poly_verts(pid);
double SJ_bef = hex_scaled_jacobian(h[0],h[1],h[2],h[3],h[4],h[5],h[6],h[7]);
h.at(m.poly_vert_offset(pid, vid)) = pos;
double SJ_aft = hex_scaled_jacobian(h[0],h[1],h[2],h[3],h[4],h[5],h[6],h[7]);
if(SJ_bef > opt.SJ_thresh && SJ_aft > opt.SJ_thresh) return true;
if(SJ_bef <= opt.SJ_thresh && SJ_aft >= SJ_bef) return true; // if it was already bad, just don't make it worse
return false;
};
// project a point on target, reverting with binary search if some element becomes degenerate
auto binary_search = [&](const unsigned int vid, const vec3d & target) -> vec3d // returns dist to target
{
float t = 1.0;
unsigned int i = 0;
vec3d new_pos = target;
bool all_good;
do
{
all_good = true;
for(unsigned int pid : m.adj_v2p(vid))
{
if(!SJ_OK(pid,vid,new_pos))
{
all_good = false;
break;
}
}
if(!all_good)
{
t *=0.5;
new_pos = target*t + m.vert(vid)*(1.0-t);
}
}
while(++i<6 && !all_good);
if(all_good) return new_pos;
return m.vert(vid);
};
// compute average/Hausodrff distance
auto distance = [&](const bool hausdorff) -> double
{
double d = (hausdorff) ? -inf_double : 0.0;
for(auto t : targets) d = (hausdorff) ? std::max(d,t.dist) : d + t.dist;
if(!hausdorff) d /= static_cast<double>(targets.size());
return d/m.bbox().diag();
};
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::: BEGIN OF ACTUAL METHOD ::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
bool converged = false;
for(unsigned int i=0; i<opt.max_iter && !converged; ++i)
{
update_targets(3,true);
// process points and store the new distance to target for next iteration
for(auto & t : targets)
{
vec3d p = binary_search(t.vid, t.target);
m.vert(t.vid) = p;
t.dist = p.dist(t.target);
}
converged = distance(opt.use_H_dist) <= opt.conv_thresh;
}
return distance(opt.use_H_dist);
}
}
|
connorslagle/connorslagle.github.io | vendor/bundle/ruby/2.6.0/gems/octokit-4.18.0/lib/octokit/client/milestones.rb | module Octokit
class Client
# Methods for the Issues Milestones API
#
# @see https://developer.github.com/v3/issues/milestones/
module Milestones
# List milestones for a repository
#
# @param repository [Integer, String, Repository, Hash] A GitHub repository
# @param options [Hash] A customizable set of options.
# @option options [Integer] :milestone Milestone number.
# @option options [String] :state (open) State: <tt>open</tt>, <tt>closed</tt>, or <tt>all</tt>.
# @option options [String] :sort (created) Sort: <tt>created</tt>, <tt>updated</tt>, or <tt>comments</tt>.
# @option options [String] :direction (desc) Direction: <tt>asc</tt> or <tt>desc</tt>.
# @return [Array<Sawyer::Resource>] A list of milestones for a repository.
# @see https://developer.github.com/v3/issues/milestones/#list-milestones-for-a-repository
# @example List milestones for a repository
# Octokit.list_milestones("octokit/octokit.rb")
def list_milestones(repository, options = {})
paginate "#{Repository.path repository}/milestones", options
end
alias :milestones :list_milestones
# Get a single milestone for a repository
#
# @param repository [Integer, String, Repository, Hash] A GitHub repository
# @param options [Hash] A customizable set of options.
# @option options [Integer] :milestone Milestone number.
# @return [Sawyer::Resource] A single milestone from a repository.
# @see https://developer.github.com/v3/issues/milestones/#get-a-single-milestone
# @example Get a single milestone for a repository
# Octokit.milestone("octokit/octokit.rb", 1)
def milestone(repository, number, options = {})
get "#{Repository.path repository}/milestones/#{number}", options
end
# Create a milestone for a repository
#
# @param repository [Integer, String, Repository, Hash] A GitHub repository
# @param title [String] A unique title.
# @param options [Hash] A customizable set of options.
# @option options [String] :state (open) State: <tt>open</tt> or <tt>closed</tt>.
# @option options [String] :description A meaningful description
# @option options [Time] :due_on Set if the milestone has a due date
# @return [Sawyer::Resource] A single milestone object
# @see https://developer.github.com/v3/issues/milestones/#create-a-milestone
# @example Create a milestone for a repository
# Octokit.create_milestone("octokit/octokit.rb", "0.7.0", {:description => 'Add support for v3 of Github API'})
def create_milestone(repository, title, options = {})
post "#{Repository.path repository}/milestones", options.merge({:title => title})
end
# Update a milestone for a repository
#
# @param repository [Integer, String, Repository, Hash] A GitHub repository
# @param number [String, Integer] ID of the milestone
# @param options [Hash] A customizable set of options.
# @option options [String] :title A unique title.
# @option options [String] :state (open) State: <tt>open</tt> or <tt>closed</tt>.
# @option options [String] :description A meaningful description
# @option options [Time] :due_on Set if the milestone has a due date
# @return [Sawyer::Resource] A single milestone object
# @see https://developer.github.com/v3/issues/milestones/#update-a-milestone
# @example Update a milestone for a repository
# Octokit.update_milestone("octokit/octokit.rb", 1, {:description => 'Add support for v3 of Github API'})
def update_milestone(repository, number, options = {})
patch "#{Repository.path repository}/milestones/#{number}", options
end
alias :edit_milestone :update_milestone
# Delete a single milestone for a repository
#
# @param repository [Integer, String, Repository, Hash] A GitHub repository
# @param options [Hash] A customizable set of options.
# @option options [Integer] :milestone Milestone number.
# @return [Boolean] Success
# @see https://developer.github.com/v3/issues/milestones/#delete-a-milestone
# @example Delete a single milestone from a repository
# Octokit.delete_milestone("octokit/octokit.rb", 1)
def delete_milestone(repository, number, options = {})
boolean_from_response :delete, "#{Repository.path repository}/milestones/#{number}", options
end
end
end
end
|
stage-tech/basestar | basestar-schema/src/main/java/io/basestar/schema/History.java | <gh_stars>1-10
package io.basestar.schema;
/*-
* #%L
* basestar-schema
* %%
* Copyright (C) 2019 - 2020 Basestar.IO
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.fasterxml.jackson.annotation.JsonCreator;
import lombok.Data;
import java.io.Serializable;
@Data
public class History implements Serializable {
// Enabled with default (storage best) consistency
public static final History ENABLED = new History(true);
public static final History DISABLED = new History(false);
public static final String ENABLED_VALUE = "ENABLED";
public static final String DISABLED_VALUE = "DISABLED";
private final boolean enabled;
private final Consistency consistency;
public History(final boolean enabled) {
this(enabled, null);
}
public History(final boolean enabled, final Consistency consistency) {
this.enabled = enabled;
this.consistency = consistency;
}
public Consistency getConsistency(final Consistency defaultValue) {
if(consistency == null) {
return defaultValue;
} else {
return consistency;
}
}
@JsonCreator
public static History fromString(final String str) {
final String upper = str.toUpperCase();
switch (upper) {
case ENABLED_VALUE:
return ENABLED;
case DISABLED_VALUE:
return DISABLED;
default:
return new History(true, Consistency.valueOf(upper));
}
}
}
|
mitring/cuba | modules/web-toolkit/src/com/haulmont/cuba/web/widgets/client/twincolselect/CubaTwinColSelectWidget.java | <reponame>mitring/cuba
/*
* Copyright (c) 2008-2016 Haulmont.
*
* 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.haulmont.cuba.web.widgets.client.twincolselect;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.SelectElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.ListBox;
import com.vaadin.client.UIDL;
import com.vaadin.client.ui.VButton;
import com.vaadin.v7.client.ui.VTwinColSelect;
import java.util.HashSet;
import java.util.Set;
public class CubaTwinColSelectWidget extends VTwinColSelect {
protected boolean addAllBtnEnabled;
protected VButton addAll;
protected VButton removeAll;
protected HandlerRegistration addAllHandlerRegistration;
protected HandlerRegistration removeAllHandlerRegistration;
public CubaTwinColSelectWidget() {
add.setText(">");
add.addStyleName("add");
remove.setText("<");
remove.addStyleName("remove");
}
@Override
protected DoubleClickListBox createOptionsBox() {
return new CubaDoubleClickListBox();
}
@Override
protected DoubleClickListBox createSelectionsBox() {
return new CubaDoubleClickListBox();
}
@Override
public void buildOptions(UIDL uidl) {
options.setMultipleSelect(isMultiselect());
selections.setMultipleSelect(isMultiselect());
int optionsSelectedIndex = options.getSelectedIndex();
int selectionsSelectedIndex = selections.getSelectedIndex();
options.clear();
selections.clear();
int selectedOptions = 0;
int availableOptions = 0;
for (Object anUidl : uidl) {
UIDL optionUidl = (UIDL) anUidl;
if (optionUidl.hasAttribute("selected")) {
selections.addItem(optionUidl.getStringAttribute("caption"),
optionUidl.getStringAttribute("key"));
if (optionUidl.hasAttribute("style")) {
CubaDoubleClickListBox cubaSelections = (CubaDoubleClickListBox) selections;
cubaSelections.setOptionClassName(selectedOptions, optionUidl.getStringAttribute("style"));
}
selectedOptions++;
} else {
options.addItem(optionUidl.getStringAttribute("caption"),
optionUidl.getStringAttribute("key"));
if (optionUidl.hasAttribute("style")) {
CubaDoubleClickListBox cubaOptions = (CubaDoubleClickListBox) options;
cubaOptions.setOptionClassName(availableOptions, optionUidl.getStringAttribute("style"));
}
availableOptions++;
}
}
if (getRows() > 0) {
options.setVisibleItemCount(getRows());
selections.setVisibleItemCount(getRows());
}
setSelectedIndex(options, optionsSelectedIndex);
setSelectedIndex(selections, selectionsSelectedIndex);
}
protected void setSelectedIndex(ListBox listBox, int index) {
if (listBox.getItemCount() > 0 && index >= 0) {
listBox.setSelectedIndex(index);
}
}
@Override
public void onClick(ClickEvent event) {
super.onClick(event);
if (addAllBtnEnabled) {
if (event.getSource() == addAll) {
addAll();
} else if (event.getSource() == removeAll) {
removeAll();
}
}
}
private Set<String> moveAllItems(ListBox source, ListBox target) {
final Set<String> movedItems = new HashSet<String>();
int size = source.getItemCount();
for (int i = 0; i < size; i++) {
movedItems.add(source.getValue(i));
final String text = source.getItemText(i);
final String value = source.getValue(i);
target.addItem(text, value);
target.setItemSelected(target.getItemCount() - 1, true);
}
target.setFocus(true);
if (source.getItemCount() > 0) {
target.setSelectedIndex(0);
}
source.clear();
return movedItems;
}
protected void addAll() {
Set<String> movedItems = moveAllItems(options, selections);
selectedKeys.addAll(movedItems);
client.updateVariable(paintableId, "selected",
selectedKeys.toArray(new String[selectedKeys.size()]),
isImmediate());
}
protected void removeAll() {
moveAllItems(selections, options);
selectedKeys.clear();
client.updateVariable(paintableId, "selected",
selectedKeys.toArray(new String[selectedKeys.size()]),
isImmediate());
}
public boolean isAddAllBtnEnabled() {
return addAllBtnEnabled;
}
public void setAddAllBtnEnabled(boolean addAllBtnEnabled) {
if (addAllBtnEnabled != this.addAllBtnEnabled) {
this.addAllBtnEnabled = addAllBtnEnabled;
if (addAllBtnEnabled) {
enableAddAllBtn();
} else {
disableAddAllBtn();
}
}
}
protected void enableAddAllBtn() {
HTML br1 = new HTML("<span/>");
br1.setStyleName(CLASSNAME + "-deco");
buttons.add(br1);
buttons.insert(br1, buttons.getWidgetIndex(add) + 1);
addAll = new VButton();
addAll.setText(">>");
addAll.addStyleName("addAll");
addAllHandlerRegistration = addAll.addClickHandler(this);
buttons.insert(addAll, buttons.getWidgetIndex(br1) + 1);
HTML br2 = new HTML("<span/>");
br2.setStyleName(CLASSNAME + "-deco");
buttons.add(br2);
removeAll = new VButton();
removeAll.setText("<<");
removeAll.addStyleName("removeAll");
removeAllHandlerRegistration = removeAll.addClickHandler(this);
buttons.add(removeAll);
}
protected void disableAddAllBtn() {
addAll.removeFromParent();
addAllHandlerRegistration.removeHandler();
addAll = null;
removeAll.removeFromParent();
removeAllHandlerRegistration.removeHandler();
removeAll = null;
}
public class CubaDoubleClickListBox extends DoubleClickListBox {
public void setOptionClassName(int optionIndex, String className) {
assert optionIndex >= 0 && options.getItemCount() > optionIndex;
SelectElement select = getElement().cast();
Element elem = select.getOptions().getItem(optionIndex);
elem.addClassName(className);
}
}
} |
fearthecowboy/yarn-aio | lib/workspace-layout.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _packageRequest;
function _load_packageRequest() {
return _packageRequest = _interopRequireDefault(require('./package-request.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const semver = require('semver');
class WorkspaceLayout {
constructor(workspaces, config) {
this.workspaces = workspaces;
this.config = config;
}
getWorkspaceManifest(key) {
return this.workspaces[key];
}
getManifestByPattern(pattern) {
var _PackageRequest$norma = (_packageRequest || _load_packageRequest()).default.normalizePattern(pattern);
const name = _PackageRequest$norma.name,
range = _PackageRequest$norma.range;
const workspace = this.getWorkspaceManifest(name);
if (!workspace || !semver.satisfies(workspace.manifest.version, range, this.config.looseSemver)) {
return null;
}
return workspace;
}
}
exports.default = WorkspaceLayout; |
danielzfranklin/lldb-sys.rs | src/lldb/Bindings/SBDeclarationBinding.cpp | <gh_stars>0
//===-- SBDeclarationBinding.cpp --------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Bindings/LLDBBinding.h"
#include "lldb/API/LLDB.h"
using namespace lldb;
#ifdef __cplusplus
extern "C" {
#endif
SBDeclarationRef
CreateSBDeclaration()
{
return reinterpret_cast<SBDeclarationRef>(new SBDeclaration());
}
SBDeclarationRef
CloneSBDeclaration(SBDeclarationRef instance)
{
return reinterpret_cast<SBDeclarationRef>(new SBDeclaration(*reinterpret_cast<SBDeclaration *>(instance)));
}
void
DisposeSBDeclaration(SBDeclarationRef instance)
{
delete reinterpret_cast<SBDeclaration *>(instance);
}
bool
SBDeclarationIsValid(SBDeclarationRef instance)
{
SBDeclaration *unwrapped = reinterpret_cast<SBDeclaration *>(instance);
return unwrapped->IsValid();
}
SBFileSpecRef
SBDeclarationGetFileSpec(SBDeclarationRef instance)
{
SBDeclaration *unwrapped = reinterpret_cast<SBDeclaration *>(instance);
return reinterpret_cast<SBFileSpecRef>(new SBFileSpec(unwrapped->GetFileSpec()));
}
unsigned int
SBDeclarationGetLine(SBDeclarationRef instance)
{
SBDeclaration *unwrapped = reinterpret_cast<SBDeclaration *>(instance);
return unwrapped->GetLine();
}
unsigned int
SBDeclarationGetColumn(SBDeclarationRef instance)
{
SBDeclaration *unwrapped = reinterpret_cast<SBDeclaration *>(instance);
return unwrapped->GetColumn();
}
void
SBDeclarationSetFileSpec(SBDeclarationRef instance, SBFileSpecRef filespec)
{
SBDeclaration *unwrapped = reinterpret_cast<SBDeclaration *>(instance);
unwrapped->SetFileSpec(*reinterpret_cast<SBFileSpec *>(filespec));
}
void
SBDeclarationSetLine(SBDeclarationRef instance, uint32_t line)
{
SBDeclaration *unwrapped = reinterpret_cast<SBDeclaration *>(instance);
unwrapped->SetLine(line);
}
void
SBDeclarationSetColumn(SBDeclarationRef instance, uint32_t column)
{
SBDeclaration *unwrapped = reinterpret_cast<SBDeclaration *>(instance);
unwrapped->SetColumn(column);
}
bool
SBDeclarationGetDescription(SBDeclarationRef instance, SBStreamRef description)
{
SBDeclaration *unwrapped = reinterpret_cast<SBDeclaration *>(instance);
return unwrapped->GetDescription(*reinterpret_cast<SBStream *>(description));
}
#ifdef __cplusplus
}
#endif
|
xstefank/smallrye-fault-tolerance | implementation/core/src/main/java/io/smallrye/faulttolerance/core/timeout/TimerTimeoutWatcher.java | package io.smallrye.faulttolerance.core.timeout;
import io.smallrye.faulttolerance.core.timer.Timer;
import io.smallrye.faulttolerance.core.timer.TimerTask;
public class TimerTimeoutWatcher implements TimeoutWatcher {
private final Timer timer;
public TimerTimeoutWatcher(Timer timer) {
this.timer = timer;
}
@Override
public TimeoutWatch schedule(TimeoutExecution execution) {
TimerTask task = timer.schedule(execution.timeoutInMillis(), execution::timeoutAndInterrupt);
return new TimeoutWatch() {
@Override
public boolean isRunning() {
return !task.isDone();
}
@Override
public void cancel() {
task.cancel();
}
};
}
}
|
lvaughn/advent | 2017/2/checksum.py | <filename>2017/2/checksum.py
#!/usr/bin/env python3
import re
rows = []
total = 0
with open('input.txt', 'r') as f:
for line in f:
data = [int(a) for a in re.split(r'\s+', line.strip())]
total += max(data) - min(data)
rows.append(data)
print("Part 1", total)
total = 0
for row in rows:
for i in range(len(row) - 1):
found = False
for j in range(i+1, len(row)):
if max(row[i], row[j]) % min(row[i], row[j]) == 0:
total += max(row[i], row[j]) // min(row[i], row[j])
found = True
break
if found:
break
print('Part 2', total)
|
KrossX/Advent_of_Code | 2019/day06_data.c | <reponame>KrossX/Advent_of_Code
/* Copyright (c) 2019 KrossX <<EMAIL>>
* License: http://www.opensource.org/licenses/mit-license.html MIT License
*/
char input[][2][4] = {
{"WGB","S14"},
{"WN4","27C"},
{"18L","M18"},
{"1HY","6ZP"},
{"TQ9","KQ6"},
{"HQ3","HH1"},
{"FLC","F1Z"},
{"D6R","ZPC"},
{"2VD","GK3"},
{"YY3","3TP"},
{"PBL","3CK"},
{"5K4","CB5"},
{"V5M","CNN"},
{"L4T","RHS"},
{"HHH","66F"},
{"Q3Y","DTL"},
{"DGN","YY3"},
{"CCT","L3B"},
{"Z6X","FM2"},
{"2QQ","VK9"},
{"MX3","C9J"},
{"4JK","BPX"},
{"8BP","N13"},
{"PBW","6Z6"},
{"2LT","DT9"},
{"JHX","GXM"},
{"5LW","BHQ"},
{"DNK","ZBT"},
{"29Z","T9D"},
{"WNP","TDC"},
{"S38","GL6"},
{"DW9","V2F"},
{"4MG","3FW"},
{"Z9Z","CPK"},
{"FKL","QNH"},
{"55D","HT2"},
{"D1D","N4Q"},
{"Y7W","1Y8"},
{"SFQ","79W"},
{"JSR","62W"},
{"4WN","J18"},
{"VK9","J2H"},
{"LS5","DCX"},
{"6LR","P4X"},
{"HDV","DGQ"},
{"1K9","KD1"},
{"2PX","17C"},
{"KSB","GL8"},
{"B4S","VTV"},
{"ZW1","KNR"},
{"BVH","43P"},
{"VKP","6L3"},
{"P5K","MHR"},
{"XHR","STT"},
{"WBG","5X5"},
{"HZF","8JQ"},
{"B47","NW4"},
{"J5V","3ZW"},
{"KGP","VVR"},
{"24K","PK8"},
{"31V","LXC"},
{"5XG","RHP"},
{"P1G","HN8"},
{"R76","3GY"},
{"5CH","17Q"},
{"TVC","XJM"},
{"598","RD3"},
{"J66","LKC"},
{"4DY","YSQ"},
{"M4Y","NLL"},
{"SMP","M2M"},
{"TBR","WNP"},
{"K22","KGP"},
{"MQ5","8MN"},
{"B9Q","6HQ"},
{"P9S","X92"},
{"TJK","ZQK"},
{"XS7","7KL"},
{"H6J","DX1"},
{"MTP","3Z6"},
{"B17","B7P"},
{"S12","PC2"},
{"47V","5KW"},
{"KCY","HWP"},
{"FB2","S38"},
{"V5M","FNT"},
{"GXM","QPR"},
{"HXR","2R2"},
{"2LV","NDP"},
{"6HQ","12S"},
{"22P","4HL"},
{"T8Q","9FB"},
{"8YW","TVZ"},
{"DR1","NNN"},
{"9TH","87Z"},
{"79W","TM2"},
{"5GB","HQM"},
{"1HY","4WN"},
{"LFV","RYJ"},
{"YCN","ZMK"},
{"8SR","SB3"},
{"P9H","PH9"},
{"ZGQ","T3J"},
{"KWW","1HY"},
{"TLF","RPG"},
{"PFD","HZR"},
{"9SF","7PY"},
{"DCX","VCC"},
{"D1R","2RB"},
{"GXC","NN9"},
{"ZZW","SCC"},
{"G44","Q8D"},
{"923","3J2"},
{"KY2","8F4"},
{"1XQ","7LD"},
{"GHX","Q6M"},
{"TZ5","V32"},
{"LM9","1XK"},
{"Q7N","Z7H"},
{"YKD","73H"},
{"9RZ","C2Q"},
{"5KN","P1G"},
{"3FJ","L73"},
{"ZPC","VYT"},
{"Y7D","FFY"},
{"C8W","J1Y"},
{"X5T","55D"},
{"Z3F","GK8"},
{"WRS","PRR"},
{"T9M","JK2"},
{"81P","5WT"},
{"7KL","5BK"},
{"S3R","VCD"},
{"56L","D1R"},
{"PR2","92L"},
{"91F","2F4"},
{"ND4","PJ6"},
{"9KY","YD4"},
{"CLH","5D7"},
{"J2F","L7Z"},
{"M4Y","PYG"},
{"891","P34"},
{"VV6","18L"},
{"RQQ","X8P"},
{"7SR","8G6"},
{"WJ8","CDL"},
{"9FB","TXD"},
{"RKK","2H5"},
{"3W8","2QQ"},
{"27C","YFC"},
{"RZZ","91F"},
{"4CP","BWH"},
{"T4L","LS5"},
{"788","G7S"},
{"47V","3W8"},
{"FGK","719"},
{"16Q","4KW"},
{"5H6","PC9"},
{"KGS","TBR"},
{"44Y","BVH"},
{"GMF","VFM"},
{"LKC","PM4"},
{"DPL","DXS"},
{"2WD","X5T"},
{"XWX","NYR"},
{"N44","Y36"},
{"72S","56L"},
{"W25","4MG"},
{"P9S","HBC"},
{"W84","3YP"},
{"NW4","S78"},
{"58Y","LDB"},
{"QJ9","VV1"},
{"5D3","4Q7"},
{"T3J","5M4"},
{"394","ZW7"},
{"JXL","QVK"},
{"7KL","FTL"},
{"885","ZGQ"},
{"58Y","8SR"},
{"GXN","PBW"},
{"HH1","JB4"},
{"H6J","W95"},
{"VYK","SQS"},
{"CCS","7CZ"},
{"PJ7","NLR"},
{"2VW","MSP"},
{"ZWK","H6X"},
{"HJ4","C1S"},
{"H41","1L3"},
{"8B9","64N"},
{"RZR","WBJ"},
{"FNT","VL7"},
{"K5M","S5Q"},
{"XJM","TC7"},
{"QWT","7Q5"},
{"43P","MY2"},
{"YP7","51N"},
{"TDX","FWZ"},
{"DB3","NCK"},
{"37M","H2L"},
{"Z3X","XRS"},
{"SGV","R2T"},
{"Y2F","63M"},
{"ZVY","JTX"},
{"DJB","KQD"},
{"848","FQP"},
{"SX3","FM5"},
{"PH9","ZPG"},
{"75S","Z9L"},
{"GPD","Y7D"},
{"9Y6","52N"},
{"SL4","S3R"},
{"4TH","T6F"},
{"K4V","D8V"},
{"89S","18F"},
{"GDN","WN4"},
{"6HT","TQZ"},
{"V1Q","JVG"},
{"R55","2LC"},
{"KH3","NT5"},
{"Q53","3DN"},
{"SRV","JND"},
{"XMC","MKK"},
{"T5J","6HT"},
{"HZR","M1M"},
{"P34","3RY"},
{"HF6","SD2"},
{"PTM","C9X"},
{"3MZ","T9M"},
{"R76","MFF"},
{"B9Y","3MC"},
{"NFG","5FC"},
{"M63","4CP"},
{"FRG","PVQ"},
{"58Z","GDM"},
{"ZT8","4L5"},
{"F5B","KF3"},
{"SQT","NTZ"},
{"M2M","252"},
{"35Y","5WF"},
{"C9J","8BP"},
{"W8H","F78"},
{"H8Z","2VW"},
{"91P","5FP"},
{"VTV","YN7"},
{"2KM","1K9"},
{"KSX","TR8"},
{"9DK","XD6"},
{"MFF","KQR"},
{"414","6L9"},
{"FQ7","T5K"},
{"G8M","WPX"},
{"794","FMS"},
{"WZV","XS7"},
{"VVR","5CH"},
{"R8G","9RH"},
{"B4D","2RT"},
{"PJ6","GWB"},
{"63M","NHF"},
{"8G7","8B9"},
{"QP5","9ZW"},
{"FW6","CDM"},
{"S5Q","172"},
{"T24","TPD"},
{"YRT","GMF"},
{"1TJ","SGV"},
{"RV3","C3D"},
{"661","MHS"},
{"QYT","D2K"},
{"T49","MFP"},
{"GY7","T2Q"},
{"686","Z4G"},
{"J49","R9L"},
{"R5S","67X"},
{"L7Z","5RM"},
{"RPP","WG9"},
{"5KW","2KM"},
{"5N2","Y7W"},
{"Z3X","JFD"},
{"KD8","4H5"},
{"5MP","RVK"},
{"12S","S2Y"},
{"TPD","D5F"},
{"51N","81P"},
{"DCH","SGQ"},
{"L6N","VKP"},
{"2XQ","6LR"},
{"3DN","S3L"},
{"VS4","83N"},
{"8DJ","WZP"},
{"DCX","FX1"},
{"SF9","Z3F"},
{"R49","S99"},
{"D1C","794"},
{"TKN","L83"},
{"21R","GP3"},
{"5RM","TG3"},
{"ZMK","R49"},
{"1QT","152"},
{"9DX","GXC"},
{"GYC","TQ9"},
{"JND","LMK"},
{"D8Z","SCW"},
{"VNZ","VS4"},
{"C1S","9RZ"},
{"LKF","D8Z"},
{"G4J","R44"},
{"92L","J66"},
{"88P","657"},
{"8Z5","R55"},
{"VV1","KRY"},
{"N44","2QK"},
{"KBC","KKG"},
{"91P","L6N"},
{"SVH","7W3"},
{"P9Z","34H"},
{"BWH","9TH"},
{"JNX","RZZ"},
{"YFG","ZT8"},
{"DSM","FF3"},
{"BMK","ZR6"},
{"7W3","V82"},
{"T9D","H2S"},
{"2QF","PFD"},
{"NDQ","F13"},
{"ZVB","MX6"},
{"KRY","7FB"},
{"KKG","HJ4"},
{"QNH","MFQ"},
{"5X5","VQM"},
{"HQM","HF6"},
{"HLT","TD2"},
{"WV4","FWH"},
{"N2T","5B5"},
{"D1R","P89"},
{"HKT","3MZ"},
{"ZQK","1DK"},
{"QQQ","FLC"},
{"73Z","TTM"},
{"ZZW","769"},
{"8G7","TYL"},
{"MFP","WMS"},
{"RQS","2YC"},
{"NLL","JHX"},
{"KCY","CSP"},
{"9F8","51H"},
{"SGQ","B27"},
{"4KM","VYK"},
{"JDY","MTW"},
{"T8Q","DB3"},
{"1VL","VV6"},
{"VV5","B4D"},
{"SPF","JR5"},
{"LYS","6CK"},
{"YMK","2VD"},
{"TD2","1VL"},
{"JKH","QHX"},
{"VD4","58J"},
{"9QQ","HKL"},
{"8JP","HQ3"},
{"NHS","31S"},
{"81Z","Q5W"},
{"R7Q","Z9M"},
{"WMS","ZK2"},
{"3J2","GY7"},
{"MFQ","CLH"},
{"S14","934"},
{"HY7","YBT"},
{"4SY","63F"},
{"NQF","PPQ"},
{"T9W","RZR"},
{"WL2","6QM"},
{"LZV","WRQ"},
{"TVZ","T9P"},
{"4X5","GN5"},
{"NQ8","FPQ"},
{"J5J","K51"},
{"Y8T","WGM"},
{"FPQ","B53"},
{"1XK","TKX"},
{"XDW","72V"},
{"WW8","9QQ"},
{"XX7","Q7N"},
{"CDM","GHX"},
{"VCC","HPP"},
{"QRK","56B"},
{"MTW","2QT"},
{"7V5","58Z"},
{"PYY","T24"},
{"9HB","J8F"},
{"TTM","PTB"},
{"FF3","ZY3"},
{"ZW7","D1D"},
{"T4H","ZTG"},
{"2PW","DSM"},
{"9WB","4TH"},
{"17C","FKX"},
{"T6F","QP3"},
{"G6R","XHR"},
{"H5T","QYT"},
{"DX1","Q9L"},
{"GJF","ZF3"},
{"LJP","JXL"},
{"QHX","3XY"},
{"DNF","8KQ"},
{"8Q1","NDQ"},
{"GP3","6MY"},
{"FPQ","QQQ"},
{"XRS","923"},
{"Q6M","7BS"},
{"K21","B47"},
{"TQZ","WJ4"},
{"9PB","3PQ"},
{"8G6","X7M"},
{"L3B","YOU"},
{"L5V","G2L"},
{"B8Y","JVS"},
{"GL6","MTP"},
{"9QZ","NRN"},
{"486","T8Q"},
{"HNN","PNM"},
{"NFK","B4S"},
{"G9C","LHT"},
{"4K9","SL4"},
{"8X5","179"},
{"VQM","47V"},
{"CNJ","J4R"},
{"ZD5","2PX"},
{"9TQ","X9Q"},
{"Q3Q","9DK"},
{"17Q","1KX"},
{"5GN","24K"},
{"K5Q","1NF"},
{"LCK","9WB"},
{"TYL","PYL"},
{"7XG","R2L"},
{"LXC","ZWK"},
{"Q62","SPF"},
{"89C","N7Z"},
{"GK8","GR7"},
{"6X1","5N2"},
{"XM8","8Q1"},
{"MCD","GXQ"},
{"S2Y","N7G"},
{"CB5","C8W"},
{"NHF","44B"},
{"QPR","GF5"},
{"HGX","YMY"},
{"3FW","2LV"},
{"5WF","RQQ"},
{"841","N31"},
{"Q9L","876"},
{"WQ8","HZ7"},
{"6K1","QVC"},
{"C2T","FQX"},
{"J3M","HLT"},
{"H2S","K5Q"},
{"STQ","8ZF"},
{"VDX","NQF"},
{"YSR","G8M"},
{"CSL","NLF"},
{"MHS","3FH"},
{"YN7","VWC"},
{"RSW","X11"},
{"FXS","L54"},
{"YBT","HX4"},
{"BHQ","FRG"},
{"83H","K4Q"},
{"NT5","2ZB"},
{"GWB","4K9"},
{"YMY","5KN"},
{"4Q7","C3G"},
{"D3J","HZF"},
{"32D","GN7"},
{"VGG","G3D"},
{"LVG","JXR"},
{"25V","GDN"},
{"L6V","KL8"},
{"FW2","STQ"},
{"V6H","8G7"},
{"COM","CB6"},
{"6Z6","SQT"},
{"W81","6M3"},
{"D2K","XF6"},
{"2NX","9KY"},
{"KRQ","LKF"},
{"P1B","VVQ"},
{"QTV","Q3Y"},
{"DTZ","ZLY"},
{"R3T","FQ7"},
{"D92","72S"},
{"H8N","9Y6"},
{"FWZ","WGB"},
{"VQW","LHJ"},
{"2HB","848"},
{"9ZW","NT8"},
{"NLR","QTV"},
{"31V","DSZ"},
{"92J","WXY"},
{"8LK","QQ3"},
{"769","ZD5"},
{"8L9","T5J"},
{"TB2","V5M"},
{"VZQ","57T"},
{"Z7H","JMR"},
{"94D","YCN"},
{"ZPF","6WK"},
{"M1F","6C2"},
{"MHV","ZCS"},
{"Q53","FBC"},
{"RPG","P3N"},
{"RHS","JDY"},
{"FTL","FB2"},
{"J47","R3T"},
{"Y9S","4JK"},
{"ZVY","TK6"},
{"LTX","BM5"},
{"D8V","3R6"},
{"J18","S19"},
{"PVQ","WL2"},
{"ZPV","QFW"},
{"719","CSV"},
{"XK9","9Q9"},
{"BM5","L5V"},
{"LDF","WZT"},
{"MSP","DTZ"},
{"HRQ","JBG"},
{"19C","GSP"},
{"GPB","HGX"},
{"2F4","8HL"},
{"886","C8J"},
{"ZF3","LM9"},
{"NQ1","394"},
{"WM9","M79"},
{"PM4","GNT"},
{"6J4","ML2"},
{"5WT","HQS"},
{"KQD","5K4"},
{"JBT","V1Q"},
{"JVS","DDT"},
{"3G2","52L"},
{"8ZF","D6R"},
{"4BQ","5H6"},
{"G7T","7T6"},
{"ZY3","83H"},
{"HYC","G9C"},
{"MX6","XC9"},
{"2NW","2SH"},
{"YXJ","JSR"},
{"QNH","YJN"},
{"TG3","886"},
{"N7Z","G98"},
{"5D7","KNW"},
{"8TN","KH3"},
{"C78","TSW"},
{"87Z","DFM"},
{"QGG","Q53"},
{"NRN","YP7"},
{"TTB","C2T"},
{"ZLY","25P"},
{"7KS","D5X"},
{"LNX","CNJ"},
{"QVK","YMK"},
{"CNN","N43"},
{"5Q9","MWG"},
{"SCC","XFV"},
{"885","G7T"},
{"4BS","4BQ"},
{"N4Q","Z6X"},
{"FQX","7W4"},
{"MLL","NF8"},
{"52N","PZ2"},
{"DNF","KBC"},
{"6C2","CCS"},
{"LZ8","P1B"},
{"CSV","686"},
{"PZ2","KKC"},
{"JMR","327"},
{"3TP","N6L"},
{"3W8","YFG"},
{"S62","J5V"},
{"FF3","VXL"},
{"4X4","MHQ"},
{"3TP","7Z7"},
{"L83","VDN"},
{"Q8D","2HB"},
{"JB4","5LR"},
{"VYT","SAN"},
{"L54","X63"},
{"15J","XF2"},
{"FWZ","WLR"},
{"R44","K5M"},
{"TK6","Q5J"},
{"J81","QP5"},
{"114","BGP"},
{"QQ3","PJ7"},
{"D5F","HNN"},
{"MFF","WW8"},
{"J18","MP3"},
{"9JN","M8G"},
{"2YC","CSL"},
{"R2T","4TS"},
{"ZBT","WQ8"},
{"XFV","MPD"},
{"R9S","XDW"},
{"8HL","99X"},
{"4MG","2QF"},
{"8X5","BMK"},
{"CN7","KSB"},
{"YJN","44Y"},
{"X11","WWY"},
{"5MP","VDX"},
{"R2L","PFY"},
{"6ZP","HPW"},
{"WGM","GPB"},
{"WCZ","KCY"},
{"NYR","TKN"},
{"1L3","SKC"},
{"MND","S5K"},
{"17N","2D1"},
{"VL7","16Q"},
{"5FP","J5J"},
{"NBL","TLF"},
{"QDV","Z9Z"},
{"2S1","VXW"},
{"K22","G6R"},
{"DTL","9Z8"},
{"BXN","YXJ"},
{"VYW","LNX"},
{"WJ4","4LM"},
{"JTX","DPL"},
{"SLM","DNF"},
{"YM4","J37"},
{"4L5","BF4"},
{"2RT","8DD"},
{"FNB","KD8"},
{"PK8","9PD"},
{"RLR","4SY"},
{"TM2","661"},
{"PQ6","2FF"},
{"92J","XMC"},
{"GDM","21R"},
{"ZTG","VV5"},
{"X3B","ZZW"},
{"5XQ","H6J"},
{"WTL","W1N"},
{"PNM","H8Z"},
{"6MY","CG5"},
{"72V","RLR"},
{"3R6","WCZ"},
{"PF8","YRM"},
{"HPY","88T"},
{"X8P","MHN"},
{"7LY","6VJ"},
{"2FF","C9G"},
{"K4Q","4BS"},
{"X63","2WD"},
{"XM8","R8Q"},
{"G98","Z3X"},
{"44B","8DJ"},
{"PWZ","V1P"},
{"MDD","7ZX"},
{"RRD","T49"},
{"YBJ","DBX"},
{"GXQ","BXP"},
{"6FX","88P"},
{"WXZ","H22"},
{"18F","WTL"},
{"NQF","885"},
{"L4T","XM2"},
{"V82","4DY"},
{"6N6","TDX"},
{"172","QRK"},
{"N6L","23T"},
{"CSP","5MP"},
{"GLG","9TQ"},
{"9P6","R76"},
{"W1N","N3F"},
{"R8G","JZ1"},
{"H2L","F2D"},
{"TGT","C9S"},
{"7BS","2XQ"},
{"FWH","TVM"},
{"23T","K3L"},
{"WQX","37M"},
{"3ZW","QH7"},
{"BGP","FW6"},
{"YFC","FGH"},
{"JCF","94D"},
{"WRQ","9JN"},
{"GN5","6RM"},
{"V6H","QGG"},
{"C1S","XK9"},
{"FFY","9SF"},
{"WPX","HKT"},
{"7Y1","NBL"},
{"6RN","GPD"},
{"NYJ","YDT"},
{"934","FKL"},
{"P3N","FXS"},
{"ZQS","KXC"},
{"4KW","PVJ"},
{"FMS","V26"},
{"NT8","WM9"},
{"7Z7","G4J"},
{"NN9","2TT"},
{"VXW","DJB"},
{"C97","Q3Q"},
{"VVQ","486"},
{"CB6","DGN"},
{"DGQ","WMN"},
{"FM5","GJF"},
{"6YY","DPN"},
{"DDT","814"},
{"KF3","SFQ"},
{"G7S","TTB"},
{"R4C","S12"},
{"R8Q","35Y"},
{"GXN","JKH"},
{"J2H","K22"},
{"F5B","7LY"},
{"NCK","YSR"},
{"SMP","KY2"},
{"P4X","X3B"},
{"DR5","LZ8"},
{"8JQ","ZPV"},
{"WG9","SX3"},
{"NDQ","LM2"},
{"32S","LFV"},
{"K51","ND4"},
{"DP3","QDV"},
{"2W7","CCT"},
{"RSK","YH6"},
{"9NZ","NSB"},
{"K3L","RV3"},
{"HN8","414"},
{"92N","75S"},
{"61M","598"},
{"ZR6","53T"},
{"J8F","TB2"},
{"H22","5YX"},
{"HSJ","M63"},
{"4KW","5GB"},
{"HR7","89C"},
{"FQP","15J"},
{"TZ5","LYS"},
{"5FP","WG4"},
{"4HL","PBL"},
{"C8J","D1C"},
{"TS3","83C"},
{"C3G","1QT"},
{"GZD","DNK"},
{"2RB","KSF"},
{"BCD","SF9"},
{"327","9QZ"},
{"4FF","ZQS"},
{"6L9","82F"},
{"TJK","123"},
{"X9M","FMY"},
{"R92","TV1"},
{"CDL","2PW"},
{"7ZX","58Y"},
{"C2N","H5T"},
{"8MN","TH2"},
{"GN7","G44"},
{"HKL","61M"},
{"XD6","1C9"},
{"ZCS","NQ8"},
{"2L8","QGH"},
{"DFC","XX7"},
{"S5K","XM8"},
{"58J","8L9"},
{"PRR","4KM"},
{"6XT","N2T"},
{"FM2","7Y1"},
{"V26","HR7"},
{"2TT","91P"},
{"88F","ZW1"},
{"JBG","891"},
{"WZT","VZQ"},
{"PYG","NHS"},
{"2QT","P9H"},
{"FB2","9QT"},
{"MP3","PQ6"},
{"WZV","YBJ"},
{"H53","VYW"},
{"N2T","VQW"},
{"ZK2","6RT"},
{"SQS","5XQ"},
{"DPN","W8H"},
{"TSW","2L8"},
{"73H","R7Q"},
{"F1Z","B9Q"},
{"M8G","9KS"},
{"NSB","H41"},
{"WBJ","THR"},
{"KSF","KGS"},
{"PXH","3BS"},
{"4NT","ZRV"},
{"VNZ","8X5"},
{"98S","DR1"},
{"3XY","TJK"},
{"JNX","P9Z"},
{"F4P","6YY"},
{"VRT","VKV"},
{"TVM","92N"},
{"WLR","S62"},
{"D5X","ZVB"},
{"152","9P6"},
{"F2D","PN3"},
{"2R2","D6K"},
{"ZRV","2NX"},
{"67X","TS3"},
{"HWP","YBD"},
{"5FC","SRV"},
{"X92","CQR"},
{"8N9","DFC"},
{"Q5J","H8N"},
{"GGG","8LK"},
{"PPQ","841"},
{"6RT","WJ8"},
{"KQR","788"},
{"92N","Q62"},
{"W7S","98S"},
{"S19","NFK"},
{"VRM","ZVY"},
{"GL8","DCH"},
{"4YM","17N"},
{"F13","D3J"},
{"QVC","VGG"},
{"31S","J81"},
{"934","93X"},
{"Q21","R4C"},
{"TH2","HQ4"},
{"1C9","114"},
{"83N","X5B"},
{"S3L","T4L"},
{"SD2","ZWX"},
{"SC1","6K1"},
{"TXD","ZPF"},
{"3GY","NQ1"},
{"Z9M","9NS"},
{"D6R","7V5"},
{"WG4","C2N"},
{"SVH","JBT"},
{"TR8","K4V"},
{"MPD","7SR"},
{"Y36","DP3"},
{"LM2","K21"},
{"KD1","2S1"},
{"FC8","J3M"},
{"JFD","BWF"},
{"6Y3","88F"},
{"STT","GXN"},
{"KKC","DW9"},
{"52L","B3G"},
{"5BK","XWX"},
{"H6X","5BQ"},
{"YH6","FGK"},
{"VM3","6RN"},
{"BWH","1PZ"},
{"JK2","BCD"},
{"9QT","LTX"},
{"6WK","F5B"},
{"HYC","C97"},
{"GSP","3MR"},
{"6M3","B9P"},
{"7LD","9NZ"},
{"N31","7KS"},
{"GGG","9PB"},
{"6RM","SC1"},
{"83C","TGT"},
{"BWT","1TJ"},
{"7YH","CN7"},
{"JLD","PFT"},
{"W95","JNX"},
{"ZBT","Y2F"},
{"TPD","RSK"},
{"3BS","BR6"},
{"KG9","X9M"},
{"6HL","5D3"},
{"WMN","P9S"},
{"V32","V6H"},
{"RYJ","3HM"},
{"SF9","SBK"},
{"HQ4","19C"},
{"BWF","2W7"},
{"2LC","91R"},
{"VCD","3G2"},
{"VKJ","9BJ"},
{"NL2","VKJ"},
{"NLF","HY7"},
{"BR6","L6V"},
{"TQ4","8N9"},
{"QH7","W84"},
{"D6K","GGG"},
{"W1J","SLM"},
{"DB2","RQS"},
{"M18","RRD"},
{"DXS","32S"},
{"KL8","YRT"},
{"Q5W","VD4"},
{"SCC","WQX"},
{"GQW","VRT"},
{"52N","J47"},
{"Z9M","6FX"},
{"FKX","GSK"},
{"TKX","WRS"},
{"7YH","NFG"},
{"9Y6","WZV"},
{"7BS","48W"},
{"NT5","KSX"},
{"1Y8","RYV"},
{"814","J2F"},
{"GSK","KRQ"},
{"FBC","W1J"},
{"C9G","VRY"},
{"V2F","8TN"},
{"5M4","Y9S"},
{"X9Q","T71"},
{"Q7G","9HB"},
{"YLR","4YM"},
{"18L","29D"},
{"M1M","1BT"},
{"82F","MX3"},
{"9BJ","BBL"},
{"R55","HRQ"},
{"9RH","R5S"},
{"414","MHV"},
{"ML2","Y8T"},
{"179","7YH"},
{"GK3","5Q9"},
{"7CZ","VRM"},
{"QP3","LDF"},
{"YRM","D92"},
{"KXC","B8Y"},
{"2ZB","6X1"},
{"XWX","JCF"},
{"B3G","CG7"},
{"LHT","4NT"},
{"NNN","5LW"},
{"48W","R9S"},
{"91R","6J4"},
{"97T","BBF"},
{"1BT","KWW"},
{"B53","QL9"},
{"HBC","DB2"},
{"2D1","89S"},
{"BBL","WBG"},
{"7WK","LJP"},
{"TV1","SNJ"},
{"K5Q","L9Q"},
{"HNN","YKD"},
{"BXP","W81"},
{"64N","GLG"},
{"L9Q","M4Y"},
{"PTB","8JP"},
{"RHP","3FJ"},
{"657","PWZ"},
{"HZ7","T8S"},
{"YKD","W25"},
{"PYL","SMP"},
{"YSQ","HSJ"},
{"W84","9F8"},
{"HQS","NL2"},
{"3MC","6Y3"},
{"24K","MDD"},
{"G3D","B17"},
{"2QF","PXH"},
{"38D","FNB"},
{"614","SVH"},
{"34H","BWT"},
{"6L3","GZD"},
{"J1Y","QJ9"},
{"3XF","GG9"},
{"MHQ","25V"},
{"3PQ","L4T"},
{"57T","3W4"},
{"8KQ","614"},
{"PC9","P5K"},
{"C2Q","F4P"},
{"J37","FW2"},
{"TDC","M1F"},
{"YD4","LZV"},
{"4H5","HYC"},
{"VRY","5XG"},
{"3W4","YLR"},
{"JZ1","Q21"},
{"SBK","1XQ"},
{"RVK","6XT"},
{"9NS","LVG"},
{"JBT","612"},
{"J4R","QWT"},
{"YDT","31V"},
{"123","C78"},
{"PN3","PTM"},
{"6QM","5GN"},
{"CG7","PF8"},
{"HX4","T4H"},
{"6CK","HXR"},
{"PFT","H53"},
{"62W","FC8"},
{"KQ6","4X5"},
{"3CK","8Z5"},
{"RHS","Q7G"},
{"N13","2LT"},
{"D3J","NYJ"},
{"PFY","N44"},
{"N3F","4FF"},
{"P89","29Z"},
{"MHN","J49"},
{"S78","LCK"},
{"8DD","DR5"},
{"51H","VM3"},
{"1NF","MLL"},
{"S99","RKK"},
{"9PD","JLD"},
{"7Q5","7WK"},
{"7WK","MND"},
{"CQR","KG9"},
{"X5B","VTN"},
{"SCW","RPP"},
{"BF4","3XF"},
{"QL9","R8G"},
{"LDB","4X4"},
{"VDN","73Z"},
{"9KY","BXN"},
{"VTN","WJ1"},
{"8F4","PR2"},
{"F78","92J"},
{"7SX","GQW"},
{"GR7","22P"},
{"56B","7SX"},
{"876","HPY"},
{"HNP","V7Y"},
{"SNJ","HHH"},
{"KNR","W7S"},
{"HT2","T9W"},
{"PC2","B9Y"},
{"6VJ","HNP"},
{"4TS","32D"},
{"7FB","TZ5"},
{"5BQ","PRT"},
{"PRT","97T"},
{"G44","9DX"},
{"THR","81Z"},
{"25P","MCD"},
{"Z9L","R92"},
{"V1P","L1D"},
{"DSZ","TVC"},
{"VKV","TQ4"},
{"4LM","YM4"},
{"T8S","6N6"},
{"HPP","WV4"},
{"99X","8YW"},
{"B9P","HDV"},
{"T2Q","TNM"},
{"JVG","7XG"},
{"QGH","KTD"},
{"DBX","VNZ"},
{"DFM","RSW"},
{"29D","GYC"},
{"LYS","38D"},
{"MKK","WXZ"},
{"5B5","MQ5"},
{"BPX","2NW"},
{"5LR","PYY"},
{"VXL","6HL"},
{"", ""}};
|
TierynnB/LeaguePyBot | LPBv2/controller/actions/combat.py | <reponame>TierynnB/LeaguePyBot
from . import Action
class Combat(Action):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def attack_move(self, x: int, y: int):
self.keyboard.press(self.hotkeys.attack_move)
self.mouse.set_position_and_left_click(x, y)
self.keyboard.release(self.hotkeys.attack_move)
async def cast_spell(self, key, x: int, y: int):
self.mouse.set_position(x, y)
self.keyboard.input_key(key)
async def cast_spells(self, x: int, y: int, ultimate=False):
await self.cast_spell(self.hotkeys.first_ability, x, y)
await self.cast_spell(self.hotkeys.second_ability, x, y)
await self.cast_spell(self.hotkeys.third_ability, x, y)
if ultimate:
await self.cast_spell(self.hotkeys.ultimate_ability, x, y)
async def attack(self, x: int, y: int):
await self.attack_move(x, y)
async def attack_target(self, unit_type, localizer_function):
pos = await localizer_function(unit_type)
if pos:
await self.attack_move(*pos)
|
alpavlenko/EvoGuess | tools/check_cnf.py | <filename>tools/check_cnf.py
import json
from concurrent.futures.process import ProcessPoolExecutor
from instance import Instance
from function.module.solver import solvers
MAX_WORKERS = 36
SOLVERS = ['g3', 'g4', 'cd']
INSTANCES = {
'sgen_150_100': 'sgen/sgen6_900_100.cnf',
'sgen_150_200': 'sgen/sgen6_900_200.cnf',
'sgen_150_300': 'sgen/sgen6_900_300.cnf',
'sgen_150_1001': 'sgen/sgen6_900_1001.cnf',
}
def worker_func(data):
instance_key, solver_key = data
clauses = Instance({
'slug': 'instance',
'cnf': {
'slug': 'cnf',
'path': INSTANCES[instance_key]
},
'input_set': None
}).clauses()
solver = solvers.get(f'solver:pysat:{solver_key}')()
status, statistic, _ = solver.solve(clauses, [])
return {
'solver': solver_key,
'instance': instance_key,
'status': status,
'statistic': statistic,
}
if __name__ == '__main__':
cases = [
(i_key, s_key)
for s_key in SOLVERS
for i_key in INSTANCES.keys()
]
workers = min(MAX_WORKERS, len(cases))
print(f'{workers} workers for {len(cases)} cases')
if workers == 1:
task_map = map
else:
executor = ProcessPoolExecutor(max_workers=workers)
task_map = executor.map
all_results = []
for result in task_map(worker_func, cases):
all_results.append(result)
with open('CNF_RESULTS', 'a+') as handle:
handle.write(f'{json.dumps(result)}\n')
|
orangejulius/donationparty | app/views/api/rounds/show.json.jbuilder | <reponame>orangejulius/donationparty<filename>app/views/api/rounds/show.json.jbuilder<gh_stars>0
json.set! :round do
json.partial! 'api/rounds/round', round: @round
end
json.set! :donations_template, @donations
json.set! :payment_info_template, @payment_info
|
fideoman/geronimo | plugins/myfaces/geronimo-myfaces/src/main/java/org/apache/geronimo/myfaces/info/GeronimoFacesConfigurationMergerFactory.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.myfaces.info;
import javax.faces.context.ExternalContext;
import org.apache.geronimo.myfaces.webapp.MyFacesWebAppContext;
import org.apache.geronimo.web.WebApplicationConstants;
import org.apache.myfaces.config.element.FacesConfigData;
import org.apache.myfaces.spi.FacesConfigurationMerger;
import org.apache.myfaces.spi.FacesConfigurationMergerFactory;
/**
* @version $Rev$ $Date$
*/
public class GeronimoFacesConfigurationMergerFactory extends FacesConfigurationMergerFactory {
private FacesConfigurationMerger facesConfigurationMerger;
@Override
public FacesConfigurationMerger getFacesConfigurationMerger(ExternalContext externalContext) {
if (facesConfigurationMerger == null) {
String webModuleName = (String) externalContext.getApplicationMap().get(WebApplicationConstants.WEB_APP_NAME);
final MyFacesWebAppContext myFacesWebAppContext = MyFacesWebAppContext.getMyFacesWebAppContext(webModuleName);
facesConfigurationMerger = new FacesConfigurationMerger() {
@Override
public FacesConfigData getFacesConfigData(ExternalContext arg0) {
return myFacesWebAppContext.getFacesConfigData();
}
};
}
return facesConfigurationMerger;
}
}
|
zubairq/jsql | public/visifile_drivers/controls/radiobutton.js | function(args) {
/*
is_app(true)
component_type("VB")
display_name("Radio button control")
description("This will return the radio button control")
base_component_id("radio_button_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
[
{
id: "text",
name: "Text",
type: "String"
}
,
{
id: "checked",
name: "Checked",
type: "Select",
default: "false",
values: [
{display: "True", value: ""},
{display: "False", value: "false"}
]
}
,
{
id: "background_color",
name: "Background color",
type: "String"
}
,
{
id: "width",
name: "Width",
default: 30,
type: "Number"
}
,
{
id: "height",
name: "Height",
default: 30,
type: "Number"
}
]
)//properties
logo_url("/driver_icons/radio.png")
*/
Vue.component("radio_button_control",{
props: ["args","design_mode"]
,
template: `<div class="radio">
<input v-bind:id='design_mode?"":args.name'
type="radio"
style="width:100%;"
v-model="args.checked"
v-bind:value='args.text'>{{args.text}}<br>
</input>
</div>`
,
data: function() {
return {
msg: "...",
checked: true
}
},
})
}
|
rudecs/ePortal | users/app/controllers/api/v1.rb | class API::V1 < Grape::API
@@Boolean = Virtus::Attribute::Boolean
format :json
formatter :json, Grape::Formatter::Jbuilder
content_type :json, 'application/json'
before do
env['api.tilt.root'] = 'app/views/api/v1'
end
def self.inherited(subclass)
super
helpers do
def authenticate!
error_401! unless session_token.present?
@current_session = Session.find_by_token(session_token)
error_401! unless @current_session.present?
@current_user = @current_session.user
error_403!(state: ['is not active']) unless @current_user.state == 'active'
error_403!(email: ['is not confirmed']) unless @current_user.email_confirmed_at.present?
if @current_user.is_enabled_2fa
unless @current_session.sms_token_confirmed_at.present?
error_403!(sms_token: ['is not confirmed'])
end
end
@current_roles = Role.joins(profiles: :user).where(users: {id: @current_user.id})
@current_clients = Client.joins(:roles).where(roles: {id: @current_roles.pluck(:id)})
end
def current_session
@current_session
end
def current_user
@current_user
end
def current_clients
@current_clients
end
def current_roles
@current_roles
end
def declared_params
declared(params, include_missing: false).merge({})
end
def error_400!()
resp = {
:code => 400,
:message => "bad_request"
}
error!(resp, 400)
end
def error_401!()
resp = {
:code => 401,
:message => 'unauthorized',
:errors => {}
}
error!(resp, 401)
end
def error_403!(errors = {})
content = {
:code => 403,
:message => 'access_denied',
:errors => errors
}
error!(content, 403)
end
def error_404!()
resp = {
:code => 404,
:message => 'not_found',
:errors => []
}
error!(resp, 404)
end
def error_422!(errors = {})
resp = {
:code => 422,
:message => 'unprocessable_entity',
:errors => errors
}
error!(resp, 422)
end
def error_500!(errors = {})
resp = {
:code => 500,
:message => 'internal_server_error',
:errors => errors
}
error!(resp, 500)
end
def session_token
token = request.headers['X-Session-Token']
token = params['session_token'] unless token.present?
token
end
end
subclass.instance_eval do
rescue_from ActiveRecord::RecordNotFound do |e|
content = { :code => 404, :message => 'not_found', errors: {} }
content.merge!(:backtrace => e.backtrace) if !Rails.env.production?
Rack::Response.new(
[content.to_json],
404,
{ 'Content-Type' => 'application/json' }
)
end
end
end
mount API::V1::ClientsResource
mount API::V1::InvitationsResource
mount API::V1::PasswordsResource
mount API::V1::ProfileResource
mount API::V1::RegisterResource
mount API::V1::SessionResource
mount API::V1::UsersResource
end
|
shaojiankui/iOS10-Runtime-Headers | Frameworks/UIKit.framework/_UIWebFindOnPageHighlightBubbleView.h | <filename>Frameworks/UIKit.framework/_UIWebFindOnPageHighlightBubbleView.h
/* Generated by RuntimeBrowser
Image: /System/Library/Frameworks/UIKit.framework/UIKit
*/
@interface _UIWebFindOnPageHighlightBubbleView : UIView {
struct CGImage { } * _highlightedContent;
struct CGPoint {
double x;
double y;
} _highlightedContentOrigin;
}
- (void)dealloc;
- (void)drawRect:(struct CGRect { struct CGPoint { double x_1_1_1; double x_1_1_2; } x1; struct CGSize { double x_2_1_1; double x_2_1_2; } x2; })arg1;
- (void)setHighlightedContent:(struct CGImage { }*)arg1 withOrigin:(struct CGPoint { double x1; double x2; })arg2;
@end
|
jamie1192/Warmind-for-Destiny-2 | app/src/main/java/com/jastley/exodusnetwork/repositories/OnBoardingRepository.java | package com.jastley.exodusnetwork.repositories;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.google.gson.Gson;
import com.jastley.exodusnetwork.api.BungieAPI;
import com.jastley.exodusnetwork.app.App;
import com.jastley.exodusnetwork.onboarding.DownloadProgressModel;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
@Singleton
public class OnBoardingRepository {
CompositeDisposable compositeDisposable = new CompositeDisposable();
private MutableLiveData<DownloadProgressModel> downloadProgressModel = new MutableLiveData<>();
@Inject
@Named("bungieRetrofit")
Retrofit retrofit;
@Inject
Gson gson;
@Inject
@Named("savedManifest")
SharedPreferences sharedPreferences;
@Inject
Context context;
@Inject
public OnBoardingRepository() {
App.getApp().getAppComponent().inject(this);
}
public LiveData<DownloadProgressModel> getDownloadProgressModel() {
return downloadProgressModel;
}
public void checkManifestVersion(){
Disposable disposable = retrofit.create(BungieAPI.class).getBungieManifests()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(response_getBungieManifest -> {
if(!response_getBungieManifest.getErrorCode().equals("1")){
downloadProgressModel.postValue(new DownloadProgressModel(response_getBungieManifest.getMessage()));
}
else {
String manifestVersion = response_getBungieManifest.getResponse().getMobileWorldContentPaths().getEnglishPath();
String savedManifestVersion = sharedPreferences.getString("manifestVersion", "");
//Download/update stored manifests
if (!manifestVersion.equals(savedManifestVersion)) {
SharedPreferences.Editor editor = sharedPreferences.edit();
try {
editor.putString("manifestVersion", manifestVersion);
editor.apply();
} catch (Exception e) {
Log.e("MANIFEST_PREFS_ERR", e.getLocalizedMessage());
}
// splashText.setText(R.string.gettingItemDatabase);
String contentUrl = response_getBungieManifest.getResponse().getMobileWorldContentPaths().getEnglishPath();
getUpdateManifests(contentUrl);
} else { //already have the latest manifest
downloadProgressModel.postValue(new DownloadProgressModel(true));
}
}
}, throwable -> downloadProgressModel.postValue(new DownloadProgressModel(throwable)));
compositeDisposable.add(disposable);
}
private void getUpdateManifests(String url){
Disposable disposable = retrofit.create(BungieAPI.class).downloadUrlContent(url)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(responseBody -> {
try {
//dynamically retrieve the /data/databases path for the device, database filename here is irrelevant
String databasePath = context.getDatabasePath("bungieAccount.db").getParent();
File manifestFile = new File(databasePath, "manifest.zip");
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = responseBody.contentLength();
long fileSizeDownloaded = 0;
inputStream = responseBody.byteStream();
outputStream = new FileOutputStream(manifestFile);
boolean downloading = true;
while (downloading) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
DecimalFormat df = new DecimalFormat("###");
df.setRoundingMode(RoundingMode.CEILING);
int downloaded = Integer.parseInt(df.format(fileSizeDownloaded));
int size = Integer.parseInt(df.format(fileSize));
downloadProgressModel.postValue(new DownloadProgressModel(downloaded, size, "Downloading manifest..."));
Log.d("Manifest Download", fileSizeDownloaded + " of " + fileSize);
outputStream.flush();
}
} catch (IOException e) {
Log.d("Content download: ", e.getLocalizedMessage());
downloadProgressModel.postValue(new DownloadProgressModel(e.getCause()));
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
unzipManifest(databasePath);
}
}
catch(IOException e){
Log.d("OUTER_CATCH", e.getLocalizedMessage());
}
}, throwable -> {
Log.e("GET_UPDATE_MANIFESTS_ER", throwable.getLocalizedMessage());
});
compositeDisposable.add(disposable);
}
private void unzipManifest(String path){
downloadProgressModel.postValue(new DownloadProgressModel(100,100, "Extracting manifest data..."));
InputStream is;
ZipInputStream zis;
try
{
String zipname = "manifest.zip";
String filename;
File bungieDB = new File(path, "bungieManifest.db");
is = new FileInputStream(path +"/"+ zipname);
zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null)
{
filename = ze.getName();
// Create directory if it doesn't exist
if (ze.isDirectory()) {
File fmd = new File(path + filename);
fmd.mkdirs();
continue;
}
FileOutputStream fout = new FileOutputStream(bungieDB);
while ((count = zis.read(buffer)) != -1)
{
fout.write(buffer, 0, count);
}
fout.close();
zis.closeEntry();
}
zis.close();
}
catch(IOException e)
{
e.printStackTrace();
downloadProgressModel.postValue(new DownloadProgressModel(e.getCause()));
}
finally {
downloadProgressModel.postValue(new DownloadProgressModel(true));
}
}
public void dispose() {
compositeDisposable.dispose();
}
}
|
cupcake/setdb | key_buffer.go | <gh_stars>10-100
package main
import (
"bytes"
"encoding/binary"
)
const keyPrefixSize = 5
// KeyBuffer is a reusable key for LevelDB
type KeyBuffer struct {
buf []byte
keyLen int
reverseKey bool
}
// Create a new key of type t with key and room for extra bytes.
func NewKeyBuffer(t byte, key []byte, extra int) *KeyBuffer {
k := &KeyBuffer{make([]byte, keyPrefixSize, keyPrefixSize+len(key)+extra), len(key), false}
k.buf[0] = t
k.SetKey(key)
return k
}
func NewKeyBufferWithSuffix(t byte, key []byte, suffix []byte) *KeyBuffer {
k := &KeyBuffer{make([]byte, keyPrefixSize, keyPrefixSize+len(key)+len(suffix)), len(key), false}
k.buf[0] = t
k.SetKey(key)
k.SetSuffix(suffix)
return k
}
func (b *KeyBuffer) SetKey(key []byte) {
if len(key) == 0 {
return
}
b.keyLen = len(key)
binary.BigEndian.PutUint32(b.buf[1:], uint32(len(key)))
b.buf = append(b.buf[:keyPrefixSize], key...)
}
// Add extra after the key, will overwrite any existing extra
func (b *KeyBuffer) SetSuffix(s []byte) {
b.buf = append(b.buf[:keyPrefixSize+b.keyLen], s...)
}
// Return a slice of size n suitable for using with an io.Reader
// The read bytes will overwrite the first n bytes of suffix (if they exist)
func (b *KeyBuffer) SuffixForRead(n int) []byte {
start := keyPrefixSize + b.keyLen
if len(b.buf) < start+n {
b.buf = append(b.buf[:start], make([]byte, n)...) // resize the slice to be large enough
}
return b.buf[start : start+n]
}
// Check if k starts with the key (without the suffix)
func (b *KeyBuffer) IsPrefixOf(k []byte) bool {
keyLen := keyPrefixSize + b.keyLen
// the last byte is 0xff, so truncate a byte early
if b.reverseKey {
keyLen--
}
if len(k) > keyLen && bytes.Equal(b.buf[:keyLen], k[:keyLen]) {
return true
}
return false
}
// Change the key so that it sorts to come after the last prefix key
//
// To get a key that will sort *after* given prefix, we increment the last
// byte that is not 0xff and truncated after the byte that was incremented
func (b *KeyBuffer) ReverseIterKey() {
b.reverseKey = true
for i := len(b.buf) - 1; i >= 0; i-- {
if b.buf[i] == 0xff {
continue
}
b.buf[i] += 1
b.buf = b.buf[:i+1]
break
}
}
func (b *KeyBuffer) Type() byte {
return b.buf[0]
}
func (b *KeyBuffer) Key() []byte {
return b.buf
}
|
osgvsun/lubanlou | lubanlou-master/lubanlou-common/src/main/java/net/gvsun/datashare/external/shareddata/SchoolRoomDTO.java | <filename>lubanlou-master/lubanlou-common/src/main/java/net/gvsun/datashare/external/shareddata/SchoolRoomDTO.java
package net.gvsun.datashare.external.shareddata;
import net.gvsun.common.Recordable;
public class SchoolRoomDTO extends Recordable implements Shared {
private String roomNumber;
private String roomNo;
private String roomName;
private String buildNumber;
private Integer floorNo;
public String getRoomNumber() {
return roomNumber;
}
public void setRoomNumber(String roomNumber) {
this.roomNumber = roomNumber;
}
public String getRoomName() {
return roomName;
}
public void setRoomName(String roomName) {
this.roomName = roomName;
}
public String getBuildNumber() {
return buildNumber;
}
public void setBuildNumber(String buildNumber) {
this.buildNumber = buildNumber;
}
public Integer getFloorNo() {
return floorNo;
}
public void setFloorNo(Integer floorNo) {
this.floorNo = floorNo;
}
public String getRoomNo() {
return roomNo;
}
public void setRoomNo(String roomNo) {
this.roomNo = roomNo;
}
}
|
Kanapriya/wso2-shindig-1 | features/src/main/javascript/features/container/service.js | /*
* 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.
*/
/**
* @fileoverview This represents the service layer that talks to OSAPI
* endpoints. All RPC requests should go into this class.
*/
/**
* @param {osapi.container.Container} The container that this service services.
* @constructor
*/
osapi.container.Service = function(container) {
/**
* The container that this service services.
* @type {osapi.container.Container}
* @private
*/
this.container_ = container;
var config = this.config_ = container.config_ || {};
var injectedEndpoint = ((gadgets.config.get('osapi') || {}).endPoints ||
[window.__API_URI.getOrigin() + '/rpc'])[0];
var matches = /^([^\/]*\/\/[^\/]+)(.*)$/.exec(injectedEndpoint);
/**
* @type {string}
* @private
*/
this.apiHost_ = String(osapi.container.util.getSafeJsonValue(config,
osapi.container.ServiceConfig.API_HOST, matches[1]));
/**
* @type {string}
* @private
*/
this.apiPath_ = String(osapi.container.util.getSafeJsonValue(config,
osapi.container.ServiceConfig.API_PATH, matches[2]));
/**
* Map of gadget URLs to cached gadgetInfo response.
* @type {Object}
* @private
*/
this.cachedMetadatas_ = {};
/**
* Map of gadget URLs to cached tokenInfo response.
* @type {Object}
* @private
*/
this.cachedTokens_ = {};
/**
* @see osapi.container.Container.prototype.getLanguage
*/
if (config.GET_LANGUAGE) {
this.getLanguage = config.GET_LANGUAGE;
}
/**
* @see osapi.container.Container.prototype.getCountry
*/
if (config.GET_COUNTRY) {
this.getCountry = config.GET_COUNTRY;
}
this.registerOsapiServices();
this.onConstructed(config);
};
/**
* Callback that occurs after instantiation/construction of this. Override to
* provide your specific functionalities.
* @param {Object=} opt_config Configuration JSON.
*/
osapi.container.Service.prototype.onConstructed = function(opt_config) {};
/**
* Return a possibly-cached gadgets metadata for gadgets in request.ids, for
* container request.container. If metadata is not cache, fetch from server
* only for the uncached gadget URLs. The optional callback opt_callback will be
* called, after a response is received.
* @param {Object} request JSON object representing the request.
* @param {function(Object)=} opt_callback function to call upon data receive.
*/
osapi.container.Service.prototype.getGadgetMetadata = function(request, opt_callback) {
// TODO: come up with an expiration mechanism to evict cached gadgets.
// Can be based on renderParam['nocache']. Be careful with preloaded and
// arbitrarily-navigated gadgets. The former should be indefinite, unless
// unloaded. The later can done without user knowing.
var callback = opt_callback || function() {};
var uncachedUrls = osapi.container.util.toArrayOfJsonKeys(
this.getUncachedDataByRequest_(this.cachedMetadatas_, request));
var finalResponse = this.getCachedDataByRequest_(this.cachedMetadatas_, request);
// If fully cached, return from cache.
if (uncachedUrls.length == 0) {
callback(finalResponse);
// Otherwise, request for uncached metadatas.
} else {
var self = this;
request['ids'] = uncachedUrls;
request['language'] = this.getLanguage();
request['country'] = this.getCountry();
this.updateContainerSecurityToken(function(error) {
if (error) {
for (var i = 0; i < request['ids'].length; i++) {
var id = request['ids'][i];
finalResponse[id] = { 'error' : error };
}
callback(finalResponse);
} else {
osapi['gadgets']['metadata'](request).execute(function(response) {
// If response entirely fails, augment individual errors.
if (response['error']) {
for (var i = 0; i < request['ids'].length; i++) {
var id = request['ids'][i];
finalResponse[id] = { 'error' : response['error'] };
}
// Otherwise, cache response. Augment final response with server response.
} else {
var currentTimeMs = osapi.container.util.getCurrentTimeMs();
for (var id in response) {
var resp = response[id];
self.updateResponse_(resp, id, currentTimeMs);
self.cachedMetadatas_[id] = resp;
finalResponse[id] = resp;
}
}
callback(finalResponse);
});
}
});
}
};
/**
* Add preloaded gadgets to cache
* @param {Object} response hash of gadgets metadata.
* @param {Object} refTime time to override responseTime (in order to support external caching).
*/
osapi.container.Service.prototype.addGadgetMetadatas = function(response, refTime) {
this.addToCache_(response, refTime, this.cachedMetadatas_);
};
/**
* Add preloaded tokens to cache
* @param {Object} response hash of gadgets metadata.
* @param {Object} refTime data time to override responseTime
* (in order to support external caching).
*/
osapi.container.Service.prototype.addGadgetTokens = function(response, refTime) {
this.addToCache_(response, refTime, this.cachedTokens_);
};
/**
* Utility function to add data to cache
* @param {Object} response hash of gadgets metadata.
* @param {Object} refTime data time to override responseTime (in order to support external caching).
* @param {Object} cache the cache to update.
* @private
*/
osapi.container.Service.prototype.addToCache_ = function(response, refTime, cache) {
var currentTimeMs = osapi.container.util.getCurrentTimeMs();
for (var id in response) {
var resp = response[id];
this.updateResponse_(resp, id, currentTimeMs, refTime);
cache[id] = resp;
}
};
/**
* Update gadget data, set gadget id and calculate expiration time
* @param {Object} resp gadget metadata item.
* @param {string} id gadget id.
* @param {Object} currentTimeMs current time.
* @param {Object} opt_refTime data time to override responseTime (support external caching).
* @private
*/
osapi.container.Service.prototype.updateResponse_ = function(
resp, id, currentTimeMs, opt_refTime) {
resp[osapi.container.MetadataParam.URL] = id;
// This ignores time to fetch metadata. Okay, expect to be < 2s.
resp[osapi.container.MetadataParam.LOCAL_EXPIRE_TIME] =
resp[osapi.container.MetadataResponse.EXPIRE_TIME_MS] -
(opt_refTime == null ?
resp[osapi.container.MetadataResponse.RESPONSE_TIME_MS] : opt_refTime) +
currentTimeMs;
};
/**
* @param {Object} request JSON object representing the request.
* @param {function(Object)=} opt_callback function to call upon data receive.
*/
osapi.container.Service.prototype.getGadgetToken = function(request, opt_callback) {
var callback = opt_callback || function() {};
// Do not check against cache. Always do a server fetch.
var self = this;
var tokenResponseCallback = function(response) {
var finalResponse = {};
// If response entirely fails, augment individual errors.
if (response['error']) {
for (var i = 0; i < request['ids'].length; i++) {
finalResponse[request['ids'][i]] = { 'error' : response['error'] };
}
// Otherwise, cache response. Augment final response with server response.
} else {
for (var id in response) {
var mid = response[id][osapi.container.TokenResponse.MODULE_ID],
url = osapi.container.util.buildTokenRequestUrl(id, mid);
//response[id]['url'] = id; // make sure url is set
self.cachedTokens_[url] = response[id];
finalResponse[id] = response[id];
}
}
callback(finalResponse);
};
// If we have a custom token fetch function, call it -- otherwise use the default
self.updateContainerSecurityToken(function(error) {
if (error) {
tokenResponseCallback({'error': error});
} else {
if (self.config_[osapi.container.ContainerConfig.GET_GADGET_TOKEN]) {
self.config_[osapi.container.ContainerConfig.GET_GADGET_TOKEN](request, tokenResponseCallback);
} else {
osapi['gadgets']['token'](request).execute(tokenResponseCallback);
}
}
});
};
/**
* @param {string} url gadget URL to use as key to get cached metadata.
* @return {string} the gadgetInfo referenced by this URL.
*/
osapi.container.Service.prototype.getCachedGadgetMetadata = function(url) {
return this.cachedMetadatas_[url];
};
/**
* @param {string} url gadget URL to use as key to get cached token.
* @return {string} the tokenInfo referenced by this URL.
*/
osapi.container.Service.prototype.getCachedGadgetToken = function(url) {
return this.cachedTokens_[url];
};
/**
* @param {Object} urls JSON containing gadget URLs to avoid removing.
*/
osapi.container.Service.prototype.uncacheStaleGadgetMetadataExcept =
function(urls) {
for (var url in this.cachedMetadatas_) {
if (typeof urls[url] === 'undefined') {
var gadgetInfo = this.cachedMetadatas_[url];
if (gadgetInfo[osapi.container.MetadataParam.LOCAL_EXPIRE_TIME] <
osapi.container.util.getCurrentTimeMs()) {
delete this.cachedMetadatas_[url];
}
}
}
};
/**
* Initialize OSAPI endpoint methods/interfaces.
*/
osapi.container.Service.prototype.registerOsapiServices = function() {
var endPoint = this.apiHost_ + this.apiPath_;
var osapiServicesConfig = {};
osapiServicesConfig['gadgets.rpc'] = ['container.listMethods'];
osapiServicesConfig[endPoint] = [
'gadgets.metadata',
'gadgets.token'
];
gadgets.config.init({
'osapi': { 'endPoints': [endPoint] },
'osapi.services': osapiServicesConfig
});
};
/**
* Get cached data by ids listed in request.
* @param {Object} cache JSON containing cached data.
* @param {Object} request containing ids.
* @return {Object} JSON containing requested and cached entries.
* @private
*/
osapi.container.Service.prototype.getCachedDataByRequest_ = function(
cache, request) {
return this.filterCachedDataByRequest_(cache, request,
function(data) { return (typeof data !== 'undefined') });
};
/**
* Get uncached data by ids listed in request.
* @param {Object} cache JSON containing cached data.
* @param {Object} request containing ids.
* @return {Object} JSON containing requested and uncached entries.
* @private
*/
osapi.container.Service.prototype.getUncachedDataByRequest_ = function(
cache, request) {
return this.filterCachedDataByRequest_(cache, request,
function(data) { return (typeof data === 'undefined') });
};
/**
* Helper to filter out cached data
* @param {Object} data JSON containing cached data.
* @param {Object} request containing ids.
* @param {Function} filterFunc function to filter result.
* @return {Object} JSON containing requested and filtered entries.
* @private
*/
osapi.container.Service.prototype.filterCachedDataByRequest_ = function(
data, request, filterFunc) {
var result = {};
for (var i = 0; i < request['ids'].length; i++) {
var id = request['ids'][i];
var cachedData = data[id];
if (filterFunc(cachedData)) {
result[id] = cachedData;
}
}
return result;
};
/**
* @return {string} Best-guess locale for current browser.
* @private
*/
osapi.container.Service.prototype.getLocale_ = function() {
var nav = window.navigator;
return nav.userLanguage || nav.systemLanguage || nav.language;
};
/**
* A callback function that will return the correct language locale part to use when
* asking the server to render a gadget or when asking the server for 1 or more
* gadget's metadata.
* <br>
* May be overridden by passing in a config parameter during container construction.
* * @return {string} Language locale part.
*/
osapi.container.Service.prototype.getLanguage = function() {
try {
return this.getLocale_().split('-')[0] || 'ALL';
} catch (e) {
return 'ALL';
}
};
/**
* A callback function that will return the correct country locale part to use when
* asking the server to render a gadget or when asking the server for 1 or more
* gadget's metadata.
* <br>
* May be overridden by passing in a config parameter during container construction.
* @return {string} Country locale part.
*/
osapi.container.Service.prototype.getCountry = function() {
try {
return this.getLocale_().split('-')[1] || 'ALL';
} catch (e) {
return 'ALL';
}
};
/**
* Container Token Refresh
*/
(function() {
var containerTimeout, lastRefresh, fetching,
containerTokenTTL = 1800000 * 0.8, // 30 min default token ttl
callbacks = [];
function runCallbacks(callbacks, error) {
while (callbacks.length) {
callbacks.shift().call(null, error); // Window context
}
}
function refresh(fetch_once) {
var self = this;
if (containerTimeout) {
clearTimeout(containerTimeout);
containerTimeout = 0;
}
var fetch = fetch_once || this.config_[osapi.container.ContainerConfig.GET_CONTAINER_TOKEN];
if (fetch) {
if (!fetching) {
fetching = true;
fetch(function(token, ttl, error) { // token and ttl may be undefined in the case of an error
fetching = false;
// Use last known ttl if there was an error
containerTokenTTL = typeof(ttl) == 'number' ? (ttl * 1000 * 0.8) : containerTokenTTL;
if (containerTokenTTL) {
// Refresh again in 80% of the reported ttl
// Pass null in to closure because FF behaves un-expectedly when that param is not explicitly provided.
containerTimeout = setTimeout(gadgets.util.makeClosure(self, refresh, null), containerTokenTTL);
}
if (token) {
// Looks like everything worked out... let's update the token.
shindig.auth.updateSecurityToken(token);
lastRefresh = osapi.container.util.getCurrentTimeMs();
// And then run all the callbacks waiting for this.
runCallbacks(callbacks);
} else if (error) {
runCallbacks(callbacks, error);
}
});
}
} else {
fetching = false;
// Fail gracefully, container supplied no fetch function. Do not hold on to callbacks.
runCallbacks(callbacks);
}
}
/**
* @see osapi.container.Container.prototype.updateContainerSecurityToken
*/
osapi.container.Service.prototype.updateContainerSecurityToken = function(callback, tokenOrWait, ttl) {
var undef,
now = osapi.container.util.getCurrentTimeMs(),
token = typeof(tokenOrWait) != 'boolean' && tokenOrWait || undef,
wait = typeof(tokenOrWait) == 'boolean' && tokenOrWait,
needsRefresh = containerTokenTTL &&
(fetching || token || !lastRefresh || now > lastRefresh + containerTokenTTL);
if (needsRefresh) {
// Hard expire in 95% of originial ttl.
var expired = !lastRefresh || now > lastRefresh + (containerTokenTTL * 95 / 80);
if (!expired && callback) {
// Token not expired, but needs refresh. Don't block operations that need a valid token.
callback();
} else if (callback) {
// We have a callback, there's either a fetch happening, or we otherwise need to refresh the
// token. Place it in the callbacks queue to be run after the fetch (currently running or
// soon to be launched) completes.
callbacks.push(callback);
}
if (token) {
// We are trying to set a token initially. Run refresh with a fetch_once function that simply
// returns the canned values. Then schedule the refresh using the function in the config
refresh.call(this, function(result) {
result(token, ttl);
});
} else if (!fetching && !wait) {
// There's no fetch going on right now. Unless wait is true, we need to start one right away
// because the token needs a refresh.
// If wait is true, the callback really just wants a valid token. It may be called with an
// error for informational purposes, but it's likely the callback will simply queue up
// immediately if there was an error. To avoid spamming the refresh method, we allow them to
// specify `wait` so that it can wait for success without forcing a fetch.
refresh.call(this);
}
} else if (callback) {
// No refresh needed, run the callback because the token is fine.
callback();
}
};
})(); |
z-zxq-123456/myproject | personalZookeeper/distributedLock/src/main/java/com/flykingmz/zookeeper/dLock/TestSimpleDistributedLock.java | package com.flykingmz.zookeeper.dLock;
import java.util.concurrent.CountDownLatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestSimpleDistributedLock {
private final static Logger logger = LoggerFactory
.getLogger(TestSimpleDistributedLock.class);
private static final int THREAD_NUM = 100;
private static final CountDownLatch threadSemaphore = new CountDownLatch(THREAD_NUM);
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
final DistributedLock dc = new SimpleDistributedLock("host:port","/rootLock");
for(int i=0; i < THREAD_NUM; i++){
new Thread(){
@Override
public void run() {
try{
logger.info("thread start no "+Thread.currentThread().getId());
dc.lock();
dc.unLock();
threadSemaphore.countDown();
} catch (Exception e){
e.printStackTrace();
}
}
}.start();
}
try {
threadSemaphore.await();
dc.release();
logger.info("所有线程运行结束!");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
javaDer/learn-qingyun | learn-goods/src/main/java/com/wwjswly/learn/service/ModuleService.java | package com.wwjswly.learn.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.wwjswly.entity.goods.Module;
/**
* <p>
* 服务类
* </p>
*
* @author zhangzhaofa
* @since 2019-05-15
*/
public interface ModuleService extends IService<Module> {
}
|
alexiynew/nih_framework | neutrino/graphics/shader.hpp | <filename>neutrino/graphics/shader.hpp
#ifndef FRAMEWORK_GRAPHICS_SHADER_HPP
#define FRAMEWORK_GRAPHICS_SHADER_HPP
#include <filesystem>
#include <string>
#include <common/instance_id.hpp>
#include <math/math.hpp>
namespace framework::graphics
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @addtogroup graphics_renderer_module
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Shader.
///
/// Each Shader consists of two parts: vertex program and fragment program.
///
/// TODO: Check if this documentation is correct
/// #### For OpenGL:
///
/// Shader has predefined vertex attribute locations listed below:
/// - position - 0
/// - normal - 1
/// - tangent - 2
/// - color - 3
/// - texture coordinate0-7 - 4-11
///
/// They can be used as follows:
/// @code
/// layout(location = 0) in vec3 vertexPosition;
/// @endcode
///
/// @see Mesh, Renderer
class Shader
{
public:
Shader() = default;
Shader(const Shader& other);
Shader(Shader&& other) noexcept;
~Shader() = default;
Shader& operator=(const Shader& other);
Shader& operator=(Shader&& other) noexcept;
/// @brief Load vertex shader source form file.
///
/// @param filepath Path to vertex shader source file.
///
/// @return `true` if loadint successful.
bool load_vertex_source(const std::filesystem::path& filepath);
/// @brief Set fragment shader source form file.
///
/// @param filepath Path to fragment shader source file.
///
/// @return `true` if loadint successful.
bool load_fragment_source(const std::filesystem::path& filepath);
/// @brief Set vertex shader source.
///
/// @param source Vertex shader source.
void set_vertex_source(const std::string& source);
/// @brief Set fragment shader source.
///
/// @param source Fragment shader source.
void set_fragment_source(const std::string& source);
/// @brief Remove all sources from Shader.
///
/// If Shader loaded to Renderer, it's can be freely cleaned.
///
/// @see Renderer::load.
void clear();
/// @brief Get Shader instance id. Guaranted to be unique.
///
/// @return Shader instance id.
InstanceId instance_id() const;
/// @brief Get vertex shader source.
///
/// @return Vertex shader source.
const std::string& vertex_source() const;
/// @brief Get fragment shader source.
///
/// @return Fragment shader source.
const std::string& fragment_source() const;
private:
friend void swap(Shader& lhs, Shader& rhs) noexcept;
InstanceId m_instance_id;
std::string m_vertex_source;
std::string m_fragment_source;
};
/// @brief Swaps two Shaders.
///
/// @param lhs Shader to swap.
/// @param rhs Shader to swap.
void swap(Shader& lhs, Shader& rhs) noexcept;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace framework::graphics
#endif
|
iaas-splab/saes-prototype | saes-knowledge-base/src/main/java/de/uni_stuttgart/iaas/saes/knowledge_base/domain/Taxonomy.java | /*
* This file is part of the Serverless Application Extraction System (SAES)
*
* The Serverless Application Extraction System is licensed under under
* the Apache License, Version 2.0. Please see the included COPYING file
* for license information.
*/
package de.uni_stuttgart.iaas.saes.knowledge_base.domain;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import de.uni_stuttgart.iaas.saes.common.db.DatabaseStorable;
import de.uni_stuttgart.iaas.saes.common.db.KnowledgeBaseObject;
import de.uni_stuttgart.iaas.saes.common.util.DeserUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.FieldNameConstants;
@Data
@NoArgsConstructor
@AllArgsConstructor
@FieldNameConstants
@DatabaseStorable("taxonomies")
public class Taxonomy implements KnowledgeBaseObject {
private static final DeserUtil DESER = new DeserUtil(Taxonomy.class);
String name;
List<TaxonomyEntry> entries = new ArrayList<>();
@Override
public List<KnowledgeBaseObject> baseDocChildren() {
return List.copyOf(entries);
}
@Override
public Map<String, Object> toBaseDoc() {
return Map.of(//
Fields.name, name, //
Fields.entries, KnowledgeBaseObject.convertList(entries));
}
public static Taxonomy fromBaseDoc(Map<String, Object> baseDoc) {
baseDoc = DESER.ensureList(baseDoc, Fields.entries);
DESER.assertContains(baseDoc, Fields.name);
return new Taxonomy(//
(String) baseDoc.get(Fields.name), //
KnowledgeBaseObject.listFromBaseDoc(baseDoc.get(Fields.entries), TaxonomyEntry::fromBaseDoc));
}
}
|
xpzouying/go-practice | map_vs_sync_map/sync_map/main.go | <reponame>xpzouying/go-practice
package main
import (
"fmt"
"sync"
)
func addWithoutMutex() {
var m sync.Map
var wg sync.WaitGroup
wg.Add(10)
for i := 0; i < 10; i++ {
go func(i int) {
defer wg.Done()
m.Store(i, i)
}(i)
}
wg.Wait()
fn := func(key, value interface{}) bool {
fmt.Printf("key=%d, value=%d\n", key, value)
return true
}
m.Range(fn)
}
func main() {
addWithoutMutex()
}
|
devuxd/Reacher | TutorialExamples/src/edu/cmu/cs/crystal/analysis/npe/simpleflow/NullLatticeElement.java | package edu.cmu.cs.crystal.analysis.npe.simpleflow;
/**
* There are only 4 possibilities for nullness:
* Null: if the value is definitely null.
* Not_null: if the value is definitely not null.
* Maybe_null: if the value could be null.
* Bottom: if the concept of nullness does not apply.
* @author ciera
*
*/
public enum NullLatticeElement {
BOTTOM, NULL, NOT_NULL, MAYBE_NULL;
}
|
shachindrasingh/apiman | gateway/engine/core/src/main/java/io/apiman/gateway/engine/IMetrics.java | /*
* Copyright 2015 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.apiman.gateway.engine;
import io.apiman.gateway.engine.metrics.RequestMetric;
/**
* An interface used by the engine to report metric information as it
* processes requests. Each request is reported to the metrics system
* so that it can be recorded/aggregated/analyzed.
*
* @author <EMAIL>
*/
public interface IMetrics {
/**
* Records the metrics for a single request. Most implementations will likely
* asynchronously process this information.
* @param metric the request metric
*/
public void record(RequestMetric metric);
/**
* Provides the component registry (before any call to {@link #record(RequestMetric)})
* is made. Metrics can then access HTTP client components, etc.
* @param registry the component registry
*/
public void setComponentRegistry(IComponentRegistry registry);
}
|
ahunter-eyelock/wtf | include/wtf/wtf.hpp | <filename>include/wtf/wtf.hpp
/** @file
@copyright <NAME> (c) 2016. Distributed under the Boost Software License Version 1.0. See LICENSE.md or http://boost.org/LICENSE_1_0.txt for details.
*/
#pragma once
#if !defined(NOMINMAX)
#define NOMINMAX 1
#endif
#if !defined(_WIN32_IE)
#define _WIN32_IE 0x600
#endif
/** @def WTF_USE_VISUAL_STYLES
@brief Enables/disables the use of visual styles through uxtheme.dll
*/
#if !defined(WTF_USE_VISUAL_STYLES)
#define WTF_USE_VISUAL_STYLES 1
#endif
/** @def WTF_USE_COMMON_CONTROLS
@brief Enables/disables the use and dependency of extended native controls in comctl32.dll
@details The most basic set of controls are implemented in the Windows GDI subsystem and extended in the common controls library
*/
#if !defined(WTF_USE_COMMON_CONTROLS)
#define WTF_USE_COMMON_CONTROLS 1
#endif
/** @def WTF_USE_RICHEDIT
@brief Enables/disables the use and dependency of the rich edit control in msftedit.dll
*/
#if !defined(WTF_USE_RICHEDIT)
#define WTF_USE_RICHEDIT 1
#endif
/** @def WTF_USE_COMMON_DIALOGS
@brief Enables/disables the use and dependency of common dialogs implemented in comdlg32.dll
*/
#if !defined(WTF_USE_COMMON_DIALOGS)
#define WTF_USE_COMMON_DIALOGS 1
#endif
/** @def WTF_DEBUG_MESSAGES
@brief Debug windows messages with OutputDebugString
*/
#if !defined(WTF_DEBUG_MESSAGES)
#if defined(DEBUG) || defined(_DEBUG)
#define WTF_DEBUG_MESSAGES 1
#else
#define WTF_DEBUG_MESSAGES 0
#endif
#endif
#define OEMRESOURCE
#include <tchar.h>
#include <WinSock2.h>
#include <Windows.h>
#include <windowsx.h>
#if WTF_USE_VISUAL_STYLES
#pragma comment(lib, "uxtheme.lib")
#include <Uxtheme.h>
#if defined _M_IX86
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='<KEY>' language='*'\"")
#elif defined _M_IA64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='<KEY>' language='*'\"")
#elif defined _M_X64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='<KEY>' language='*'\"")
#else
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='<KEY>' language='*'\"")
#endif
#endif
#if WTF_USE_COMMON_CONTROLS
#include <CommCtrl.h>
#pragma comment(lib, "comctl32.lib")
#endif
#if WTF_USE_RICHEDIT
#include <richedit.h>
#endif
#if WTF_USE_COMMON_DIALOGS
#include <commdlg.h>
#include <cderr.h>
#pragma comment(lib, "comdlg32.lib")
#endif
#include <algorithm>
#include <stdexcept>
#include <string>
#include <cassert>
#include <typeinfo>
#include <memory>
#include <vector>
#include <map>
#include <functional>
#include <iterator>
#include <sstream>
#include <mutex>
#include <locale>
#include <codecvt>
#include <atomic>
#if !defined(DOXY_INVOKED)
#define DOXY_INVOKED 0
#endif
/** @defgroup Policies Policies
@brief Behavioral policies
@details This group of classes are discrete behavioral components. They're composed to create feature-rich concrete controls
*/
/** @defgroup Messages Messages
@brief Message handling policies
@details This group of policy classes handle windows messages. They're composed to create feature-rich concrete controls
*/
/** @defgroup Controls Controls
@brief WTF Controls
@details This group of concrete classes are a composition of behavioral policies and message handlers
*/
/** @namespace wtf
@brief Primary namespace
*/
namespace wtf {
/** @namespace wtf::controls
@brief Native controls
@details These controls are implemented by the Windows system
*/
namespace controls {}
/** @namespace wtf::custom
@brief Custom controls
@details These controls are implemented by WTF and only available in WTF binaries
*/
namespace custom{}
/** @namespace wtf::layouts
@brief Layout policies
@details These policies define how child windows are positioned and resized
*/
namespace layouts {}
/**
@interface window window.hpp
@brief Base class of controls and forms
@details This class is inherited as the super-most base class of controls and forms via hierarchy generation.
*/
struct window;
/**
@class window_impl window.hpp
@brief Implements a control or form
@details This is the hierarchy generator that composes a collection of behavior policies and message handlers into a concrete control or form.
@details Policies are combine in a linear hierarchy in the order listed with the window class being the super-most base class.
@tparam implementation_type The concrete implementation
@tparam policy_list The list of behavioral policies that the implementation will inherit.
*/
template <typename implementation_type, template <typename> typename...policy_list> struct window_impl;
/** @enum coord_frame
@brief Distinguishes coordinate frame relative to the screen or window client area
*/
enum class coord_frame {
screen, /**< screen relative */
client, /**< window client area relative */
};
/** @typedef tstring
@brief Primary string representation. Can be either MULTIBYTE or UNICODE depending on compilation mode.
*/
using tstring = std::basic_string<TCHAR>;
#if !DOXY_INVOKED
extern "C" HINSTANCE__ __ImageBase;
#endif
//! @brief Returns the instance handle of the current process.
inline static constexpr HINSTANCE instance_handle() noexcept { return &__ImageBase; }
/** @brief Constructs a tstring representation of a value
@param value value to convert
@return a tstring representation of the value
*/
template <typename _Ty> static tstring to_tstring(_Ty value){ return _::to_tstring_impl<_Ty, TCHAR>::get(value); }
/** @namespace wtf::policy
@brief Behavioral policies
@ingroup Policies
*/
namespace policy{
#if !DOXY_INVOKED
namespace _{}
#endif
}
#if !DOXY_INVOKED
namespace _ {
static std::mutex& _active_forms_lock() noexcept {
static std::mutex _forms_lock;
return _forms_lock;
}
static std::vector<const window*>& _active_forms() noexcept {
static std::vector<const window*> _forms;
return _forms;
}
}
#endif
//! @brief Contains the active WTF forms in the process
static const std::vector<const window*>& active_forms() noexcept { return _::_active_forms(); }
#if !DOXY_INVOKED
namespace _ {
template <typename, typename> struct to_tstring_impl;
template <typename _Ty> struct to_tstring_impl<_Ty, wchar_t> {
static std::basic_string<wchar_t> get(const _Ty& value) { return std::to_wstring(value); }
};
template <typename _Ty> struct to_tstring_impl<_Ty, char> {
static std::basic_string<char> get(const _Ty& value) { return std::to_string(value); }
};
template <> struct to_tstring_impl<const char *, char> {
static std::basic_string<char> get(const char * value) { return std::basic_string<char>(value); }
};
template <> struct to_tstring_impl<const char *, wchar_t> {
static std::basic_string<wchar_t> get(const char * value) {
return std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(value);
}
};
template <> struct to_tstring_impl<std::string, char> {
static std::basic_string<char> get(std::string value) {
return std::basic_string<char>(value);
}
};
template <> struct to_tstring_impl<std::string, wchar_t> {
static std::basic_string<wchar_t> get(std::string value) {
return std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(value);
}
};
}
#endif
}
#if !defined(PRAGMA_)
#define PRAGMA_( ... ) __pragma( __VA_ARGS__ )
#endif
#if !defined(NOVTABLE)
#define NOVTABLE __declspec(novtable)
#endif
#if !defined(_QUOTE)
#define _QUOTE( ... ) # __VA_ARGS__
#endif
#if !defined(QUOTE)
#define QUOTE( ... ) _QUOTE( __VA_ARGS__ )
#endif
#if !defined(NOTE)
#define NOTE( ... ) PRAGMA_(message ( __FILE__ "(" QUOTE(__LINE__) "): TODO : " __VA_ARGS__ ))
#endif
#if !defined(NOTE)
#define NOTE( ... ) PRAGMA_(message ( __FILE__ "(" QUOTE(__LINE__) "): NOTE : " __VA_ARGS__ ))
#endif
#if defined(_DEBUG)
#if !defined(D_)
#define D_(...) __VA_ARGS__
#endif
#if !defined(R_)
#define R_(...)
#endif
#else
#if !defined(D_)
#define D_(...)
#endif
#if !defined(R_)
#define R_(...) __VA_ARGS__
#endif
#endif
#include "exception.hpp"
#include "_/meta.hpp"
#include "_/msg_names.hpp"
#include "_/weak_enum.hpp"
#include "_/coinitialize.hpp"
#include "_/init_common_controls.hpp"
#include "message_box.hpp"
#include "callback.hpp"
#include "point.hpp"
#include "color.hpp"
#include "rect.hpp"
#include "size.hpp"
#include "icon.hpp"
#include "cursor.hpp"
#include "bitmap.hpp"
#include "brush.hpp"
#include "pen.hpp"
#include "region.hpp"
#include "resource.hpp"
#include "font.hpp"
#include "window_class.hpp"
#include "device_context.hpp"
#include "paint_struct.hpp"
#include "message.hpp"
#include "window_message.hpp"
#include "menu.hpp"
#include "window.hpp"
#include "monitor.hpp"
#include "_/effects.hpp"
#include "_/text_metrics.hpp"
#include "_/SystemParameters.hpp"
#include "messages/messages.hpp"
#include "messages/nm_click.hpp"
#include "messages/nm_dblclick.hpp"
#include "messages/nm_killfocus.hpp"
#include "messages/nm_rclick.hpp"
#include "messages/nm_setfocus.hpp"
#include "messages/wm_activate.hpp"
#include "messages/wm_char.hpp"
#include "messages/wm_close.hpp"
#include "messages/wm_command.hpp"
#include "messages/wm_create.hpp"
#include "messages/wm_dblclick.hpp"
#include "messages/wm_destroy.hpp"
#include "messages/wm_enable.hpp"
#include "messages/wm_erasebkgnd.hpp"
#include "messages/wm_geticon.hpp"
#include "messages/wm_getminmaxinfo.hpp"
#include "messages/wm_keydown.hpp"
#include "messages/wm_keyup.hpp"
#include "messages/wm_killfocus.hpp"
#include "messages/wm_mouse_down.hpp"
#include "messages/wm_mouse_leave.hpp"
#include "messages/wm_mouse_move.hpp"
#include "messages/wm_mouse_up.hpp"
#include "messages/wm_mouse_wheel.hpp"
#include "messages/wm_move.hpp"
#include "messages/wm_nccalcsize.hpp"
#include "messages/wm_ncmouse_down.hpp"
#include "messages/wm_ncmouse_leave.hpp"
#include "messages/wm_ncmouse_move.hpp"
#include "messages/wm_ncmouse_up.hpp"
#include "messages/wm_ncpaint.hpp"
#include "messages/wm_notify.hpp"
#include "messages/wm_notifyformat.hpp"
#include "messages/wm_paint.hpp"
#include "messages/wm_setcursor.hpp"
#include "messages/wm_setfocus.hpp"
#include "messages/wm_showwindow.hpp"
#include "messages/wm_size.hpp"
#include "messages/wm_sizing.hpp"
#include "messages/wm_timer.hpp"
#include "policies/has_background.hpp"
#include "policies/has_border.hpp"
#include "policies/has_caret.hpp"
#include "policies/has_click.hpp"
#include "policies/has_close.hpp"
#include "policies/has_cursor.hpp"
#include "policies/has_enable.hpp"
#include "policies/has_exstyle.hpp"
#include "policies/has_focus.hpp"
#include "policies/has_font.hpp"
#include "policies/has_hscroll.hpp"
#include "policies/has_icon.hpp"
#include "policies/has_image.hpp"
#include "policies/has_invalidate.hpp"
#include "policies/has_move.hpp"
#include "policies/has_orientation.hpp"
#include "policies/has_owner_drawn_border.hpp"
#include "policies/has_owner_drawn_font.hpp"
#include "policies/has_owner_drawn_text.hpp"
#include "policies/has_repeat_click.hpp"
#include "policies/has_show.hpp"
#include "policies/has_size.hpp"
#include "policies/has_style.hpp"
#include "policies/has_text.hpp"
#include "policies/has_timer.hpp"
#include "policies/has_titlebar.hpp"
#include "policies/has_vscroll.hpp"
#include "policies/has_zorder.hpp"
#include "layouts/grid.hpp"
#include "controls/button.hpp"
#include "controls/combobox.hpp"
#include "controls/edit.hpp"
#include "controls/label.hpp"
#include "controls/listbox.hpp"
#include "controls/menu.hpp"
#if WTF_USE_COMMON_CONTROLS
#include "controls/calendar.hpp"
#include "controls/date_time.hpp"
#include "controls/hotkey.hpp"
#include "controls/image_list.hpp"
#include "controls/listview.hpp"
#include "controls/pager.hpp"
#include "controls/property_sheet.hpp"
#include "controls/rebar.hpp"
#include "controls/progressbar.hpp"
#include "controls/tab.hpp"
#include "controls/tree.hpp"
#include "controls/statusbar.hpp"
#include "controls/syslink.hpp"
#include "controls/task_dialog.hpp"
#include "controls/tooltip.hpp"
#include "controls/trackbar.hpp"
#include "controls/up_down.hpp"
#endif
#if WTF_USE_RICHEDIT
#include "controls/richedit.hpp"
#endif
#if WTF_USE_COMMON_DIALOGS
#include "dialogs/exception.hpp"
#include "dialogs/choose_color.hpp"
#include "dialogs/file_open_save.hpp"
#endif
#include "custom/splitter.hpp"
#include "custom/panel.hpp"
#include "form.hpp"
#include "console.hpp" |
Theembers/iot-dc | iot-framework-dc/src/main/java/com/theembers/iot/router/route/MultipleRoute.java | <filename>iot-framework-dc/src/main/java/com/theembers/iot/router/route/MultipleRoute.java
package com.theembers.iot.router.route;
import com.theembers.iot.collector.SourceData;
import com.theembers.iot.processor.Processor;
import com.theembers.iot.router.Router;
import com.theembers.iot.router.rule.MultipleRule;
import com.theembers.iot.shadow.Shadow;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;
/**
* @author <NAME>
* createTime 2019-11-13 15:53
*/
public class MultipleRoute extends AbstractRoute<Map<String[], Dispatcher>, MultipleRule> {
private static final ExecutorService THREAD_POOL = new ThreadPoolExecutor(5, 10, 60, TimeUnit.MINUTES,
new LinkedBlockingQueue<>(100), Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
@Override
public Map<String[], Dispatcher> buildDispatcher(Router router, MultipleRule rule, Map<String[], Dispatcher> dispatchers) {
if (dispatchers == null) {
dispatchers = new HashMap<>();
}
Map<String, Processor> processorMap = router.getMap();
Map<String, String[]> ruleKey = this.rule.key();
if (ruleKey == null || ruleKey.size() == 0) {
return dispatchers;
}
for (String head : ruleKey.keySet()) {
String[] keys = ruleKey.get(head);
if (keys == null || keys.length == 0) {
return dispatchers;
}
Dispatcher d = new Dispatcher();
for (String key : keys) {
d.append(processorMap.get(key));
}
dispatchers.put(keys, d);
}
return dispatchers;
}
@Override
public void run(Shadow shadow, SourceData data) {
Map<String[], Dispatcher> dispatcherMap = this.dispatchers;
dispatcherMap.forEach((keys, dispatcher) -> THREAD_POOL.execute(() -> dispatcher.run(shadow, data)));
}
}
|
kolema-tech/sigma-spring | sigma-security-spring-boot-starter/src/main/java/com/sigma/security/SigmaSecurityProperties.java | <gh_stars>0
package com.sigma.security;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* @author huston.peng
* @version 1.0.8
* date-time: 2019-10-
* desc:
**/
@Configuration
@ConfigurationProperties(prefix = "sigma.security")
@Data
public class SigmaSecurityProperties {
/**
* 是否启用
*/
private Boolean enableOpsCors = false;
}
|
fabiojna02/OpenCellular | firmware/coreboot/3rdparty/blobs/cpu/intel/model_f3x/microcode.h |
#include "microcode-m0df320a.h"
#include "microcode-m0df330c.h"
#include "microcode-m1df3417.h"
|
wangjuneng/spring-security-staff | core/src/main/java/org/springframework/security/core/context/InheritableThreadLocalSecurityContextHolderStrategy.java | <reponame>wangjuneng/spring-security-staff<gh_stars>0
package org.springframework.security.core.context;
import org.springframework.util.Assert;
public class InheritableThreadLocalSecurityContextHolderStrategy implements SecurityContextHolderStrategy {
private static final ThreadLocal<SecurityContext> contextHolder = new InheritableThreadLocal<SecurityContext>();
@Override
public void clearContext() {
contextHolder.remove();
}
@Override
public SecurityContext getContext() {
SecurityContext ctx = contextHolder.get();
if (ctx == null) {
ctx = createEmptyContext();
contextHolder.set(ctx);
}
return ctx;
}
public void setContext(SecurityContext context) {
Assert.notNull(context, "Only non-null SecurityContext instances are permitted");
contextHolder.set(context);
}
public SecurityContext createEmptyContext() {
return new SecurityContextImpl();
}
}
|
Suicolen/RSPSi | Client/src/main/java/com/jagex/util/GraphicUtils.java | package com.jagex.util;
import java.awt.Graphics;
public class GraphicUtils {
public static void drawStringCentered(Graphics g, int y, int width, String text) {
g.drawString(text, width / 2 - g.getFontMetrics().stringWidth(text), y);
}
}
|
danielavellar15/ckeditor5 | packages/ckeditor5-find-and-replace/src/findandreplacestate.js | /**
* @license Copyright (c) 2003-2021, CKSource - <NAME>. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @module find-and-replace/findandreplacestate
*/
import { ObservableMixin, mix, Collection } from 'ckeditor5/src/utils';
/**
* The object storing find and replace plugin state for a given editor instance.
*
* @mixes module:utils/observablemixin~ObservableMixin
*/
export default class FindAndReplaceState {
/**
* Creates an instance of the state.
*
* @param {module:engine/model/model~Model} model
*/
constructor( model ) {
/**
* A collection of find matches.
*
* @protected
* @observable
* @member {module:utils/collection~Collection} #results
*/
this.set( 'results', new Collection() );
/**
* Currently highlighted search result in {@link #results matched results}.
*
* @readonly
* @observable
* @member {Object|null} #highlightedResult
*/
this.set( 'highlightedResult', null );
/**
* Searched text value.
*
* @readonly
* @observable
* @member {String} #searchText
*/
this.set( 'searchText', '' );
/**
* Replace text value.
*
* @readonly
* @observable
* @member {String} #replaceText
*/
this.set( 'replaceText', '' );
/**
* Indicates whether the matchCase checkbox has been checked.
*
* @readonly
* @observable
* @member {Boolean} #matchCase
*/
this.set( 'matchCase', false );
/**
* Indicates whether the matchWholeWords checkbox has been checked.
*
* @readonly
* @observable
* @member {Boolean} #matchWholeWords
*/
this.set( 'matchWholeWords', false );
this.results.on( 'change', ( eventInfo, { removed, index } ) => {
removed = Array.from( removed );
if ( removed.length ) {
let highlightedResultRemoved = false;
model.change( writer => {
for ( const removedResult of removed ) {
if ( this.highlightedResult === removedResult ) {
highlightedResultRemoved = true;
}
if ( model.markers.has( removedResult.marker.name ) ) {
writer.removeMarker( removedResult.marker );
}
}
} );
if ( highlightedResultRemoved ) {
const nextHighlightedIndex = index >= this.results.length ? 0 : index;
this.highlightedResult = this.results.get( nextHighlightedIndex );
}
}
} );
}
/**
* Cleans the state up and removes markers from the model.
*
* @param {module:engine/model/model~Model} model
*/
clear( model ) {
this.searchText = '';
model.change( writer => {
if ( this.highlightedResult ) {
const oldMatchId = this.highlightedResult.marker.name.split( ':' )[ 1 ];
const oldMarker = model.markers.get( `findResultHighlighted:${ oldMatchId }` );
if ( oldMarker ) {
writer.removeMarker( oldMarker );
}
}
[ ...this.results ].forEach( ( { marker } ) => {
writer.removeMarker( marker );
} );
} );
this.results.clear();
}
}
mix( FindAndReplaceState, ObservableMixin );
|
nathanchen/netty-netty-5.0.0.Alpha1 | transport/src/main/java/io/netty/channel/ThreadPerChannelEventLoop.java | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.channel;
/**
* {@link SingleThreadEventLoop} which is used to handle OIO {@link Channel}'s. So in general there will be
* one {@link ThreadPerChannelEventLoop} per {@link Channel}.
*
*/
public class ThreadPerChannelEventLoop extends SingleThreadEventLoop {
private final ThreadPerChannelEventLoopGroup parent;
private Channel ch;
public ThreadPerChannelEventLoop(ThreadPerChannelEventLoopGroup parent) {
super(parent, parent.executor, true);
this.parent = parent;
}
@Override
protected void run() {
for (;;) {
Runnable task = takeTask();
if (task != null) {
task.run();
updateLastExecutionTime();
}
Channel ch = this.ch;
if (isShuttingDown()) {
if (ch != null) {
ch.unsafe().close(ch.unsafe().voidPromise());
}
if (confirmShutdown()) {
break;
}
} else {
if (ch != null) {
// Handle deregistration
if (!ch.isRegistered()) {
runAllTasks();
deregister();
}
}
}
}
}
protected void deregister() {
ch = null;
parent.activeChildren.remove(this);
parent.idleChildren.add(this);
}
}
|
driden/EntregaGrafos4 | Entrega4/CasoDePrueba.cpp | <gh_stars>0
#include "CasoDePrueba.h"
#include "CadenaFuncionHash.h"
#include "FuncionCostoCadenaInt.h"
CasoDePrueba::CasoDePrueba(Puntero<Sistema>(*inicializar)(nat max_ciudades))
{
this->inicializar = inicializar;
maxVertices = 20;
}
Puntero<Sistema> CasoDePrueba::InicializarSistema()
{
Puntero<Sistema> interfaz = inicializar(maxVertices);
ignorarOK = false;
return interfaz;
}
Cadena CasoDePrueba::GetNombre()const
{
return "Casos de Prueba";
}
void CasoDePrueba::CorrerPruebaConcreta()
{
Prueba1TADGrafo();
Prueba2TADGrafo();
Prueba3TADGrafo();
Prueba4TADGrafo();
Prueba5TADGrafoA();
Prueba5TADGrafoB();
Prueba6TADGrafo();
Prueba1Ej2();
Prueba2Ej2();
Prueba3Ej2(); // falla algo
Prueba4Ej2();
Prueba5Ej2();
Prueba6Ej2();
Prueba7Ej2();
Prueba8Ej2();
}
void CasoDePrueba::Verificar(TipoRetorno obtenido, TipoRetorno esperado, Cadena comentario)
{
if (!ignorarOK || obtenido != esperado)
Prueba::Verificar(obtenido, esperado, comentario);
}
template <class T>
void CasoDePrueba::Verificar(const T& obtenido, const T& esperado, Cadena comentario)
{
Verificar(SonIguales(obtenido, esperado) ? OK : ERROR, OK, comentario.DarFormato(ObtenerTexto(obtenido), ObtenerTexto(esperado)));
}
template <class T>
void CasoDePrueba::VerificarConjuntos(Iterador<T> obtenidos, Iterador<T> esperados, Cadena comentarioEncontrado, Cadena comentarioFalta, Cadena comentarioSobra)
{
bool verificarCantidad = true;
nat totalObtenidos = 0;
T aux;
obtenidos.Reiniciar();
esperados.Reiniciar();
foreach(T obtenido, obtenidos)
{
totalObtenidos++;
if (Pertenece(obtenido, esperados, aux))
Verificar(OK, OK, comentarioEncontrado.DarFormato(ObtenerTexto(obtenido), ObtenerTexto(obtenido)));
else
{
Verificar(ERROR, OK, comentarioSobra.DarFormato(ObtenerTexto(obtenido)));
verificarCantidad = false;
}
}
nat totalEsperados = 0;
obtenidos.Reiniciar();
esperados.Reiniciar();
foreach(T esperado, esperados)
{
totalEsperados++;
if (!Pertenece(esperado, obtenidos, aux))
{
Verificar(ERROR, OK, comentarioFalta.DarFormato(ObtenerTexto(esperado)));
verificarCantidad = false;
}
}
if (verificarCantidad && totalObtenidos != totalEsperados)
Verificar(ERROR, OK, "Se verifica la cantidad de elementos de los conjuntos");
}
template <class T>
bool CasoDePrueba::MismosElementos(Iterador<T> obtenidos, Iterador<T> esperados) const
{
T aux;
foreach(T obtenido, obtenidos)
{
if (!Pertenece(obtenido, esperados, aux))
{
return false;
}
}
foreach(T esperado, esperados)
{
if (!Pertenece(esperado, obtenidos, aux))
{
return false;
}
}
return true;
}
template <class T>
void CasoDePrueba::VerificarSecuencias(Iterador<T> obtenidos, Iterador<T> esperados, Cadena comentarioEncontrado, Cadena comentarioFalta, Cadena comentarioSobra)
{
esperados.Reiniciar();
foreach(T obtenido, obtenidos)
{
if (esperados.HayElemento())
{
T esperado = *esperados;
++esperados;
Verificar(obtenido, esperado, comentarioEncontrado);
}
else
Verificar(ERROR, OK, comentarioSobra.DarFormato(ObtenerTexto(obtenido)));
}
while (esperados.HayElemento())
{
T esperado = *esperados;
++esperados;
Verificar(ERROR, OK, comentarioFalta.DarFormato(ObtenerTexto(esperado)));
}
}
bool CasoDePrueba::SonIguales(const Cadena& obtenidos, const Cadena& esperados) const
{
return obtenidos == esperados;
}
template <class T>
bool CasoDePrueba::SonIguales(Iterador<T> obtenidos, Iterador<T> esperados) const
{
obtenidos.Reiniciar();
esperados.Reiniciar();
while (obtenidos.HayElemento() && esperados.HayElemento())
{
if (!SonIguales(*obtenidos, *esperados))
return false;
++obtenidos;
++esperados;
}
return esperados.HayElemento() == obtenidos.HayElemento();
}
template <class T>
Cadena CasoDePrueba::ObtenerTexto(Iterador<T> it) const
{
Cadena sepVacio = "";
Cadena sepGuion = "-";
Cadena sep = sepVacio;
Cadena retorno = sepVacio;
foreach(auto t, it)
{
retorno += sep + ObtenerTexto(t);
sep = sepGuion;
}
return retorno;
}
Cadena CasoDePrueba::ObtenerTexto(const Tupla<Cadena, Cadena>& t) const
{
Cadena ret = " ({0} - {1}) ";
return ret.DarFormato(ObtenerTexto(t.Dato1), ObtenerTexto(t.Dato2));
}
Cadena CasoDePrueba::ObtenerTexto(const Tupla<nat, nat>& t) const
{
Cadena ret = " {0} - {1} ";
return ret.DarFormato(ObtenerTexto(t.Dato1), ObtenerTexto(t.Dato2));
}
Cadena CasoDePrueba::ObtenerTexto(TipoConexo tipo) const
{
Cadena retorno = "error";
switch (tipo)
{
case NO_CONEXO:
retorno = "No Conexo";
break;
case DEBILMENTE_CONEXO:
retorno = "Debilmente Conexo";
break;
case FUERTEMENTE_CONEXO:
retorno = "Fuertemente Conexo";
break;
default:
break;
}
return retorno;
}
Cadena CasoDePrueba::ObtenerTexto(Cadena n) const
{
return n;
}
Cadena CasoDePrueba::ObtenerTexto(int n) const
{
nat nro = n;
Cadena ret = ObtenerTexto(nro);
if (n < 0)
{
ret = Cadena("-") + ret;
}
return ret;
}
Cadena CasoDePrueba::ObtenerTexto(nat n) const
{
switch (n)
{
case 0:
return "0";
case 1:
return "1";
case 2:
return "2";
case 3:
return "3";
case 4:
return "4";
case 5:
return "5";
case 6:
return "6";
case 7:
return "7";
case 8:
return "8";
case 9:
return "9";
default:
Cadena ret = "";
while (n != 0)
{
ret = ObtenerTexto(n % 10) + ret;
n /= 10;
}
return ret;
}
}
bool CasoDePrueba::SonIguales(const Tupla<Cadena, Cadena>& obtenido, const Tupla<Cadena, Cadena>& esperado) const
{
return (obtenido.Dato1 == esperado.Dato1 && obtenido.Dato2 == esperado.Dato2);
}
bool CasoDePrueba::SonIguales(const Tupla<nat, nat>& obtenido, const Tupla<nat, nat>& esperado) const
{
return (obtenido.Dato1 == esperado.Dato1 && obtenido.Dato2 == esperado.Dato2) ||
(obtenido.Dato2 == esperado.Dato1 && obtenido.Dato1 == esperado.Dato2);
}
bool CasoDePrueba::SonIguales(const bool obtenido, const bool esperado) const
{
return obtenido == esperado;
}
bool CasoDePrueba::SonIguales(const int obtenido, const int esperado) const
{
return obtenido == esperado;
}
bool CasoDePrueba::SonIguales(const nat obtenido, const nat esperado) const
{
return obtenido == esperado;
}
bool CasoDePrueba::SonIguales(const TipoConexo obtenido, const TipoConexo esperado) const
{
return obtenido == esperado;
}
template <class T>
bool CasoDePrueba::Pertenece(const T& dato, Iterador<T> iterador, T& encontrado) const
{
iterador.Reiniciar();
foreach(T dato2, iterador)
{
if (SonIguales(dato, dato2))
{
encontrado = dato2;
return true;
}
}
return false;
}
Array<Cadena> CasoDePrueba::InicializarGrafoCadenas(Puntero<Grafo<Cadena, int>> grafo) const
{
// Creamos datos de pruebas en el grafo
Array<Cadena> ciudades1(5);
ciudades1[0] = "Montevideo";
ciudades1[1] = "Maldonado";
ciudades1[2] = "La Paz";
ciudades1[3] = "Salto";
ciudades1[4] = "Durazno";
foreach (Cadena ciudad, ciudades1.ObtenerIterador())
{
grafo->AgregarVertice(ciudad);
}
// Cramos aristas de nivel 1
grafo->AgregarArco(ciudades1[0], ciudades1[1], 10);
grafo->AgregarArco(ciudades1[0], ciudades1[2], 17);
grafo->AgregarArco(ciudades1[2], ciudades1[3], 1);
grafo->AgregarArco(ciudades1[2], ciudades1[4], 3);
grafo->AgregarArco(ciudades1[3], ciudades1[4], 10);
return ciudades1;
}
Array<Cadena> CasoDePrueba::InicializarGrafoCadenas2(Puntero<Grafo<Cadena, int>> grafo) const
{
// Creamos datos de pruebas en el grafo
Array<Cadena> ciudades1(5);
ciudades1[0] = "Montevideo";
ciudades1[1] = "Maldonado";
ciudades1[2] = "La Paz";
ciudades1[3] = "Salto";
ciudades1[4] = "Durazno";
foreach(Cadena ciudad, ciudades1.ObtenerIterador())
{
grafo->AgregarVertice(ciudad);
}
// Cramos aristas de nivel 1
grafo->AgregarArco(ciudades1[0], ciudades1[1], 10);
grafo->AgregarArco(ciudades1[0], ciudades1[2], 17);
grafo->AgregarArco(ciudades1[2], ciudades1[3], 1);
grafo->AgregarArco(ciudades1[2], ciudades1[4], 10);
grafo->AgregarArco(ciudades1[3], ciudades1[4], 3);
return ciudades1;
}
//Operacion 1:
void CasoDePrueba::Prueba1TADGrafo()
{
IniciarSeccion("TAD Grafo");
Puntero<Sistema> interfaz = InicializarSistema();
Cadena mensaje = "";
nat cantidades = 0;
Tupla<TipoRetorno, Puntero<Grafo<Cadena, int>>> retorno = interfaz->CrearGrafo<Cadena, int>(maxVertices, new CadenaFuncionHash(), Comparador<Cadena>::Default);
Verificar(retorno.Dato1, OK, "Se crea el grafo.");
Puntero<Grafo<Cadena, int>> grafo = retorno.Dato2;
if (grafo == nullptr)
{
Verificar(ERROR, OK, "El grafo creado es nulo.");
}
else
{
IniciarSeccion("Pruebas creacion del grafo", OK);
Array<Cadena> ciudades = InicializarGrafoCadenas(grafo);
CerrarSeccion();
IniciarSeccion("Pruebas Vertices del grafo", OK);
Verificar(grafo->CantidadVertices(), ciudades.Largo, "Cantidad de vertices esperada '{1}', obtenida '{0}'");
cantidades = 5;
Verificar(grafo->CantidadArcos(), cantidades, "Cantidad de arcos esperada '{1}', obtenida '{0}'");
Cadena existeVertice = "El vertice '{0}' pertenece al grafo.";
foreach(Cadena ciudad, ciudades.ObtenerIterador())
{
if (grafo->ExisteVertice(ciudad))
{
Verificar(OK, OK, existeVertice.DarFormato(ciudad));
}
else
{
Verificar(ERROR, OK, existeVertice.DarFormato(ciudad));
}
}
VerificarConjuntos(grafo->Vertices(), ciudades.ObtenerIterador());
CerrarSeccion();
IniciarSeccion("Pruebas Adyacentes", OK);
Cadena ady = "Cantidad de vertieces adyacentes a '{0}' {1}";
Cadena aux = "esperado '{1}' obtenido '{0}'";
cantidades = 2;
Verificar(grafo->CantidadAdyacentes(ciudades[2]), cantidades, ady.DarFormato(ciudades[2], aux));
Verificar(grafo->CantidadAdyacentes(ciudades[0]), cantidades, ady.DarFormato(ciudades[0], aux));
Cadena incidentes = "Cantidad de vertieces incidentes a '{0}' {1}";
Verificar(grafo->CantidadIncidentes(ciudades[4]), cantidades, incidentes.DarFormato(ciudades[4], aux));
Array<Cadena> adyacentes(2);
adyacentes[0] = ciudades[4];
adyacentes[1] = ciudades[3];
VerificarConjuntos(grafo->Adyacentes(ciudades[2]), adyacentes.ObtenerIterador());
VerificarArco(grafo, ciudades[0], ciudades[1], 10);
VerificarArco(grafo, ciudades[2], ciudades[3], 1);
VerificarArco(grafo, ciudades[2], ciudades[4], 3);
VerificarArco(grafo, ciudades[0], ciudades[2], 17);
CerrarSeccion();
}
CerrarSeccion();
}
void CasoDePrueba::VerificarArco(Puntero<Grafo<Cadena, int>> grafo, Cadena origen, Cadena destino, int arcoEsperado)
{
Cadena existeArco = "Arco entre '{0} -> {1}' {2}";
Cadena aux = "esperado '{1}' obtenido '{0}'";
int arco = 0;
if (grafo->ExisteArco(origen, destino))
{
Verificar(OK, OK, existeArco.DarFormato(origen, destino, "existe"));
arco = grafo->ObtenerArco(origen, destino);
Verificar(arco, arcoEsperado, existeArco.DarFormato(origen, destino, aux));
}
else
{
Verificar(ERROR, OK, existeArco.DarFormato(origen, destino, "existe"));
}
}
void CasoDePrueba::Prueba2TADGrafo()
{
IniciarSeccion("TAD Grafo - Orden topologico");
Puntero<Sistema> interfaz = InicializarSistema();
Cadena mensaje = "";
nat cantidades = 0;
ignorarOK = true;
Tupla<TipoRetorno, Puntero<Grafo<Cadena, int>>> retorno = interfaz->CrearGrafo<Cadena, int>(maxVertices, new CadenaFuncionHash(), Comparador<Cadena>::Default);
Puntero<Grafo<Cadena, int>> grafo = retorno.Dato2;
if (grafo != nullptr)
{
Array<Cadena> ciudades = InicializarGrafoCadenas(grafo);
ignorarOK = false;
Matriz<bool> precedencias(5);
precedencias[0][1] = true;
precedencias[0][2] = true;
precedencias[2][3] = true;
precedencias[2][4] = true;
precedencias[3][4] = true;
Iterador<Cadena> orden = grafo->OrdenTopologico();
ComprobarOrdenTopologico(orden, ciudades, precedencias);
}
CerrarSeccion();
}
void CasoDePrueba::ComprobarOrdenTopologico(const Iterador<Cadena> &orden, const Array<Cadena> &ciudades, const Matriz<bool> &precedencias)
{
Array<nat> indices(ciudades.Largo);
int idx = 0;
foreach(Cadena ciudad, orden)
{
for (nat i = 0; i < indices.Largo; i++)
{
if (ciudades[i] == ciudad)
{
indices[idx++] = i;
break;
}
}
}
Cadena obtenido = "Se obtuvo el orden: '{0}'";
Verificar(OK, OK, obtenido.DarFormato(ObtenerTexto(orden)));
Cadena hayarco = "Hay un arco entre '{0}'y '{1}'";
for (nat i = 0; i < indices.Largo; i++)
{
for (nat j = i + 1; j < indices.Largo; j++)
{
if (precedencias[indices[j]][indices[i]])
{
Verificar(ERROR, OK, hayarco.DarFormato(ciudades[indices[j]], ciudades[indices[i]]));
}
}
}
}
void CasoDePrueba::CheckHayCamino(Puntero<Sistema> interfaz, Puntero<Grafo<Cadena, int>> grafo, Cadena origen, Cadena destino, bool esperado)
{
Cadena hayCamino = "No hay camino entre el vertice '{0}' y '{1}'";
if (esperado)
{
hayCamino = "Hay camino entre el vertice '{0}' y '{1}'";
}
if (esperado == grafo->HayCamino(origen, destino))
{
Verificar(OK, OK, hayCamino.DarFormato(origen, destino));
}
else
{
Verificar(ERROR, OK, hayCamino.DarFormato(origen, destino));
}
}
void CasoDePrueba::Prueba3TADGrafo()
{
IniciarSeccion("TAD Grafo - HayCamino");
Puntero<Sistema> interfaz = InicializarSistema();
ignorarOK = true;
Tupla<TipoRetorno, Puntero<Grafo<Cadena, int>>> retorno = interfaz->CrearGrafo<Cadena, int>(maxVertices, new CadenaFuncionHash(), Comparador<Cadena>::Default);
Puntero<Grafo<Cadena, int>> grafo = retorno.Dato2;
if (grafo != nullptr)
{
Array<Cadena> ciudades = InicializarGrafoCadenas(grafo);
ignorarOK = false;
CheckHayCamino(interfaz, grafo, ciudades[0], ciudades[1], true);
CheckHayCamino(interfaz, grafo, ciudades[1], ciudades[0], false);
CheckHayCamino(interfaz, grafo, ciudades[0], ciudades[3], true);
CheckHayCamino(interfaz, grafo, ciudades[0], ciudades[4], true);
CheckHayCamino(interfaz, grafo, ciudades[3], ciudades[0], false);
}
CerrarSeccion();
}
void CasoDePrueba::Prueba4TADGrafo()
{
IniciarSeccion("TAD Grafo - Es conexo");
Puntero<Sistema> interfaz = InicializarSistema();
ignorarOK = true;
Tupla<TipoRetorno, Puntero<Grafo<Cadena, int>>> retorno = interfaz->CrearGrafo<Cadena, int>(maxVertices, new CadenaFuncionHash(), Comparador<Cadena>::Default);
Puntero<Grafo<Cadena, int>> grafo = retorno.Dato2;
if (grafo != nullptr)
{
Array<Cadena> ciudades = InicializarGrafoCadenas(grafo);
ignorarOK = false;
Cadena mensaje = "Se esperaba un grafo '{1}' y se obtuvo '{0}'";
Verificar(grafo->EsConexo(), DEBILMENTE_CONEXO, mensaje);
grafo->AgregarArco(ciudades[1], ciudades[4], 10);
grafo->AgregarArco(ciudades[4], ciudades[0], 10);
Verificar(grafo->EsConexo(), FUERTEMENTE_CONEXO, mensaje);
grafo->AgregarVertice("cadena1");
grafo->AgregarVertice("cadena2");
grafo->AgregarArco("cadena2", "cadena1", 10);
grafo->AgregarArco("cadena1", "cadena2", 10);
Verificar(grafo->EsConexo(), NO_CONEXO, mensaje);
}
CerrarSeccion();
}
void CasoDePrueba::Prueba5TADGrafoA()
{
IniciarSeccion("TAD Grafo - cubrimiento minimo A");
Puntero<Sistema> interfaz = InicializarSistema();
ignorarOK = true;
Tupla<TipoRetorno, Puntero<Grafo<Cadena, int>>> retorno = interfaz->CrearGrafo<Cadena, int>(maxVertices, new CadenaFuncionHash(), Comparador<Cadena>::Default);
Puntero<Grafo<Cadena, int>> grafo = retorno.Dato2;
if (grafo != nullptr)
{
Array<Cadena> ciudades = InicializarGrafoCadenas2(grafo);
ignorarOK = false;
Iterador<Tupla<Cadena, Cadena>> esperado1;
Iterador<Tupla<Cadena, Cadena>> esperado2;
Iterador<Tupla<Cadena, Cadena>> esperado3;
Iterador<Tupla<Cadena, Cadena>> obtenido;
Array<Tupla<Cadena, Cadena>> arbol1(4);
arbol1[0] = Tupla<Cadena, Cadena>(ciudades[0], ciudades[1]);
arbol1[1] = Tupla<Cadena, Cadena>(ciudades[0], ciudades[2]);
arbol1[2] = Tupla<Cadena, Cadena>(ciudades[2], ciudades[3]);
arbol1[3] = Tupla<Cadena, Cadena>(ciudades[2], ciudades[4]);
Array<Tupla<Cadena, Cadena>> arbol2(4);
arbol2[0] = Tupla<Cadena, Cadena>(ciudades[0], ciudades[1]);
arbol2[1] = Tupla<Cadena, Cadena>(ciudades[0], ciudades[2]);
arbol2[2] = Tupla<Cadena, Cadena>(ciudades[2], ciudades[4]);
arbol2[3] = Tupla<Cadena, Cadena>(ciudades[4], ciudades[3]);
Array<Tupla<Cadena, Cadena>> arbol3(4);
arbol3[0] = Tupla<Cadena, Cadena>(ciudades[0], ciudades[1]);
arbol3[1] = Tupla<Cadena, Cadena>(ciudades[0], ciudades[2]);
arbol3[2] = Tupla<Cadena, Cadena>(ciudades[2], ciudades[3]);
arbol3[3] = Tupla<Cadena, Cadena>(ciudades[3], ciudades[4]);
esperado1 = arbol1.ObtenerIterador();
esperado2 = arbol2.ObtenerIterador();
esperado3 = arbol3.ObtenerIterador();
obtenido = grafo->ArbolCubrimientoMinimo();
if (MismosElementos(obtenido, esperado1)) {
VerificarConjuntos(obtenido, esperado1);
}
if (MismosElementos(obtenido, esperado2)) {
VerificarConjuntos(obtenido, esperado2);
}
if (MismosElementos(obtenido, esperado3)) {
VerificarConjuntos(obtenido, esperado3);
}
// VerificarConjuntos(obtenido, esperado1);
}
CerrarSeccion();
}
void CasoDePrueba::Prueba5TADGrafoB()
{
IniciarSeccion("TAD Grafo - cubrimiento minimo B");
Puntero<Sistema> interfaz = InicializarSistema();
ignorarOK = true;
Tupla<TipoRetorno, Puntero<Grafo<Cadena, int>>> retorno = interfaz->CrearGrafo<Cadena, int>(maxVertices, new CadenaFuncionHash(), Comparador<Cadena>::Default);
Puntero<Grafo<Cadena, int>> grafo = retorno.Dato2;
if (grafo != nullptr)
{
Array<Cadena> ciudades = InicializarGrafoCadenas2(grafo);
ignorarOK = false;
Iterador<Tupla<Cadena, Cadena>> esperado;
Iterador<Tupla<Cadena, Cadena>> obtenido;
Array<Tupla<Cadena, Cadena>> arbol(4);
arbol[0] = Tupla<Cadena, Cadena>(ciudades[0], ciudades[1]);
arbol[1] = Tupla<Cadena, Cadena>(ciudades[0], ciudades[2]);
arbol[2] = Tupla<Cadena, Cadena>(ciudades[2], ciudades[3]);
arbol[3] = Tupla<Cadena, Cadena>(ciudades[3], ciudades[4]);
esperado = arbol.ObtenerIterador();
obtenido = grafo->ArbolCubrimientoMinimo(FuncionCostoCadenaInt());
VerificarConjuntos(obtenido, esperado);
}
CerrarSeccion();
}
void CasoDePrueba::VerificarComponentes(const Iterador<Iterador<Cadena>> &obtenidos, const Iterador<Iterador<Cadena>> &esperados)
{
bool verificarCantidad = true;
nat totalObtenidos = 0;
Cadena comentarioEncontrado = "Se encontro la componente '{0}'";
Cadena comentarioSobra = "Sobra la componente '{0}'";
Cadena comentarioFalta = "Falta la componente '{0}'";
foreach(Iterador<Cadena> obtenido, obtenidos)
{
totalObtenidos++;
if (Pertenece(obtenido, esperados))
Verificar(OK, OK, comentarioEncontrado.DarFormato(ObtenerTexto(obtenido)));
else
{
Verificar(ERROR, OK, comentarioSobra.DarFormato(ObtenerTexto(obtenido)));
verificarCantidad = false;
}
}
nat totalEsperados = 0;
foreach(Iterador<Cadena> esperado, esperados)
{
totalEsperados++;
if (!Pertenece(esperado, obtenidos))
{
Verificar(ERROR, OK, comentarioFalta.DarFormato(ObtenerTexto(esperado)));
verificarCantidad = false;
}
}
if (verificarCantidad && totalObtenidos != totalEsperados)
Verificar(ERROR, OK, "Se verifica la cantidad de elementos de los conjuntos");
}
bool CasoDePrueba::Pertenece(const Iterador<Cadena>& dato, const Iterador<Iterador<Cadena>> &iterador) const
{
foreach(Iterador<Cadena> dato2, iterador)
{
if (MismosElementos(dato, dato2))
{
return true;
}
}
return false;
}
void CasoDePrueba::Prueba6TADGrafo()
{
IniciarSeccion("TAD Grafo - componentes conexas");
Puntero<Sistema> interfaz = InicializarSistema();
ignorarOK = true;
Tupla<TipoRetorno, Puntero<Grafo<Cadena, int>>> retorno = interfaz->CrearGrafo<Cadena, int>(maxVertices, new CadenaFuncionHash(), Comparador<Cadena>::Default);
Puntero<Grafo<Cadena, int>> grafo = retorno.Dato2;
if (grafo != nullptr)
{
Array<Cadena> ciudades = InicializarGrafoCadenas(grafo);
ignorarOK = false;
/*
grafo->AgregarArco(ciudades[0], ciudades[1], 10);
grafo->AgregarArco(ciudades[0], ciudades[2], 17);
grafo->AgregarArco(ciudades[2], ciudades[3], 1);
grafo->AgregarArco(ciudades[2], ciudades[4], 3);
grafo->AgregarArco(ciudades[3], ciudades[4], 10);
*/
Iterador<Iterador<Cadena>> obtenido = grafo->ComponentesConexas();
Array<Iterador<Cadena>> esperado(1);
esperado[0] = ciudades.ObtenerIterador();
VerificarComponentes(obtenido, esperado.ObtenerIterador());
}
CerrarSeccion();
}
Array<Cadena> CasoDePrueba::InicializarCiudades1(Puntero<Sistema> interfaz, bool conexiones)
{
// Creamos datos de pruebas en el grafo
Array<Cadena> ciudades1(5);
ciudades1[0] = "Montevideo";
ciudades1[1] = "Maldonado";
ciudades1[2] = "La Paz";
ciudades1[3] = "Salto";
ciudades1[4] = "Durazno";
Cadena mensaje = "Se da de alta la ciuadad '{0}'";
foreach(Cadena ciudad, ciudades1.ObtenerIterador())
{
Verificar(interfaz->AltaCiudad(ciudad), OK, mensaje.DarFormato(ciudad));
}
if (conexiones)
{
// Creamos datos de pruebas en el grafo
mensaje = "Se da de alta la conexion '{0}-{1}'";
Verificar(interfaz->AltaConexion(ciudades1[0], ciudades1[1], OMNIBUS, 1000, 100, 10), OK, mensaje.DarFormato(ciudades1[0], ciudades1[1]));
Verificar(interfaz->AltaConexion(ciudades1[0], ciudades1[2], OMNIBUS, 70, 10, 1), OK, mensaje.DarFormato(ciudades1[0], ciudades1[2]));
Verificar(interfaz->AltaConexion(ciudades1[2], ciudades1[0], OMNIBUS, 70, 10, 1), OK, mensaje.DarFormato(ciudades1[2], ciudades1[0]));
Verificar(interfaz->AltaConexion(ciudades1[0], ciudades1[3], AVION, 500, 50, 1), OK, mensaje.DarFormato(ciudades1[0], ciudades1[3]));
Verificar(interfaz->AltaConexion(ciudades1[2], ciudades1[3], OMNIBUS, 200, 40, 4), OK, mensaje.DarFormato(ciudades1[2], ciudades1[3]));
Verificar(interfaz->AltaConexion(ciudades1[2], ciudades1[4], OMNIBUS, 100, 20, 8), OK, mensaje.DarFormato(ciudades1[2], ciudades1[4]));
Verificar(interfaz->AltaConexion(ciudades1[4], ciudades1[3], OMNIBUS, 50, 20, 8), OK, mensaje.DarFormato(ciudades1[4], ciudades1[3]));
Verificar(interfaz->AltaConexion(ciudades1[3], ciudades1[1], OMNIBUS, 500, 200, 1), OK, mensaje.DarFormato(ciudades1[3], ciudades1[1]));
}
return ciudades1;
}
Array<Cadena> CasoDePrueba::InicializarCiudades2(Puntero<Sistema> interfaz, bool conexiones)
{
// Creamos datos de pruebas en el grafo
Array<Cadena> ciudades1(3);
ciudades1[0] = "Gualeguaychu";
ciudades1[1] = "Mar del Plata";
ciudades1[2] = "Buenos Aires";
Cadena mensaje = "Se da de alta la ciuadad '{0}'";
foreach(Cadena ciudad, ciudades1.ObtenerIterador())
{
Verificar(interfaz->AltaCiudad(ciudad), OK, mensaje.DarFormato(ciudad));
}
if (conexiones)
{
// Creamos datos de pruebas en el grafo
mensaje = "Se da de alta la conexion '{0}-{1}'";
//const TipoTransporte &tipo, const nat &costo, const nat &tiempo, const nat &nroParadas);
Verificar(interfaz->AltaConexion(ciudades1[0], ciudades1[1], OMNIBUS, 100, 110, 8), OK, mensaje.DarFormato(ciudades1[0], ciudades1[1]));
Verificar(interfaz->AltaConexion(ciudades1[0], ciudades1[2], OMNIBUS, 50, 100, 3), OK, mensaje.DarFormato(ciudades1[0], ciudades1[2]));
Verificar(interfaz->AltaConexion(ciudades1[1], ciudades1[2], OMNIBUS, 49, 10, 4), OK, mensaje.DarFormato(ciudades1[1], ciudades1[2]));
Verificar(interfaz->AltaConexion(ciudades1[2], ciudades1[1], OMNIBUS, 49, 10, 4), OK, mensaje.DarFormato(ciudades1[2], ciudades1[1]));
Verificar(interfaz->AltaConexion(ciudades1[2], ciudades1[0], OMNIBUS, 30, 20, 1), OK, mensaje.DarFormato(ciudades1[2], ciudades1[0]));
}
return ciudades1;
}
Array<Cadena> CasoDePrueba::InicializarCiudades3(Puntero<Sistema> interfaz, bool conexiones)
{
// Creamos datos de pruebas en el grafo
Array<Cadena> ciudades1(4);
ciudades1[0] = "<NAME>";
ciudades1[1] = "Brasilia";
ciudades1[2] = "Natal";
ciudades1[3] = "Rio";
Cadena mensaje = "Se da de alta la ciuadad '{0}'";
foreach(Cadena ciudad, ciudades1.ObtenerIterador())
{
Verificar(interfaz->AltaCiudad(ciudad), OK, mensaje.DarFormato(ciudad));
}
if (conexiones)
{
// Creamos datos de pruebas en el grafo
mensaje = "Se da de alta la conexion '{0}-{1}'";
//const TipoTransporte &tipo, const nat &costo, const nat &tiempo, const nat &nroParadas);
Verificar(interfaz->AltaConexion(ciudades1[0], ciudades1[1], AVION, 700, 30, 8), OK, mensaje.DarFormato(ciudades1[0], ciudades1[1]));
Verificar(interfaz->AltaConexion(ciudades1[1], ciudades1[2], AVION, 300, 70, 1), OK, mensaje.DarFormato(ciudades1[1], ciudades1[2]));
Verificar(interfaz->AltaConexion(ciudades1[2], ciudades1[3], AVION, 5000, 1000, 4), OK, mensaje.DarFormato(ciudades1[2], ciudades1[3]));
Verificar(interfaz->AltaConexion(ciudades1[3], ciudades1[0], AVION, 3000, 50, 1), OK, mensaje.DarFormato(ciudades1[3], ciudades1[0]));
}
return ciudades1;
}
void CasoDePrueba::InicializarConexionesExtra(Puntero<Sistema> interfaz)
{
Cadena mensaje = "Se da de alta la conexion '{0}-{1}'";
Verificar(interfaz->AltaConexion("Montevideo", "Buenos Aires", AVION, 1000, 1000, 7), OK, mensaje.DarFormato("Montevideo", "Buenos Aires"));
Verificar(interfaz->AltaConexion("Salto", "Buenos Aires", AVION, 500, 10, 1), OK, mensaje.DarFormato("Salto", "Buenos Aires"));
Verificar(interfaz->AltaConexion("Salto", "Gualeguaychu", OMNIBUS, 20, 10, 1), OK, mensaje.DarFormato("Salto", "Gualeguaychu"));
Verificar(interfaz->AltaConexion("Montevideo", "San Pablo", AVION, 20, 10, 100), OK, mensaje.DarFormato("Montevideo", "San Pablo"));
Verificar(interfaz->AltaConexion("Maldonado", "Natal", AVION, 20, 10, 1), OK, mensaje.DarFormato("Maldonado", "Natal"));
}
//Ejercicio 2:
void CasoDePrueba::Prueba1Ej2()
{
IniciarSeccion("Ejercicio Grafo 1 - Creacion");
Puntero<Sistema> interfaz = InicializarSistema();
Array<Cadena> ciudades = InicializarCiudades1(interfaz, true);
InicializarCiudades2(interfaz, true);
InicializarCiudades3(interfaz, true);
InicializarConexionesExtra(interfaz);
Cadena errorCiudad = "La ciudad '{0}' ya existe";
Verificar(interfaz->AltaCiudad(ciudades[0]), ERROR, errorCiudad.DarFormato(ciudades[0]));
Verificar(interfaz->AltaCiudad(ciudades[2]), ERROR, errorCiudad.DarFormato(ciudades[2]));
Verificar(interfaz->AltaConexion("Roma", ciudades[0], OMNIBUS, 100, 10, 1), ERROR, "No existe ciudad 'Roma'");
Verificar(interfaz->AltaConexion(ciudades[0], "Roma", OMNIBUS, 100, 10, 1), ERROR, "No existe ciudad 'Roma'");
CerrarSeccion();
}
void CasoDePrueba::VerificarCamino(Tupla<TipoRetorno, Iterador<Cadena>> &obtenido, Tupla<TipoRetorno, Iterador<Cadena>> &esperado, const Cadena &comentario)
{
if (obtenido.Dato1 == OK && esperado.Dato1 == OK)
{
IniciarSeccion(comentario, esperado.Dato1);
VerificarSecuencias(obtenido.Dato2, esperado.Dato2);
CerrarSeccion();
}
else
Verificar(obtenido.Dato1, esperado.Dato1, comentario);
}
void CasoDePrueba::Prueba2Ej2()
{
IniciarSeccion("Ejercicio Grafo 2 - CAmino Mas Barato");
Puntero<Sistema> interfaz = InicializarSistema();
//No queremos que cuente los OK pq ya se probaron antes
ignorarOK = true;
Array<Cadena> ciudades1 = InicializarCiudades1(interfaz, true);
ignorarOK = false;
Cadena comentario = "Se verifica camino mas barato entre '{0}-{1}'";
Tupla<TipoRetorno, Iterador<Cadena>> obtenido;
Tupla<TipoRetorno, Iterador<Cadena>> esperado(OK, nullptr);
Array<Cadena> camino;
camino = Array<Cadena>(4);
camino[0] = ciudades1[0];
camino[1] = ciudades1[2];
camino[2] = ciudades1[4];
camino[3] = ciudades1[3];
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMasBarato(ciudades1[0], ciudades1[3]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades1[0], ciudades1[3]));
ignorarOK = true;
Array<Cadena> ciudades2 = InicializarCiudades2(interfaz, true);
Array<Cadena> ciudades3 = InicializarCiudades3(interfaz, true);
ignorarOK = false;
//Mismo resultado
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMasBarato(ciudades1[0], ciudades1[3]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades1[0], ciudades1[3]));
camino = Array<Cadena>(3);
camino[0] = ciudades2[0];
camino[1] = ciudades2[2];
camino[2] = ciudades2[1];
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMasBarato(ciudades2[0], ciudades2[1]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades2[0], ciudades2[1]));
ignorarOK = true;
InicializarConexionesExtra(interfaz);
ignorarOK = false;
camino = Array<Cadena>(4);
camino[0] = ciudades1[0];
camino[1] = ciudades1[2];
camino[2] = ciudades1[4];
camino[3] = ciudades1[3];
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMasBarato(ciudades1[0], ciudades1[3]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades1[0], ciudades1[3]));
camino = Array<Cadena>(3);
camino[0] = ciudades2[0];
camino[1] = ciudades2[2];
camino[2] = ciudades2[1];
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMasBarato(ciudades2[0], ciudades2[1]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades2[0], ciudades2[1]));
//Cruzados
camino = Array<Cadena>(7);
camino[0] = ciudades1[0];
camino[1] = ciudades1[2];
camino[2] = ciudades1[4];
camino[3] = ciudades1[3];
camino[4] = ciudades2[0];
camino[5] = ciudades2[2];
camino[6] = ciudades2[1];
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMasBarato(ciudades1[0], ciudades2[1]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades1[0], ciudades2[1]));
CerrarSeccion();
}
void CasoDePrueba::Prueba3Ej2()
{
IniciarSeccion("Ejercicio Grafo 2 - CAmino Menor tiempo");
Puntero<Sistema> interfaz = InicializarSistema();
//No queremos que cuente los OK pq ya se probaron antes
ignorarOK = true;
Array<Cadena> ciudades1 = InicializarCiudades1(interfaz, true);
ignorarOK = false;
Cadena comentario = "Se verifica camino de menor tiempo entre '{0}-{1}'";
Tupla<TipoRetorno, Iterador<Cadena>> obtenido;
Tupla<TipoRetorno, Iterador<Cadena>> esperado(OK, nullptr);
Array<Cadena> camino;
camino = Array<Cadena>(4);
camino[0] = ciudades1[0];
camino[1] = ciudades1[2];
camino[2] = ciudades1[4];
camino[3] = ciudades1[3];
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMenorTiempo(ciudades1[0], ciudades1[3]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades1[0], ciudades1[3]));
ignorarOK = true;
Array<Cadena> ciudades2 = InicializarCiudades2(interfaz, true);
Array<Cadena> ciudades3 = InicializarCiudades3(interfaz, true);
InicializarConexionesExtra(interfaz);
ignorarOK = false;
camino = Array<Cadena>(4);
camino[0] = ciudades1[0];
camino[1] = ciudades1[2];
camino[2] = ciudades1[4];
camino[3] = ciudades1[3];
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMenorTiempo(ciudades1[0], ciudades1[3]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades1[0], ciudades1[3]));
//Cruzados
camino = Array<Cadena>(6);
camino[0] = ciudades1[0];
camino[1] = ciudades1[2];
camino[2] = ciudades1[4];
camino[3] = ciudades1[3];
camino[4] = ciudades2[2];
camino[5] = ciudades2[1];
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMenorTiempo(ciudades1[0], ciudades2[1]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades1[0], ciudades2[1]));
//Por mvd hay uno igual tiempo y costo
camino = Array<Cadena>(3);
camino[0] = ciudades1[0];
camino[1] = ciudades1[1];
camino[2] = ciudades3[2];
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMenorTiempo(ciudades1[0], ciudades3[2]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades1[0], ciudades3[2]));
CerrarSeccion();
}
void CasoDePrueba::Prueba4Ej2()
{
IniciarSeccion("Ejercicio Grafo 2 - CAmino Menos ciudades");
Puntero<Sistema> interfaz = InicializarSistema();
//No queremos que cuente los OK pq ya se probaron antes
ignorarOK = true;
Array<Cadena> ciudades1 = InicializarCiudades1(interfaz, true);
Array<Cadena> ciudades2 = InicializarCiudades2(interfaz, true);
Array<Cadena> ciudades3 = InicializarCiudades3(interfaz, true);
InicializarConexionesExtra(interfaz);
ignorarOK = false;
Cadena comentario = "Se verifica camino de menos ciudades entre '{0}-{1}'";
Tupla<TipoRetorno, Iterador<Cadena>> obtenido;
Tupla<TipoRetorno, Iterador<Cadena>> esperado(OK, nullptr);
Array<Cadena> camino;
camino = Array<Cadena>(2);
camino[0] = ciudades1[0];
camino[1] = ciudades1[3];
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMenosCiudades(ciudades1[0], ciudades1[3]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades1[0], ciudades1[3]));
camino = Array<Cadena>(3);
camino[0] = ciudades1[0];
camino[1] = ciudades1[3];
camino[2] = ciudades2[0];
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMenosCiudades(ciudades1[0], ciudades2[0]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades1[0], ciudades2[0]));
camino = Array<Cadena>(3);
camino[0] = ciudades1[0];
camino[1] = ciudades1[1];
camino[2] = ciudades3[2];
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMenosCiudades(ciudades1[0], ciudades3[2]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades1[0], ciudades3[2]));
CerrarSeccion();
}
void CasoDePrueba::Prueba5Ej2()
{
IniciarSeccion("Ejercicio Grafo 2 - CaminoMenosTrayectosOmnibus");
Puntero<Sistema> interfaz = InicializarSistema();
//No queremos que cuente los OK pq ya se probaron antes
ignorarOK = true;
Array<Cadena> ciudades1 = InicializarCiudades1(interfaz, true);
Array<Cadena> ciudades2 = InicializarCiudades2(interfaz, true);
Array<Cadena> ciudades3 = InicializarCiudades3(interfaz, true);
InicializarConexionesExtra(interfaz);
ignorarOK = false;
Cadena comentario = "Se verifica camino de menos trayecto omnibus entre '{0}-{1}'";
Tupla<TipoRetorno, Iterador<Cadena>> obtenido;
Tupla<TipoRetorno, Iterador<Cadena>> esperado(OK, nullptr);
Array<Cadena> camino;
camino = Array<Cadena>(2);
camino[0] = ciudades1[0];
camino[1] = ciudades1[3];
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMenosTrayectosOmnibus(ciudades1[0], ciudades1[3]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades1[0], ciudades1[3]));
CerrarSeccion();
}
void CasoDePrueba::Prueba6Ej2()
{
IniciarSeccion("Ejercicio Grafo 2 - CaminoMenosTrayectosAvion");
Puntero<Sistema> interfaz = InicializarSistema();
//No queremos que cuente los OK pq ya se probaron antes
ignorarOK = true;
Array<Cadena> ciudades1 = InicializarCiudades1(interfaz, true);
Array<Cadena> ciudades2 = InicializarCiudades2(interfaz, true);
Array<Cadena> ciudades3 = InicializarCiudades3(interfaz, true);
Verificar(interfaz->AltaConexion("Montevideo", "Durazno", OMNIBUS, 10, 10, 7), OK, "Se da de alta un trayecto auxiliar entre Montevideo Durazno");
InicializarConexionesExtra(interfaz);
ignorarOK = false;
Cadena comentario = "Se verifica camino de menos trayecto avion entre '{0}-{1}'";
Tupla<TipoRetorno, Iterador<Cadena>> obtenido;
Tupla<TipoRetorno, Iterador<Cadena>> esperado(OK, nullptr);
Array<Cadena> camino;
camino = Array<Cadena>(3);
camino[0] = ciudades1[0];
camino[1] = ciudades1[4];
camino[2] = ciudades1[3];
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMenosTrayectosAvion(ciudades1[0], ciudades1[3]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades1[0], ciudades1[3]));
camino = Array<Cadena>(2);
camino[0] = ciudades1[0];
camino[1] = ciudades3[0];
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMenosTrayectosAvion(ciudades1[0], ciudades3[0]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades1[0], ciudades3[0]));
CerrarSeccion();
}
void CasoDePrueba::Prueba7Ej2()
{
IniciarSeccion("Ejercicio Grafo 2 - CaminoMenosParadasIntermedias");
Puntero<Sistema> interfaz = InicializarSistema();
//No queremos que cuente los OK pq ya se probaron antes
ignorarOK = true;
Array<Cadena> ciudades1 = InicializarCiudades1(interfaz, true);
Array<Cadena> ciudades2 = InicializarCiudades2(interfaz, true);
Array<Cadena> ciudades3 = InicializarCiudades3(interfaz, true);
InicializarConexionesExtra(interfaz);
ignorarOK = false;
Cadena comentario = "Se verifica camino de menos paradas intermedias entre '{0}-{1}'";
Tupla<TipoRetorno, Iterador<Cadena>> obtenido;
Tupla<TipoRetorno, Iterador<Cadena>> esperado(OK, nullptr);
Array<Cadena> camino;
camino = Array<Cadena>(2);
camino[0] = ciudades1[0];
camino[1] = ciudades1[3];
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMenosParadasIntermedias(ciudades1[0], ciudades1[3]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades1[0], ciudades1[3]));
CerrarSeccion();
}
void CasoDePrueba::Prueba8Ej2()
{
IniciarSeccion("Ejercicio Grafo 2 - CaminoMasBaratoOminbus");
Puntero<Sistema> interfaz = InicializarSistema();
//No queremos que cuente los OK pq ya se probaron antes
ignorarOK = true;
Array<Cadena> ciudades1 = InicializarCiudades1(interfaz, true);
Array<Cadena> ciudades2 = InicializarCiudades2(interfaz, true);
Array<Cadena> ciudades3 = InicializarCiudades3(interfaz, true);
InicializarConexionesExtra(interfaz);
ignorarOK = false;
Cadena comentario = "Se verifica camino mas barato por omnibus entre '{0}-{1}'";
Tupla<TipoRetorno, Iterador<Cadena>> obtenido;
Tupla<TipoRetorno, Iterador<Cadena>> esperado(OK, nullptr);
Array<Cadena> camino;
camino = Array<Cadena>(4);
camino[0] = ciudades1[0];
camino[1] = ciudades1[2];
camino[2] = ciudades1[4];
camino[3] = ciudades1[3];
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMasBaratoOminbus(ciudades1[0], ciudades1[3]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades1[0], ciudades1[3]));
interfaz->AltaConexion(ciudades1[0], ciudades3[1], OMNIBUS, 420, 1000, 20);
//Por mvd-mald hay uno igual tiempo y costo
camino = Array<Cadena>(3);
camino[0] = ciudades1[0];
camino[1] = ciudades3[1];
camino[2] = ciudades3[2];
esperado.Dato2 = camino.ObtenerIterador();
obtenido = interfaz->CaminoMasBaratoOminbus(ciudades1[0], ciudades3[2]);
VerificarCamino(obtenido, esperado, comentario.DarFormato(ciudades1[0], ciudades3[2]));
CerrarSeccion();
} |
UKPLab/inlg2019-revisiting-binlin | binlin/model/nn_utils.py | import copy
import torch
from torch import nn as nn
def get_embed_matrix(vocab_size, embedding_dim, padding_idx):
return nn.Embedding(vocab_size, embedding_dim, padding_idx)
def get_gru_unit(gru_config):
return nn.GRU(input_size=gru_config['input_size'],
hidden_size=gru_config['hidden_size'],
dropout=gru_config.get('dropout', 0.0),
num_layers=gru_config.get('num_layers', 1),
bidirectional=gru_config.get('bidirectional', False))
def get_lstm_unit(lstm_config):
return nn.LSTM(input_size=lstm_config['input_size'],
hidden_size=lstm_config['hidden_size'],
dropout=lstm_config.get('dropout', 0.0),
num_layers=lstm_config.get('num_layers', 1),
bidirectional=lstm_config.get('bidirectional', False))
def get_bridge(encoder, decoder, bridge_type='dense'):
if bridge_type == 'dense':
# a dense layer which squeezes a bidirectional encoder state,
# from size (num_layers * num_directions, batch_size, hidden_size)
# to size (1, batch_size, hidden_size)
bridge_input_size = encoder._hidden_size * encoder._num_layers * encoder._num_directions
bridge = nn.Linear(bridge_input_size, decoder._hidden_size)
# we also need to define a bridging operation which will reshape the encoder state.
# so that we can feed it to the dense layer defined above
# the result of this reshaping operation is a tensor with size (batch_size, num_layers * num_directions * hidden_size)
bridge_reshape = lambda t: torch.transpose(t, 0, 1).contiguous().view(-1, bridge_input_size)
return bridge, bridge_reshape
# elif bridge_type == 'sum':
# bridge_input_size = encoder._hidden_size * encoder._num_layers * encoder._num_directions
# bridge_reshape = lambda t: torch.transpose(t, 0, 1).contiguous().view(-1, bridge_input_size)
# bridge = lambda t: torch.sum(t,)
else:
raise NotImplementedError()
def sum_bidirectional_outputs(outputs, rnn):
"""
:param outputs: SL x B x (enc_dim * num_directions)
"""
encoder_outputs_sum = outputs[:, :, :rnn.hidden_size] + \
outputs[:, :, rnn.hidden_size:]
return encoder_outputs_sum
def sum_bidirectional_state(hidden):
"""
:param hidden: (num_layers * num_directions) x B x enc_dim
:return:
"""
encoder_hidden_sum = torch.sum(hidden, 0).unsqueeze(0)
return encoder_hidden_sum
def add_bos_eos(seq, bos, eos):
new_seq = copy.deepcopy(seq)
return bos + new_seq + eos
def pad_seq(seq, max_len, pad_id):
padded_seq = seq + [pad_id] * (max_len - len(seq))
return padded_seq
def pad_attn(alignment_ids_seq, max_len):
new_seq = copy.deepcopy(alignment_ids_seq)
last_element = alignment_ids_seq[-1]
padded_alignment = new_seq + [last_element] * (max_len - len(alignment_ids_seq))
return padded_alignment
|
ChrisWC/MaterL | src/components/Material/CardGrid/Component.js | /****************************************************************************
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
import React, { PropTypes } from 'react';
import classNames from 'classnames';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import BarDecor from '../BarDecor';
/****************************************************************
****************************************************************/
class Component extends React.Component {
constructor(props) {
super(props);
this.state = {
style: {
},
active:false,
dirty:(this.props.value.length > 0)? true:false,
error:false,
value:this.props.value,
disabled:this.props.disabled,
incognito:false
}
}
static propTypes = {
};
static defaultProps = {
error:false,
valid:false,
required:false,
inset:false,
value:""
};
static contextTypes = {
palette: React.PropTypes.object,
theme: React.PropTypes.object
};
handleClick = (e) => {
this.setState({active:!this.state.active});
}
handleChange = (e, v) => {
if (this.state.disabled) {
return
}
this.setState({value: e.target.value, dirty:(e.target.value == "")? false:true})
if (this.props.onChange) {
this.props.onChange(e);
}
}
handleFocus = (e) => {
if (!this.state.disabled) {
this.setState({active:true})
}
//move floating hint text to top
}
handleBlur = (e) => {
this.setState({active:false})
}
render() {
//get container size
return (
<div>
{React.Children.map(this.props.children, (val, ind, arr) => {
return val;
})
</div>
);
}
}
export default Component;
|
mattvonrocketstein/ymir | ymir/api.py | <reponame>mattvonrocketstein/ymir
# -*- coding: utf-8 -*-
""" ymir.api
"""
import os
import re
import demjson
from fabric.colors import yellow
from voluptuous import Optional, Undefined
from ymir import util
from ymir.base import report as base_report
from ymir import schema as yschema
import jinja2
jinja_env = jinja2.Environment(undefined=jinja2.StrictUndefined)
guess_service_json_file = util.guess_service_json
class ReflectionError(Exception):
pass
def str_reflect(obj, ctx, simple=True):
""" when `simple` is true, lazy JIT params like host/username/pem need
not be resolved and certain errors are allowed
"""
pattern = r"'([A-Za-z0-9_\./\\-]*)'"
try:
return jinja_env.from_string(obj).render(**ctx)
except jinja2.UndefinedError as err:
lazy_keys = ['host', 'username', 'pem']
group = re.search(pattern, str(err)).group().replace("'", '')
if group in lazy_keys and simple:
return obj
else:
raise ReflectionError(
str(dict(
original_err=err,
group=group,
lazy_keys=lazy_keys,
simple=simple,)))
def list_reflect(lst, ctx, simple=True):
return [rreflect(obj, ctx, simple=simple) for obj in lst]
def dict_reflect(dct, ctx, simple=True):
return dict([[rreflect(k, ctx, simple=simple),
rreflect(v, ctx, simple=simple)]
for k, v in dct.items()])
def rreflect(obj, ctx, simple=True):
""" """
if isinstance(obj, basestring):
return str_reflect(obj, ctx, simple=simple)
elif isinstance(obj, list):
return list_reflect(obj, ctx, simple=simple)
elif isinstance(obj, dict):
return dict_reflect(obj, ctx, simple=simple)
else:
return obj
def _reflect(service_json=None, simple=True):
""" given a dictionary of service-json, reflects that data onto the service object"""
working = service_json.copy()
service_defaults = service_json.get('service_defaults', {})
working.update(**service_defaults)
# reflect toplevel service_json into itself
for k, v in working.items():
working[k] = rreflect(v, working)
out = dict([[k, v] for k, v in working.items() if k in service_json])
return out
def load_json(fname):
""" loads json and allows for
templating / value reflection
"""
if not os.path.exists(fname):
err = ("\nERROR: Service description file '{0}' not found.\n\n"
"Set the YMIR_SERVICE_JSON environment "
"variable and retry this operation.")
raise SystemExit(err.format(util.unexpand(fname)))
with open(fname) as fhandle:
tmp = demjson.decode(fhandle.read())
return tmp
def load_service_from_json(filename=None, quiet=False, die=True):
""" return a service object from ymir-style service.json file.
when filename is not given it will be guessed based on cwd.
"""
service_json_file = filename or util.get_or_guess_service_json_file(
insist=True)
# report('ymir.api', 'service.json is {0}'.format(
# util.unexpand(service_json_file)))
service_obj = _load_service_from_json_helper(
service_json_file=service_json_file,
service_json=load_json(service_json_file),
quiet=quiet, die=die)
# trigger the caching of some config values now,
# just to print the message as early as possible
service_obj._debug_mode
service_obj._supports_puppet
return service_obj
# this alias is frequently imported in
# fabfiles to avoid cluttering fabric namespace
_load_service_from_json = load_service_from_json
def set_schema_defaults(service_json, chosen_schema):
""" set default values for Optional() entries which are not provided """
service_json = service_json.copy()
defaults = [[str(k), k.default] for k in chosen_schema.schema.keys()
if type(k) == Optional]
defaults = filter(lambda x: not isinstance(x[1], Undefined), defaults)
defaults = dict(defaults)
for k, default in defaults.items():
if k not in service_json:
default = default() if callable(default) else default
service_json[k] = default
return service_json
EXTENSION_MAGIC = '__extension__'
def _load_service_from_json_helper(service_json_file=None,
service_json={}, quiet=False,
simple=False, die=True):
""" load service obj from service json """
from ymir import validation
report = util.NOOP if quiet else base_report
chosen_schema = yschema.choose_schema(service_json)
validation.validate(
service_json_file=service_json_file,
service_json=service_json,
schema=chosen_schema, simple=True, die=die)
if chosen_schema == yschema.extension_schema:
report('ymir.api', 'extension schema detected, resolving..')
extending = load_json(service_json["extends"])
extending.update(**service_json)
extending.pop("extends")
return _load_service_from_json_helper(
service_json_file=EXTENSION_MAGIC,
service_json=extending,
quiet=quiet, simple=simple, die=die)
report('ymir.api', 'chose schema: {0}'.format(
yellow(chosen_schema.schema_name)))
# report("ymir", "ymir service.json version:")
# report('ymir.api', 'loading service object from description')
service_json = set_schema_defaults(service_json, chosen_schema)
service_json = _reflect(service_json)
classname = str(service_json["name"])
BaseService = chosen_schema.get_service_class(service_json)
report('ymir.api', 'chose service class: {0}'.format(
yellow(BaseService.__name__)))
ServiceFromJSON = type(classname, (BaseService,),
dict(service_json_file=service_json_file))
obj = ServiceFromJSON(service_json_file=service_json_file)
obj._schema = chosen_schema
service_json = set_schema_defaults(service_json, chosen_schema)
ServiceFromJSON._service_json = service_json
return obj
|
Cwc-Lib/Cello | src/Type.c | #include "Cello.h"
static const char* Cast_Name(void) {
return "Cast";
}
static const char* Cast_Brief(void) {
return "Runtime Type Checking";
}
static const char* Cast_Description(void) {
return
"The `Cast` class provides a rudimentary run-time type checking. By "
"default it simply checks that the passed in object is of a given type "
"but it can be overridden by types which have to do more complex checking "
"to ensure the types are correct.";
}
static const char* Cast_Definition(void) {
return
"struct Cast {\n"
" var (*cast)(var, var);\n"
"};\n";
}
static struct Example* Cast_Examples(void) {
static struct Example examples[] = {
{
"Usage",
"var x = $I(100);\n"
"struct Int* y = cast(x, Int);\n"
"show(y);\n"
}, {NULL, NULL}
};
return examples;
}
static struct Method* Cast_Methods(void) {
static struct Method methods[] = {
{
"cast",
"var cast(var self, var type);",
"Ensures the object `self` is of the given `type` and returns it if it "
"is."
}, {NULL, NULL, NULL}
};
return methods;
}
var Cast = Cello(Cast, Instance(Doc,
Cast_Name, Cast_Brief, Cast_Description,
Cast_Definition, Cast_Examples, Cast_Methods));
var cast(var self, var type) {
struct Cast* c = instance(self, Cast);
if (c and c->cast) {
return c->cast(self, type);
}
if (type_of(self) is type) {
return self;
} else {
return throw(ValueError,
"cast expected type %s, got type %s", type_of(self), type);
}
}
static const char* Type_Name(void) {
return "Type";
}
static const char* Type_Brief(void) {
return "Metadata Object";
}
static const char* Type_Description(void) {
return
"The `Type` type is one of the most important types in Cello. It is the "
"object which specifies the meta-data associated with a particular object. "
"Most importantly this says what classes an object implements and what "
"their instances are."
"\n\n"
"One can get the type of an object using the `type_of` function."
"\n\n"
"To see if an object implements a class `implements` can be used. To "
"call a member of a class with an object `method` can be used."
"\n\n"
"To see if a type implements a class `type_implements` can be used. To "
"call a member of a class, implemented `type_method` can be used.";
}
static struct Example* Type_Examples(void) {
static struct Example examples[] = {
{
"Usage",
"var t = type_of($I(5));\n"
"show(t); /* Int */\n"
"\n"
"show($I(type_implements(t, New))); /* 1 */\n"
"show($I(type_implements(t, Cmp))); /* 1 */\n"
"show($I(type_implements(t, Hash))); /* 1 */\n"
"\n"
"show($I(type_method(t, Cmp, cmp, $I(5), $I(6))));\n"
}, {NULL, NULL}
};
return examples;
}
static struct Method* Type_Methods(void) {
static struct Method methods[] = {
{
"type_of",
"var type_of(var self);",
"Returns the `Type` of an object `self`."
}, {
"instance",
"var instance(var self, var cls);\n"
"var type_instance(var type, var cls);",
"Returns the instance of class `cls` implemented by object `self` or "
"type `type`. If class is not implemented then returns `NULL`."
}, {
"implements",
"bool implements(var self, var cls);\n"
"bool type_implements(var type, var cls);",
"Returns if the object `self` or type `type` implements the class `cls`."
}, {
"method",
"#define method(X, C, M, ...)\n"
"#define type_method(T, C, M, ...)",
"Returns the result of the call to method `M` of class `C` for object `X`"
"or type `T`. If class is not implemented then an error is thrown."
}, {
"implements_method",
"#define implements_method(X, C, M)\n"
"#define type_implements_method(T, C, M)",
"Returns if the type `T` or object `X` implements the method `M` of "
"class C."
}, {NULL, NULL, NULL}
};
return methods;
}
enum {
CELLO_NBUILTINS = 2 + (CELLO_CACHE_NUM / 3),
CELLO_MAX_INSTANCES = 256
};
static var Type_Alloc(void) {
struct Header* head = calloc(1,
sizeof(struct Header) +
sizeof(struct Type) *
(CELLO_NBUILTINS +
CELLO_MAX_INSTANCES + 1));
#if CELLO_MEMORY_CHECK == 1
if (head is NULL) {
throw(OutOfMemoryError, "Cannot create new 'Type', out of memory!");
}
#endif
return header_init(head, Type, AllocHeap);
}
static void Type_New(var self, var args) {
struct Type* t = self;
var name = get(args, $I(0));
var size = get(args, $I(1));
#if CELLO_MEMORY_CHECK == 1
if (len(args) - 2 > CELLO_MAX_INSTANCES) {
throw(OutOfMemoryError,
"Cannot construct 'Type' with %i instances, maximum is %i.",
$I(len(args)), $I(CELLO_MAX_INSTANCES));
}
#endif
size_t cache_entries = CELLO_CACHE_NUM / 3;
for (size_t i = 0; i < cache_entries; i++) {
t[i] = (struct Type){ NULL, NULL, NULL };
}
t[cache_entries+0] = (struct Type){ NULL, "__Name", (var)c_str(name) };
t[cache_entries+1] = (struct Type){ NULL, "__Size", (var)(uintptr_t)c_int(size) };
for(size_t i = 2; i < len(args); i++) {
var ins = get(args, $I(i));
t[CELLO_NBUILTINS-2+i] = (struct Type){
NULL, (var)c_str(type_of(ins)), ins };
}
t[CELLO_NBUILTINS+len(args)-2] = (struct Type){ NULL, NULL, NULL };
}
static char* Type_Builtin_Name(struct Type* t) {
return t[(CELLO_CACHE_NUM / 3)+0].inst;
}
static size_t Type_Builtin_Size(struct Type* t) {
return (size_t)t[(CELLO_CACHE_NUM / 3)+1].inst;
}
static int Type_Show(var self, var output, int pos) {
return format_to(output, pos, "%s", Type_Builtin_Name(self));
}
static int Type_Cmp(var self, var obj) {
struct Type* objt = cast(obj, Type);
return strcmp(Type_Builtin_Name(self), Type_Builtin_Name(objt));
}
static uint64_t Type_Hash(var self) {
const char* name = Type_Builtin_Name(self);
return hash_data(name, strlen(name));
}
static char* Type_C_Str(var self) {
return Type_Builtin_Name(self);
}
static void Type_Assign(var self, var obj) {
throw(ValueError, "Type objects cannot be assigned.");
}
static var Type_Copy(var self) {
return throw(ValueError, "Type objects cannot be copied.");
}
static int print_indent(var out, int pos, const char* str) {
pos = print_to(out, pos, " ");
while (*str) {
if (*str is '\n') { pos = print_to(out, pos, "\n "); }
else { pos = print_to(out, pos, "%c", $I(*str)); }
str++;
}
return pos;
}
static int Type_Help_To(var self, var out, int pos) {
struct Doc* doc = type_instance(self, Doc);
if (doc is NULL) {
return print_to(out, pos, "\nNo Documentation Found for Type %s\n", self);
}
pos = print_to(out, pos, "\n");
pos = print_to(out, pos, "# %s ", self);
if (doc->brief) {
pos = print_to(out, pos, " - %s\n\n", $S((char*)doc->brief()));
}
if (doc->description) {
pos = print_to(out, pos, "%s\n\n", $S((char*)doc->description()));
}
if (doc->definition) {
pos = print_to(out, pos, "\n### Definition\n\n");
pos = print_indent(out, pos, doc->definition());
pos = print_to(out, pos, "\n\n");
}
if (doc->methods) {
pos = print_to(out, pos, "\n### Methods\n\n");
struct Method* methods = doc->methods();
while (methods[0].name) {
pos = print_to(out, pos, "__%s__\n\n", $S((char*)methods[0].name));
pos = print_indent(out, pos, methods[0].definition);
pos = print_to(out, pos, "\n\n%s\n\n", $S((char*)methods[0].description));
methods++;
}
}
if (doc->examples) {
pos = print_to(out, pos, "\n### Examples\n\n");
struct Example* examples = doc->examples();
while (examples[0].name) {
pos = print_to(out, pos, "__%s__\n\n", $S((char*)examples[0].name));
pos = print_indent(out, pos, examples[0].body);
pos = print_to(out, pos, "\n\n");
examples++;
}
pos = print_to(out, pos, "\n\n");
}
return pos;
}
var Type = CelloEmpty(Type,
Instance(Doc,
Type_Name, Type_Brief, Type_Description, NULL, Type_Examples, Type_Methods),
Instance(Assign, Type_Assign),
Instance(Copy, Type_Copy),
Instance(Alloc, Type_Alloc, NULL),
Instance(New, Type_New, NULL),
Instance(Cmp, Type_Cmp),
Instance(Hash, Type_Hash),
Instance(Show, Type_Show, NULL),
Instance(C_Str, Type_C_Str),
Instance(Help, Type_Help_To));
static var Type_Scan(var self, var cls) {
#if CELLO_METHOD_CHECK == 1
if (type_of(self) isnt Type) {
return throw(TypeError, "Method call got non type '%s'", type_of(self));
}
#endif
struct Type* t;
t = (struct Type*)self + CELLO_NBUILTINS;
while (t->name) { if (t->cls is cls) { return t->inst; } t++; }
t = (struct Type*)self + CELLO_NBUILTINS;
while (t->name) {
if (strcmp(t->name, Type_Builtin_Name(cls)) is 0) {
t->cls = cls;
return t->inst;
}
t++;
}
return NULL;
}
static bool Type_Implements(var self, var cls) {
return Type_Scan(self, cls) isnt NULL;
}
bool type_implements(var self, var cls) {
return Type_Implements(self, cls);
}
static var Type_Instance(var self, var cls);
static var Type_Method_At_Offset(
var self, var cls, size_t offset, const char* method_name) {
var inst = Type_Instance(self, cls);
#if CELLO_METHOD_CHECK == 1
if (inst is NULL) {
return throw(ClassError,
"Type '%s' does not implement class '%s'",
self, cls);
}
#endif
#if CELLO_METHOD_CHECK == 1
var meth = *((var*)(((char*)inst) + offset));
if (meth is NULL) {
return throw(ClassError,
"Type '%s' implements class '%s' but not the method '%s' required",
self, cls, $(String, (char*)method_name));
}
#endif
return inst;
}
var type_method_at_offset(
var self, var cls, size_t offset, const char* method_name) {
return Type_Method_At_Offset(self, cls, offset, method_name);
}
static bool Type_Implements_Method_At_Offset(var self, var cls, size_t offset) {
var inst = Type_Scan(self, cls);
if (inst is NULL) { return false; }
var meth = *((var*)(((char*)inst) + offset));
if (meth is NULL) { return false; }
return true;
}
bool type_implements_method_at_offset(var self, var cls, size_t offset) {
return Type_Implements_Method_At_Offset(self, cls, offset);
}
/*
** Doing the lookup of a class instances is fairly fast
** but still too slow to be done inside a tight inner loop.
** This is because there could be any number of instances
** and they could be in any order, so each time a linear
** search must be done to find the correct instance.
**
** We can remove the need for a linear search by placing
** some common class instances at known locations. These
** are the _Type Cache Entries_ and are located at some
** preallocated space at the beginning of every type object.
**
** The only problem is that these instances are not filled
** at compile type, so we must dynamically fill them if they
** are empty. But this can be done with a standard call to
** `Type_Scan` the first time.
**
** The main advantage of this method is that it gives the compiler
** a better chance of inlining the code up to the call of the
** instance function pointer, and removes the overhead
** associated with setting up the call to `Type_Scan` which is
** too complex a call to be effectively inlined.
**
*/
#define Type_Cache_Entry(i, lit) \
if (cls is lit) { \
var inst = ((var*)self)[i]; \
if (inst is NULL) { \
inst = Type_Scan(self, lit); \
((var*)self)[i] = inst; \
} \
return inst; \
}
static var Type_Instance(var self, var cls) {
#if CELLO_CACHE == 1
Type_Cache_Entry( 0, Size); Type_Cache_Entry( 1, Alloc);
Type_Cache_Entry( 2, New); Type_Cache_Entry( 3, Assign);
Type_Cache_Entry( 4, Cmp); Type_Cache_Entry( 5, Mark);
Type_Cache_Entry( 6, Hash); Type_Cache_Entry( 7, Len);
Type_Cache_Entry( 8, Iter); Type_Cache_Entry( 9, Push);
Type_Cache_Entry(10, Concat); Type_Cache_Entry(11, Get);
Type_Cache_Entry(12, C_Str); Type_Cache_Entry(13, C_Int);
Type_Cache_Entry(14, C_Float); Type_Cache_Entry(15, Current);
Type_Cache_Entry(16, Cast); Type_Cache_Entry(17, Pointer);
#endif
return Type_Scan(self, cls);
}
#undef Type_Cache_Entry
var type_instance(var self, var cls) {
return Type_Instance(self, cls);
}
static var Type_Of(var self) {
/*
** The type of a Type object is just `Type` again. But because `Type` is
** extern it isn't a constant expression. This means it cannot be set at
** compile time.
**
** But we really want to be able to construct types statically. So by
** convention at compile time the type of a Type object is set to `NULL`.
** So if we access a statically allocated object and it tells us `NULL`
** is the type, we assume the type is `Type`.
*/
#if CELLO_NULL_CHECK == 1
if (self is NULL) {
return throw(ValueError, "Received NULL as value to 'type_of'");
}
#endif
struct Header* head =
(struct Header*)((char*)self - sizeof(struct Header));
#if CELLO_MAGIC_CHECK == 1
if (head->magic is (var)0xDeadCe110) {
throw(ValueError, "Pointer '%p' passed to 'type_of' "
"has bad magic number, it looks like it was already deallocated.", self);
}
if (head->magic isnt ((var)CELLO_MAGIC_NUM)) {
throw(ValueError, "Pointer '%p' passed to 'type_of' "
"has bad magic number, perhaps it wasn't allocated by Cello.", self);
}
#endif
if (head->type is NULL) { head->type = Type; }
return head->type;
}
var type_of(var self) {
return Type_Of(self);
}
var instance(var self, var cls) {
return Type_Instance(Type_Of(self), cls);
}
bool implements(var self, var cls) {
return Type_Implements(Type_Of(self), cls);
}
var method_at_offset(
var self, var cls, size_t offset, const char* method_name) {
return Type_Method_At_Offset(Type_Of(self), cls, offset, method_name);
}
bool implements_method_at_offset(var self, var cls, size_t offset) {
return Type_Implements_Method_At_Offset(Type_Of(self), cls, offset);
}
static const char* Size_Name(void) {
return "Size";
}
static const char* Size_Brief(void) {
return "Type Size";
}
static const char* Size_Description(void) {
return
"The `Size` class is a very important class in Cello because it gives the "
"size in bytes you can expect an object of a given type to be. This is "
"used by many methods to allocate, assign, or compare various objects."
"\n\n"
"By default this size is automatically found and recorded by the `Cello` "
"macro, but if the type does it's own allocation, or the size cannot be "
"found naturally then it may be necessary to override this method.";
}
static const char* Size_Definition(void) {
return
"struct Size {\n"
" size_t (*size)(void);\n"
"};\n";
}
static struct Example* Size_Examples(void) {
static struct Example examples[] = {
{
"Usage",
"show($I(size(Int)));\n"
"show($I(size(Float)));\n"
"show($I(size(Array)));\n"
}, {NULL, NULL}
};
return examples;
}
static struct Method* Size_Methods(void) {
static struct Method methods[] = {
{
"size",
"size_t size(var type);",
"Returns the associated size of a given `type` in bytes."
}, {NULL, NULL, NULL}
};
return methods;
}
var Size = Cello(Size, Instance(Doc,
Size_Name, Size_Brief, Size_Description,
Size_Definition, Size_Examples, Size_Methods));
size_t size(var type) {
struct Size* s = type_instance(type, Size);
if (s and s->size) {
return s->size();
}
return Type_Builtin_Size(type);
}
|
chriskim06/go-sdk | db/migration/guards.go | /*
Copyright (c) 2021 - Present. Blend Labs, Inc. All rights reserved
Use of this source code is governed by a MIT license that can be found in the LICENSE file.
*/
package migration
import (
"context"
"database/sql"
"github.com/blend/go-sdk/db"
)
// GuardFunc is a control for migration steps.
// It should internally evaluate if the action should be called.
// The action is typically given separately so these two components can be composed.
type GuardFunc func(context.Context, *db.Connection, *sql.Tx, Action) error
// GuardPredicateFunc is a function that can act as a guard
type GuardPredicateFunc func(context.Context, *db.Connection, *sql.Tx) (bool, error)
// --------------------------------------------------------------------------------
// Guards
// --------------------------------------------------------------------------------
// Guard returns a function that determines if a step in a group should run.
func Guard(description string, predicate GuardPredicateFunc) GuardFunc {
return func(ctx context.Context, c *db.Connection, tx *sql.Tx, step Action) error {
proceed, err := predicate(ctx, c, tx)
if err != nil {
if suite := GetContextSuite(ctx); suite != nil {
return suite.Error(WithLabel(ctx, description), err)
}
return err
}
if !proceed {
if suite := GetContextSuite(ctx); suite != nil {
suite.Skipf(ctx, description)
}
return nil
}
err = step.Action(ctx, c, tx)
if err != nil {
if suite := GetContextSuite(ctx); suite != nil {
return suite.Error(WithLabel(ctx, description), err)
}
return err
}
if suite := GetContextSuite(ctx); suite != nil {
suite.Applyf(ctx, description)
}
return nil
}
}
// guardPredicate wraps a predicate in a GuardFunc
func guardPredicate(description string, p predicate, arg1 string) GuardFunc {
return Guard(description, func(ctx context.Context, c *db.Connection, tx *sql.Tx) (bool, error) {
return p(ctx, c, tx, arg1)
})
}
// guardNotPredicate inverts a predicate, and wraps that in a GuardFunc
func guardNotPredicate(description string, p predicate, arg1 string) GuardFunc {
return Guard(description, func(ctx context.Context, c *db.Connection, tx *sql.Tx) (bool, error) {
return Not(p(ctx, c, tx, arg1))
})
}
// guardPredicate2 wraps a predicate2 in a GuardFunc
func guardPredicate2(description string, p predicate2, arg1, arg2 string) GuardFunc {
return Guard(description, func(ctx context.Context, c *db.Connection, tx *sql.Tx) (bool, error) {
return p(ctx, c, tx, arg1, arg2)
})
}
// guardNotPredicate2 inverts a predicate2, and wraps that in a GuardFunc
func guardNotPredicate2(description string, p predicate2, arg1, arg2 string) GuardFunc {
return Guard(description, func(ctx context.Context, c *db.Connection, tx *sql.Tx) (bool, error) {
return Not(p(ctx, c, tx, arg1, arg2))
})
}
// guardPredicate3 wraps a predicate3 in a GuardFunc
func guardPredicate3(description string, p predicate3, arg1, arg2, arg3 string) GuardFunc {
return Guard(description, func(ctx context.Context, c *db.Connection, tx *sql.Tx) (bool, error) {
return p(ctx, c, tx, arg1, arg2, arg3)
})
}
// guardNotPredicate3 inverts a predicate3, and wraps that in a GuardFunc
func guardNotPredicate3(description string, p predicate3, arg1, arg2, arg3 string) GuardFunc {
return Guard(description, func(ctx context.Context, c *db.Connection, tx *sql.Tx) (bool, error) {
return Not(p(ctx, c, tx, arg1, arg2, arg3))
})
}
// predicate is a function that evaluates based on a string param.
type predicate func(context.Context, *db.Connection, *sql.Tx, string) (bool, error)
// predicate2 is a function that evaluates based on two string params.
type predicate2 func(context.Context, *db.Connection, *sql.Tx, string, string) (bool, error)
// predicate3 is a function that evaluates based on three string params.
type predicate3 func(context.Context, *db.Connection, *sql.Tx, string, string, string) (bool, error)
|
isabella232/spring-data-geode | spring-data-geode/src/main/java/org/springframework/data/gemfire/GemfireUtils.java | /*
* Copyright 2010-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.gemfire;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.internal.GemFireVersion;
import org.w3c.dom.Element;
import org.springframework.data.gemfire.config.support.GemfireFeature;
import org.springframework.data.gemfire.util.RegionUtils;
import org.springframework.util.ClassUtils;
/**
* {@link GemfireUtils} is an abstract utility class encapsulating common functionality for accessing features
* and capabilities of Apache Geode based on version as well as other configuration meta-data.
*
* @author <NAME>
* @see org.apache.geode.cache.CacheFactory
* @see org.apache.geode.internal.GemFireVersion
* @see org.springframework.data.gemfire.config.support.GemfireFeature
* @see org.springframework.data.gemfire.util.RegionUtils
* @since 1.3.3
*/
@SuppressWarnings("unused")
public abstract class GemfireUtils extends RegionUtils {
public final static String APACHE_GEODE_NAME = "Apache Geode";
public final static String GEMFIRE_NAME = apacheGeodeProductName();
public final static String GEMFIRE_VERSION = apacheGeodeVersion();
public final static String UNKNOWN = "unknown";
private static final String ASYNC_EVENT_QUEUE_ELEMENT_NAME = "async-event-queue";
private static final String ASYNC_EVENT_QUEUE_TYPE_NAME = "org.apache.geode.cache.asyncqueue.AsyncEventQueue";
private static final String CQ_ELEMENT_NAME = "cq-listener-container";
private static final String CQ_TYPE_NAME = "org.apache.geode.cache.query.CqQuery";
private static final String GATEWAY_RECEIVER_ELEMENT_NAME = "gateway-receiver";
private static final String GATEWAY_RECEIVER_TYPE_NAME = "org.apache.geode.cache.wan.GatewayReceiverFactory";
private static final String GATEWAY_SENDER_ELEMENT_NAME = "gateway-sender";
private static final String GATEWAY_SENDER_TYPE_NAME = "org.apache.geode.cache.wan.GatewaySenderFactory";
public static String apacheGeodeProductName() {
try {
return GemFireVersion.getProductName();
}
catch (Throwable ignore) {
return APACHE_GEODE_NAME;
}
}
public static String apacheGeodeVersion() {
try {
return CacheFactory.getVersion();
}
catch (Throwable ignore) {
return UNKNOWN;
}
}
public static boolean isClassAvailable(String fullyQualifiedClassName) {
return ClassUtils.isPresent(fullyQualifiedClassName, GemfireUtils.class.getClassLoader());
}
public static boolean isGemfireFeatureAvailable(GemfireFeature feature) {
boolean featureAvailable = (!GemfireFeature.AEQ.equals(feature) || isAsyncEventQueueAvailable());
featureAvailable &= (!GemfireFeature.CONTINUOUS_QUERY.equals(feature) || isContinuousQueryAvailable());
featureAvailable &= (!GemfireFeature.WAN.equals(feature) || isGatewayAvailable());
return featureAvailable;
}
public static boolean isGemfireFeatureAvailable(Element element) {
boolean featureAvailable = (!isAsyncEventQueue(element) || isAsyncEventQueueAvailable());
featureAvailable &= (!isContinuousQuery(element) || isContinuousQueryAvailable());
featureAvailable &= (!isGateway(element) || isGatewayAvailable());
return featureAvailable;
}
public static boolean isGemfireFeatureUnavailable(GemfireFeature feature) {
return !isGemfireFeatureAvailable(feature);
}
public static boolean isGemfireFeatureUnavailable(Element element) {
return !isGemfireFeatureAvailable(element);
}
private static boolean isAsyncEventQueue(Element element) {
return ASYNC_EVENT_QUEUE_ELEMENT_NAME.equals(element.getLocalName());
}
private static boolean isAsyncEventQueueAvailable() {
return isClassAvailable(ASYNC_EVENT_QUEUE_TYPE_NAME);
}
private static boolean isContinuousQuery(Element element) {
return CQ_ELEMENT_NAME.equals(element.getLocalName());
}
private static boolean isContinuousQueryAvailable() {
return isClassAvailable(CQ_TYPE_NAME);
}
private static boolean isGateway(Element element) {
String elementLocalName = element.getLocalName();
return (GATEWAY_RECEIVER_ELEMENT_NAME.equals(elementLocalName)
|| GATEWAY_SENDER_ELEMENT_NAME.equals(elementLocalName));
}
private static boolean isGatewayAvailable() {
return isClassAvailable(GATEWAY_SENDER_TYPE_NAME);
}
public static void main(final String... args) {
System.out.printf("Product Name [%1$s] Version [%2$s]%n", GEMFIRE_NAME, GEMFIRE_VERSION);
}
}
|
BookCrossingTeam/BookCrossingAPP | app/src/main/java/com/example/administrator/bookcrossingapp/fragment/ReviewsArticleFragment.java | package com.example.administrator.bookcrossingapp.fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.administrator.bookcrossingapp.R;
import com.example.administrator.bookcrossingapp.activity.ShareListActivity;
import com.example.administrator.bookcrossingapp.datamodel.BookDetail;
import com.example.administrator.bookcrossingapp.datamodel.ReviewItem;
import com.example.administrator.bookcrossingapp.adapter.ReviewItemAdapter;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* @author Lyh
*/
public class ReviewsArticleFragment extends Fragment {
private View view;
private ReviewItemAdapter adapter;
private int userid;
private List<ReviewItem> reviewlist = new ArrayList<>();
public ReviewsArticleFragment() {
super();
}
//创建newInstance方法的方法来向fragment传递参数(注意这个方法是属于类方法)
public static final ReviewsArticleFragment newInstance(int userid){
ReviewsArticleFragment fragment = new ReviewsArticleFragment();
Bundle bundle = new Bundle();
bundle.putInt("userid",userid);
fragment.setArguments(bundle);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userid =getArguments().getInt("userid");
//initReviewListTest();
initReviewList();
}
private void initReviewList(){
//从服务器端获取数据
new Thread(new Runnable() {
@Override
public void run() {
//发送请求
try {
OkHttpClient client = new OkHttpClient();
//不懂这里为什么要加“”
//获取当前时间(毫秒)
long lastTime = System.currentTimeMillis();
RequestBody requestBody = new FormBody.Builder()
.add("userid",userid+"")
.add("lastTime", lastTime+"").build();
Request request = new Request.Builder().url("http://172.16.17.32/Book/APP/reviewAll").post(requestBody).build();
Response response = client.newCall(request).execute();
Log.i("testtttttttttttt",response.toString());
if(response.isSuccessful()){
// getActivity().runOnUiThread(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(getActivity(), "成功连接服务器!", Toast.LENGTH_SHORT).show();
// }
// });
String responseData = response.body().string();
handleResponseData(responseData);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
adapter.notifyDataSetChanged();
}
});
}
} catch (IOException e) {
e.printStackTrace();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), "服务器开小差啦", Toast.LENGTH_SHORT).show();
}
});
}
}
}
}).start();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_reviews, container, false);
initReviewListRecyclerView();
return view;
}
private void initReviewListRecyclerView() {
RecyclerView recyclerView = view.findViewById(R.id.reviews_article_recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
adapter = new ReviewItemAdapter(reviewlist, getContext(), getActivity());
recyclerView.setAdapter(adapter);
}
public void handleResponseData(final String responseData) {
try {
JSONArray jsonArray = new JSONArray(responseData);
for (int i = jsonArray.length()-1; i >= 0; i--) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int articleId = Integer.parseInt(jsonObject.getString("id"));
String title = jsonObject.getString("title");
String author = jsonObject.getString("username");
String coverImgUrl = jsonObject.getString("coverImgUrl");
int likeAmount = Integer.parseInt(jsonObject.getString("likeAmount"));
int isLike;
if( jsonObject.getString("userId").equals("isNotLike")){
//表明该item没有被该用户点赞(注意,java的字符串比较是equals函数!)
isLike = 0;
}
else isLike = 1;
ReviewItem reviewItem = new ReviewItem();
reviewItem.setArticleId(articleId);
reviewItem.setTitle(title);
reviewItem.setAuthor(author);
reviewItem.setCoverImgUrl(coverImgUrl);
reviewItem.setLikeAmount(likeAmount);
reviewItem.setIsLike(isLike);
reviewlist.add(reviewItem);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
johsteffens/beth | lib/bmath/bmath_quicktypes_list.h | /** List of predefined types for quick access.
* Created via bmath_quicktypes_to_stdout( NULL );
*/
#define TYPEOF_bmath_arr_grt_f2_s 0x52F7E9BA63D022AAull
#define TYPEOF_bmath_arr_grt_f3_s 0x5DAD02BA6A753825ull
#define TYPEOF_bmath_arr_mf2_s 0xCE12553698D40859ull
#define TYPEOF_bmath_arr_mf3_s 0xC6C33C3695121BDEull
#define TYPEOF_bmath_arr_mfx_eval_s 0xCC0F91F8A136DAA2ull
#define TYPEOF_bmath_arr_vf2_s 0xCCFCFE22B87B4F88ull
#define TYPEOF_bmath_arr_vf3_s 0xD7B21722BF206503ull
#define TYPEOF_bmath_cf2_s 0x61747E7231FC9A6Full
#define TYPEOF_bmath_cf3_s 0x579965722C1128B4ull
#define TYPEOF_bmath_estimator_s 0xBE81A2C3F3C02220ull
#define TYPEOF_bmath_fp_f3_ar0 0xEB12C610F5362E8Aull
#define TYPEOF_bmath_fp_f3_ar1 0xEB12C710F536303Dull
#define TYPEOF_bmath_fp_f3_ar2 0xEB12C410F5362B24ull
#define TYPEOF_bmath_fp_f3_op_ar0 0x4DFCADA58D9C182Cull
#define TYPEOF_bmath_fp_f3_op_ar1 0x4DFCAEA58D9C19DFull
#define TYPEOF_bmath_fp_f3_op_ar2 0x4DFCAFA58D9C1B92ull
#define TYPEOF_bmath_fp_mf2_s_av 0x4A6DCD69BC6CEAD2ull
#define TYPEOF_bmath_fp_mf2_s_cld 0xF47502AB34E13D3Eull
#define TYPEOF_bmath_fp_mf2_s_evd_htp 0x896CCFF28AF25B7Dull
#define TYPEOF_bmath_fp_mf2_s_hsm_piv 0x2E790DEC03AACA27ull
#define TYPEOF_bmath_fp_mf2_s_htp_mul 0x08623516051E54E6ull
#define TYPEOF_bmath_fp_mf2_s_htp_mul_htp 0x15A25EC01909F0B5ull
#define TYPEOF_bmath_fp_mf2_s_inv 0x2A0BF6AB53B08C4Cull
#define TYPEOF_bmath_fp_mf2_s_lbd 0x555BE7AB6C397021ull
#define TYPEOF_bmath_fp_mf2_s_lqd 0x5595B5AB6C6A9372ull
#define TYPEOF_bmath_fp_mf2_s_lud 0x5587D5AB6C5E8C76ull
#define TYPEOF_bmath_fp_mf2_s_mul 0x4AC5B6AB65AEE26Dull
#define TYPEOF_bmath_fp_mf2_s_mul_htp 0x965A6C80F58D5B0Eull
#define TYPEOF_bmath_fp_mf2_s_pdf_inv 0xB25018CD95AAC321ull
#define TYPEOF_bmath_fp_mf2_s_piv 0x63CA57AAE3AC0728ull
#define TYPEOF_bmath_fp_mf2_s_pmt_lqd 0x9FC669ED92CD3974ull
#define TYPEOF_bmath_fp_mf2_s_qrd 0x58BA30AADCBA2E36ull
#define TYPEOF_bmath_fp_mf2_s_qrd_pmt 0x472BA64917D0D4B0ull
#define TYPEOF_bmath_fp_mf2_s_svd 0x6ACB7EAAE72BEA1Cull
#define TYPEOF_bmath_fp_mf2_s_trd 0x8467FFAAF591B9C9ull
#define TYPEOF_bmath_fp_mf2_s_trd_htp 0xBB7ACC5E3AD30E4Aull
#define TYPEOF_bmath_fp_mf2_s_ua 0x4A44D069BC49EAD7ull
#define TYPEOF_bmath_fp_mf2_s_uau 0x7CD8C5AAF199B146ull
#define TYPEOF_bmath_fp_mf2_s_uav 0x7CD8C4AAF199AF93ull
#define TYPEOF_bmath_fp_mf2_s_ubd 0x7CDCC4AAF19D986Aull
#define TYPEOF_bmath_fp_mf2_s_vav 0x95F54DAAFF93C4EEull
#define TYPEOF_bmath_fp_mf3_s_av 0xE1659A8595CE944Full
#define TYPEOF_bmath_fp_mf3_s_cld 0xDCB52DFD956B7161ull
#define TYPEOF_bmath_fp_mf3_s_evd_htp 0x3918E584C018A46Eull
#define TYPEOF_bmath_fp_mf3_s_hsm_piv 0xD9A65527CC52F478ull
#define TYPEOF_bmath_fp_mf3_s_htp_mul 0x598A0238EF9429B5ull
#define TYPEOF_bmath_fp_mf3_s_htp_mul_htp 0xF02DE9437C34CD36ull
#define TYPEOF_bmath_fp_mf3_s_inv 0x133411FDB500865Bull
#define TYPEOF_bmath_fp_mf3_s_lbd 0x2C726CFDC31733F2ull
#define TYPEOF_bmath_fp_mf3_s_lqd 0x2C389EFDC2E610A1ull
#define TYPEOF_bmath_fp_mf3_s_lud 0x2C2A8EFDC2D9B815ull
#define TYPEOF_bmath_fp_mf3_s_mul 0x3387BDFDC6A8074Eull
#define TYPEOF_bmath_fp_mf3_s_mul_htp 0x0B4AF250675BCC3Dull
#define TYPEOF_bmath_fp_mf3_s_pdf_inv 0x9D3F1ED8F8FFE142ull
#define TYPEOF_bmath_fp_mf3_s_piv 0x3A0110FD39CC13E7ull
#define TYPEOF_bmath_fp_mf3_s_pmt_lqd 0x10817993E9AD040Full
#define TYPEOF_bmath_fp_mf3_s_qrd 0x41753BFD3DAD3B35ull
#define TYPEOF_bmath_fp_mf3_s_qrd_pmt 0x8A19A7DF9713ACE3ull
#define TYPEOF_bmath_fp_mf3_s_svd 0x53BC99FD484CA1BBull
#define TYPEOF_bmath_fp_mf3_s_trd 0x5B11C4FD4C13187Aull
#define TYPEOF_bmath_fp_mf3_s_trd_htp 0xE9A7FE8DC4A63AD9ull
#define TYPEOF_bmath_fp_mf3_s_ua 0xE13CBF8595ABCE1Aull
#define TYPEOF_bmath_fp_mf3_s_uau 0x6607DEFD52EFC69Dull
#define TYPEOF_bmath_fp_mf3_s_uav 0x6607DBFD52EFC184ull
#define TYPEOF_bmath_fp_mf3_s_ubd 0x6603BFFD52EBA919ull
#define TYPEOF_bmath_fp_mf3_s_vav 0x6D0506FD566BC26Dull
#define TYPEOF_bmath_group 0xE16B10A21D903F93ull
#define TYPEOF_bmath_group_s 0x63F9204E24447255ull
#define TYPEOF_bmath_grt_f2_s 0xE637059CABD70C4Eull
#define TYPEOF_bmath_grt_f3_s 0xEE5F1E9CB050E989ull
#define TYPEOF_bmath_matrix 0x25E510035C004129ull
#define TYPEOF_bmath_matrix_s 0x2D60B61E7902DA83ull
#define TYPEOF_bmath_mf2_s 0x3E275DB6F92BB6D5ull
#define TYPEOF_bmath_mf3_s 0x344C44B6F340451Aull
#define TYPEOF_bmath_mfx_eval_result_s 0x8F6452678565A6BAull
#define TYPEOF_bmath_mfx_eval_s 0xDE985D880AB9DC86ull
#define TYPEOF_bmath_plot 0x98DA44617E51FFDFull
#define TYPEOF_bmath_plot_s 0x38A7D643EFB12EE9ull
#define TYPEOF_bmath_pmt_s 0x981988B03CA37BF3ull
#define TYPEOF_bmath_ring 0x3CF0B66E6BAB252Aull
#define TYPEOF_bmath_ring_s 0x4279837E4B899E74ull
#define TYPEOF_bmath_u2_argb_from_f3 0x532C6E6F818AEC87ull
#define TYPEOF_bmath_vcf2_s 0x42F35B6E7A2BC091ull
#define TYPEOF_bmath_vcf3_s 0x3918226E74401876ull
#define TYPEOF_bmath_vector 0x38A11950400898FFull
#define TYPEOF_bmath_vector_s 0x548F29B311F5CEC9ull
#define TYPEOF_bmath_vf2_s 0x0FC2A93CCE88DAD4ull
#define TYPEOF_bmath_vf3_s 0x17EAC23CD302B80Full
|
ewie/activej | core-serializer/src/main/java/io/activej/serializer/util/RecordSerializer.java | package io.activej.serializer.util;
import io.activej.codegen.util.WithInitializer;
import io.activej.record.Record;
import io.activej.record.RecordScheme;
import io.activej.serializer.BinaryInput;
import io.activej.serializer.BinaryOutput;
import io.activej.serializer.BinarySerializer;
import io.activej.serializer.CorruptedDataException;
public final class RecordSerializer implements BinarySerializer<Record>, WithInitializer<RecordSerializer> {
private final RecordScheme scheme;
private final BinarySerializer<?>[] fieldSerializers;
private RecordSerializer(RecordScheme scheme) {
this.scheme = scheme;
this.fieldSerializers = new BinarySerializer[scheme.size()];
}
public static RecordSerializer create(RecordScheme scheme) {
return new RecordSerializer(scheme);
}
public RecordSerializer withField(String field, BinarySerializer<?> fieldSerializer) {
this.fieldSerializers[scheme.getFieldIndex(field)] = fieldSerializer;
return this;
}
@Override
public void encode(BinaryOutput out, Record record) {
for (int i = 0; i < fieldSerializers.length; i++) {
//noinspection unchecked
BinarySerializer<Object> serializer = (BinarySerializer<Object>) fieldSerializers[i];
serializer.encode(out, record.get(i));
}
}
@Override
public Record decode(BinaryInput in) throws CorruptedDataException {
Record record = scheme.record();
for (int i = 0; i < fieldSerializers.length; i++) {
BinarySerializer<?> serializer = fieldSerializers[i];
record.set(i, serializer.decode(in));
}
return record;
}
}
|
MadBase/MadNetJS | src/Wallet.js | const Account = require("./Account.js")
const Transaction = require("./Transaction.js")
const RPC = require("./RPC.js");
const utils = require("./Util");
/**
* Wallet handler
* @class
* @alias module:Wallet
* @property {Number} chainId - ChainID of the network to be connected to
* @property {Account} Account - Main Account Handler Instance
* @property {Transaction} Transaction - Main Transaction Handler Instance
* @property {RPC} RPC - Main RPC Handler Instance
* @property {UtilityCollection} Utils - Utility Collection
*/
class Wallet {
/**
* Creates an instance of Wallet.
* @param {number} [chainId=1]
* @param {string} [rpcServer=false]
*/
constructor(chainId, rpcServer = false) {
this.chainId = chainId ? utils.isNumber(chainId) : 1;
this.Account = new Account(this)
this.Transaction = new Transaction(this);
this.Rpc = new RPC(this, rpcServer);
this.Utils = utils;
}
}
module.exports = Wallet; |
sunahsuh/s3mock | src/test/scala/io/findify/s3mock/MultipartUploadTest.scala | package io.findify.s3mock
import java.io.ByteArrayInputStream
import java.nio.charset.Charset
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpMethods, HttpRequest}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Sink
import akka.util.ByteString
import com.amazonaws.services.s3.model._
import org.apache.commons.codec.digest.DigestUtils
import scala.collection.JavaConverters._
import scala.concurrent.duration._
import scala.concurrent.Await
import scala.util.Random
/**
* Created by shutty on 8/10/16.
*/
class MultipartUploadTest extends S3MockTest {
override def behaviour(fixture: => Fixture) = {
implicit val system = ActorSystem.create("test")
implicit val mat = ActorMaterializer()
val http = Http(system)
val s3 = fixture.client
val port = fixture.port
it should "upload multipart files" in {
s3.createBucket("getput")
val response1 = Await.result(http.singleRequest(HttpRequest(method = HttpMethods.POST, uri = s"http://127.0.0.1:$port/getput/foo2?uploads")), 10.minutes)
val data = Await.result(response1.entity.dataBytes.fold(ByteString(""))(_ ++ _).runWith(Sink.head), 10.seconds)
val uploadId = (scala.xml.XML.loadString(data.utf8String) \ "UploadId").text
val response2 = Await.result(http.singleRequest(HttpRequest(method = HttpMethods.POST, uri = s"http://127.0.0.1:$port/getput/foo2?partNumber=1&uploadId=$uploadId", entity = "foo")), 10.minutes)
response2.status.intValue() shouldBe 200
val response3 = Await.result(http.singleRequest(HttpRequest(method = HttpMethods.POST, uri = s"http://127.0.0.1:$port/getput/foo2?partNumber=2&uploadId=$uploadId", entity = "boo")), 10.minutes)
response3.status.intValue() shouldBe 200
val commit = """<CompleteMultipartUpload>
| <Part>
| <PartNumber>1</PartNumber>
| <ETag>ETag</ETag>
| </Part>
| <Part>
| <PartNumber>2</PartNumber>
| <ETag>ETag</ETag>
| </Part>
|</CompleteMultipartUpload>""".stripMargin
val response4 = Await.result(http.singleRequest(HttpRequest(method = HttpMethods.POST, uri = s"http://127.0.0.1:$port/getput/foo2?uploadId=$uploadId", entity = commit)), 10.minutes)
response4.status.intValue() shouldBe 200
getContent(s3.getObject("getput", "foo2")) shouldBe "fooboo"
}
it should "work with java sdk" in {
s3.createBucket("getput")
val init = s3.initiateMultipartUpload(new InitiateMultipartUploadRequest("getput", "foo4"))
val p1 = s3.uploadPart(new UploadPartRequest().withBucketName("getput").withPartSize(10).withKey("foo4").withPartNumber(1).withUploadId(init.getUploadId).withInputStream(new ByteArrayInputStream("hellohello".getBytes())))
val p2 = s3.uploadPart(new UploadPartRequest().withBucketName("getput").withPartSize(10).withKey("foo4").withPartNumber(2).withUploadId(init.getUploadId).withInputStream(new ByteArrayInputStream("worldworld".getBytes())))
val result = s3.completeMultipartUpload(new CompleteMultipartUploadRequest("getput", "foo4", init.getUploadId, List(p1.getPartETag, p2.getPartETag).asJava))
result.getKey shouldBe "foo4"
getContent(s3.getObject("getput", "foo4")) shouldBe "hellohelloworldworld"
}
it should "work with large blobs" in {
val init = s3.initiateMultipartUpload(new InitiateMultipartUploadRequest("getput", "fooLarge"))
val blobs = for (i <- 0 to 200) yield {
val blob1 = new Array[Byte](10000)
Random.nextBytes(blob1)
val p1 = s3.uploadPart(new UploadPartRequest().withBucketName("getput").withPartSize(blob1.length).withKey("fooLarge").withPartNumber(i).withUploadId(init.getUploadId).withInputStream(new ByteArrayInputStream(blob1)))
blob1 -> p1.getPartETag
}
val result = s3.completeMultipartUpload(new CompleteMultipartUploadRequest("getput", "fooLarge", init.getUploadId, blobs.map(_._2).asJava))
result.getKey shouldBe "fooLarge"
DigestUtils.md5Hex(s3.getObject("getput", "fooLarge").getObjectContent) shouldBe DigestUtils.md5Hex(blobs.map(_._1).fold(Array[Byte]())(_ ++ _))
}
it should "produce NoSuchBucket if bucket does not exist" in {
val exc = intercept[AmazonS3Exception] {
val init = s3.initiateMultipartUpload(new InitiateMultipartUploadRequest("aws-404", "foo4"))
val p1 = s3.uploadPart(new UploadPartRequest().withBucketName("aws-404").withPartSize(10).withKey("foo4").withPartNumber(1).withUploadId(init.getUploadId).withInputStream(new ByteArrayInputStream("hellohello".getBytes())))
}
exc.getStatusCode shouldBe 404
exc.getErrorCode shouldBe "NoSuchBucket"
}
it should "upload multipart with metadata" in {
s3.createBucket("getput")
val metadata: ObjectMetadata = new ObjectMetadata()
metadata.setContentType("application/json")
metadata.addUserMetadata("metamaic", "maic")
val init = s3.initiateMultipartUpload(new InitiateMultipartUploadRequest("getput", "foo4", metadata))
val p1 = s3.uploadPart(new UploadPartRequest().withBucketName("getput").withPartSize(10).withKey("foo4").withPartNumber(1).withUploadId(init.getUploadId).withInputStream(new ByteArrayInputStream("hellohello".getBytes())))
val p2 = s3.uploadPart(new UploadPartRequest().withBucketName("getput").withPartSize(10).withKey("foo4").withPartNumber(2).withUploadId(init.getUploadId).withInputStream(new ByteArrayInputStream("worldworld".getBytes())))
val result = s3.completeMultipartUpload(new CompleteMultipartUploadRequest("getput", "foo4", init.getUploadId, List(p1.getPartETag, p2.getPartETag).asJava))
result.getKey shouldBe "foo4"
val s3Object = s3.getObject("getput", "foo4")
getContent(s3Object) shouldBe "hellohelloworldworld"
val actualMetadata: ObjectMetadata = s3Object.getObjectMetadata
actualMetadata.getContentType shouldBe "application/json"
actualMetadata.getUserMetadata.get("metamaic") shouldBe "maic"
}
}
}
|
kamushadenes/swayit | modules/bw/functions.go | package bw
import (
"encoding/json"
"fmt"
"github.com/kamushadenes/swayit/common"
"github.com/kamushadenes/swayit/config"
"os"
"os/exec"
"strings"
"time"
)
func maskPassword(pwd string) string {
var masked []string
masked = append(masked, string(pwd[0]))
for i := 1; i <= len(pwd)-2; i++ {
masked = append(masked, "*")
}
masked = append(masked, string(pwd[len(pwd)-1]))
return strings.Join(masked, "")
}
func formatItemsWofi(tasks []*Item) []string {
var formatted []string
for _, item := range tasks {
formatted = append(formatted, fmt.Sprintf("<b>%s</b>\n%s", item.Name, item.Login.Username))
}
return formatted
}
func GetItems() ([]*Item, error) {
var items []*Item
cached, expired, err := common.GetCache(module.GetSlug(), "items.json", time.Duration(config.SwayItConfig.BW.MaxAge)*time.Minute)
if err == nil && !expired {
err = json.Unmarshal(cached, &items)
if err == nil {
return items, nil
}
}
common.Notify("BW", "Refreshing items")
cmd := exec.Command(config.SwayItConfig.BW.Command, "list", "items")
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, fmt.Sprintf("BW_SESSION=%s", config.SwayItConfig.BW.SessionToken))
out, err := cmd.Output()
if err != nil {
return nil, err
}
err = json.Unmarshal(out, &items)
b, err := json.Marshal(&items)
if err != nil {
return nil, err
}
err = common.SetCache(module.GetSlug(), "items.json", b)
return items, err
} |
wivw0306/bk-cmdb | src/source_controller/coreservice/service/count.go | <reponame>wivw0306/bk-cmdb
/*
* Tencent is pleased to support the open source community by making 蓝鲸 available.,
* Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the ",License",); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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 service
import (
"sync"
"configcenter/src/common"
"configcenter/src/common/blog"
"configcenter/src/common/errors"
"configcenter/src/common/http/rest"
"configcenter/src/common/util"
"configcenter/src/storage/driver/mongodb"
)
// get counts in table based on filters, returns in the same order
func (s *coreService) GetCountByFilter(ctx *rest.Contexts) {
req := struct {
Table string `json:"table"`
Filters []map[string]interface{} `json:"filters"`
}{}
if err := ctx.DecodeInto(&req); nil != err {
ctx.RespAutoError(err)
return
}
filters := req.Filters
table := req.Table
// to speed up, multi goroutine to get count
var wg sync.WaitGroup
var lock sync.RWMutex
var firstErr errors.CCErrorCoder
pipeline := make(chan bool, 10)
results := make([]int64, len(filters))
for idx, filter := range filters {
pipeline <- true
wg.Add(1)
go func(idx int, filter map[string]interface{}) {
defer func() {
wg.Done()
<-pipeline
}()
filter = util.SetQueryOwner(filter, ctx.Kit.SupplierAccount)
count, err := mongodb.Client().Table(table).Find(filter).Count(ctx.Kit.Ctx)
if err != nil {
blog.ErrorJSON("GetCountByFilter failed, error: %s, table: %s, filter: %s, rid: %s", err.Error(), table, filter, ctx.Kit.Rid)
if firstErr == nil {
firstErr = ctx.Kit.CCError.CCError(common.CCErrCommDBSelectFailed)
}
return
}
lock.Lock()
results[idx] = int64(count)
lock.Unlock()
}(idx, filter)
}
wg.Wait()
if firstErr != nil {
ctx.RespAutoError(firstErr)
return
}
ctx.RespEntity(results)
}
|
RichardBronosky/aws-api-tools | __mocks__/react-intersection-observer.js | <filename>__mocks__/react-intersection-observer.js
import React from 'react'
// __mocks__/react-intersection-observer.js
export const InView = ({ children }) => React.createElement(
'div',
{ ref: null, inView: true },
children
)
|
arjun-dasinfomedia/tutor_park | src/views/Timeline/EditTimeLine.js | <gh_stars>0
import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { useHistory } from 'react-router-dom'
import {
CRow,
CCol,
} from "@coreui/react";
import { updateTimeLine } from "./TImeLineAction"
import { Form, useForm } from "src/components/formControls/useForm";
import Controls from "src/components/formControls/controls/Controls";
import useFullPageLoader from "../../hooks/useFullPageLoader";
// main Edit class start
const EditTimeLine = (data) => {
// dropdown option for Audiance
const Audiance = [
{ id: "Kindergarten", name: "Kindergarten" },
{ id: "Primary", name: "Primary" },
{ id: "High School", name: "High School" },
{ id: "Intermediate", name: "Intermediate" },
{ id: "Degree", name: "Degree" },
{ id: "Others", name: "Others" }
];
// dispatch Method
const [editTimeLineModal, setEditTimeLineModal] = useState(false);
const dispatch = useDispatch();
const [isLoading, setLoading] = useState(false);
const [loader, showLoader, hideLoader] = useFullPageLoader();
const history = useHistory()
// initial value
const initialFValues = {
id: data.data.id,
audiance: data.data.audiance,
image: "",
image_name: "",
description: data.data.description,
video: "",
video_name: "",
};
// validation code start
const validate = (fieldValues = values) => {
let temp = { ...errors };
if ("audiance" in fieldValues)
temp.audiance = fieldValues.audiance ? "" : "Please select target audience.";
if (fieldValues.audiance === "Others") {
if ("other_audiance" in fieldValues)
temp.other_audiance = fieldValues.other_audiance ? "" : "Please enter target audience.";
}
if ("description" in fieldValues)
temp.description = fieldValues.description
? ""
: "Pleasse add your description.";
if ("video_name" in fieldValues) {
var imagePath = fieldValues.video_name;
var logo = ['mp4', 'mov', 'wmv', 'mkv', 'avi']
var extension = imagePath.substring(
imagePath.lastIndexOf(".") + 1,
imagePath.length
);
if (fieldValues.video_name) {
if (logo.includes(extension)) {
temp.video_name = "";
} else {
temp.video_name = "Only mp4, mov, wmv, mkv and avi file is allowed.";
}
} else {
temp.video_name = "";
}
}
if ("image_name" in fieldValues) {
var imagePath = fieldValues.image_name;
var logo = ['jpeg', 'png', 'jpg']
var extension = imagePath.substring(
imagePath.lastIndexOf(".") + 1,
imagePath.length
);
if (fieldValues.image_name) {
if (logo.includes(extension)) {
temp.image_name = "";
} else {
temp.image_name = "Only Jpg, png and jpg file is allowed.";
}
} else {
temp.image_name = "";
}
}
setErrors({
...temp,
});
if (fieldValues === values) return Object.values(temp).every((x) => x === "");
};
const { values, setValues, errors, setErrors, handleInputChange, resetForm } =
useForm(initialFValues, true, validate);
// validation code end
// handle update form submit
const handleSubmit = (e) => {
e.preventDefault();
if (validate()) {
let data = new FormData();
data.append("id", values.id);
if (values.audiance === "Others") {
data.append("audiance", values.other_audiance);
} else {
data.append("audiance", values.audiance)
}
data.append("description", values.description);
data.append("video", values.video);
data.append("image", values.image);
dispatch(updateTimeLine(data));
}
}
return (
<>
<Form onSubmit={handleSubmit}>
<CRow>
<CCol sm={6} md={6} lg={6} xl={6}>
<Controls.Select
name="audiance"
label="Select Target Audience *"
value={values.audiance}
onChange={handleInputChange}
options={Audiance}
error={errors.audiance}
/>
</CCol>
{
values.audiance === "Others" ?
<CCol sm={6} md={6} lg={6} xl={6}>
<Controls.Input
name="other_audiance"
label="Other Target Audience *"
value={values.oteher_audiance}
labelShow={true}
onChange={handleInputChange}
error={errors.audiance}
/>
</CCol>
: ""
}
<CRow>
<CCol xl={12} sm={12}>
<Controls.CustomTextArea
label="Description *"
rows={3}
name="description"
value={values.description}
onChange={handleInputChange}
error={errors.description}
/>
</CCol>
</CRow>
<CRow>
<CCol xl={6} sm={6} className="">
<Controls.InputLabelShown
name="image_name"
label="Timeline Image"
type="file"
value={values.image_name}
onChange={handleInputChange}
error={errors.image_name}
/>
</CCol>
<CCol xl={6} sm={6} className="">
<Controls.InputLabelShown
name="video_name"
label="Timeline Video"
type="file"
value={values.video_name}
onChange={handleInputChange}
error={errors.video_name}
/>
</CCol>
</CRow>
</CRow>
<CRow>
<CCol sm={12} md={12} lg={6} xl={6} className="m-2">
<div className="d-inline">
<Controls.Button
type="submit"
text="Update timeline"
className="m-1"
onDismiss={() => setEditTimeLineModal(false)}
/>
</div>
<div className="d-inline">
<Controls.Button
className="m-1"
text="Reset"
color="default"
onClick={resetForm}
/>
</div>
</CCol>
</CRow>
</Form>
</>
);
};
export default EditTimeLine
|
jdh8/metallic | include/fcntl.h | #ifndef _FCNTL_H
#define _FCNTL_H
typedef unsigned mode_t;
typedef long long off_t;
typedef int pid_t;
struct flock
{
short l_type;
short l_whence;
off_t l_start;
off_t l_len;
pid_t l_pid;
};
#define F_DUPFD 0
#define F_GETFD 1
#define F_SETFD 2
#define F_GETFL 3
#define F_SETFL 4
#define F_GETLK 5
#define F_SETLK 6
#define F_SETLKW 7
#define F_SETOWN 8
#define F_GETOWN 9
#define FD_CLOEXEC 1
#define F_RDLCK 0
#define F_WRLCK 1
#define F_UNLCK 2
#define O_CREAT 0100
#define O_EXCL 0200
#define O_NOCTTY 0400
#define O_TRUNC 01000
#define O_APPEND 02000
#define O_NONBLOCK 04000
#define O_DSYNC 010000
#define O_SYNC 04010000
#define O_RSYNC 04010000
#define O_DIRECTORY 0200000
#define O_NOFOLLOW 0400000
#define O_CLOEXEC 02000000
#define O_ASYNC 020000
#define O_DIRECT 040000
#define O_LARGEFILE 0
#define O_NOATIME 01000000
#define O_PATH 010000000
#define O_TMPFILE 020200000
#define O_NDELAY O_NONBLOCK
#define O_SEARCH O_PATH
#define O_EXEC O_PATH
#define O_TTY_INIT 0
#define O_ACCMODE (3 | O_EXEC)
#define O_RDONLY 0
#define O_WRONLY 1
#define O_RDWR 2
#define POSIX_FADV_NORMAL 0
#define POSIX_FADV_RANDOM 1
#define POSIX_FADV_SEQUENTIAL 2
#define POSIX_FADV_WILLNEED 3
#define POSIX_FADV_DONTNEED 4
#define POSIX_FADV_NOREUSE 5
#ifdef __cplusplus
extern "C" {
#endif
int creat(const char*, mode_t);
int fcntl(int, int, ...);
int open(const char*, int, ...);
int posix_fadvise(int, off_t, off_t, int);
int posix_fallocate(int, off_t, off_t);
#ifdef __cplusplus
}
#endif
#endif /* fcntl.h */
|
elimak/music-tag-extractor | node_modules/redux-async-connect/modules/ReduxAsyncConnect.js | import React from 'react';
import RouterContext from 'react-router/lib/RouterContext';
import { beginGlobalLoad, endGlobalLoad } from './asyncConnect';
import { connect } from 'react-redux';
const { array, func, object, any } = React.PropTypes;
/**
* We need to iterate over all components for specified routes.
* Components array can include objects if named components are used:
* https://github.com/rackt/react-router/blob/latest/docs/API.md#named-components
*
* @param components
* @param iterator
*/
function eachComponents(components, iterator) {
for (let i = 0, l = components.length; i < l; i++) { // eslint-disable-line id-length
if (typeof components[i] === 'object') {
for (let [key, value] of Object.entries(components[i])) {
iterator(value, i, key);
}
} else {
iterator(components[i], i);
}
}
}
function filterAndFlattenComponents(components) {
const flattened = [];
eachComponents(components, (Component) => {
if (Component && Component.reduxAsyncConnect) {
flattened.push(Component);
}
});
return flattened;
}
function loadAsyncConnect({components, filter = () => true, ...rest}) {
let async = false;
const promise = Promise.all(filterAndFlattenComponents(components).map(Component => {
const asyncItems = Component.reduxAsyncConnect;
return Promise.all(asyncItems.reduce((itemsResults, item) => {
let promiseOrResult = item.promise(rest);
if (filter(item, Component)) {
if (promiseOrResult && promiseOrResult.then instanceof Function) {
async = true;
promiseOrResult = promiseOrResult.catch(error => ({error}));
}
return [...itemsResults, promiseOrResult];
} else {
return itemsResults;
}
}, [])).then(results => {
return asyncItems.reduce((result, item, i) => ({...result, [item.key]: results[i]}), {});
});
}));
return {promise, async};
}
export function loadOnServer(args) {
const result = loadAsyncConnect(args);
if (result.async) {
result.promise.then(() => {
args.store.dispatch(endGlobalLoad());
});
}
return result.promise;
}
let loadDataCounter = 0;
class ReduxAsyncConnect extends React.Component {
static propTypes = {
components: array.isRequired,
params: object.isRequired,
render: func.isRequired,
beginGlobalLoad: func.isRequired,
endGlobalLoad: func.isRequired,
helpers: any
};
static contextTypes = {
store: object.isRequired
};
static defaultProps = {
render(props) {
return <RouterContext {...props} />;
}
};
isLoaded() {
return this.context.store.getState().reduxAsyncConnect.loaded;
}
constructor(props, context) {
super(props, context);
this.state = {
propsToShow: this.isLoaded() ? props : null
};
}
componentDidMount() {
const dataLoaded = this.isLoaded();
if (!dataLoaded) { // we dont need it if we already made it on server-side
this.loadAsyncData(this.props);
}
}
componentWillReceiveProps(nextProps) {
this.loadAsyncData(nextProps);
}
shouldComponentUpdate(nextProps, nextState) {
return this.state.propsToShow !== nextState.propsToShow;
}
loadAsyncData(props) {
const store = this.context.store;
const loadResult = loadAsyncConnect({...props, store});
loadDataCounter++;
if (loadResult.async) {
this.props.beginGlobalLoad();
(loadDataCounterOriginal => {
loadResult.promise.then(() => {
// We need to change propsToShow only if loadAsyncData that called this promise
// is the last invocation of loadAsyncData method. Otherwise we can face situation
// when user is changing route several times and we finally show him route that has
// loaded props last time and not the last called route
if (loadDataCounter === loadDataCounterOriginal) {
this.setState({propsToShow: props});
}
this.props.endGlobalLoad();
});
})(loadDataCounter);
} else {
this.setState({propsToShow: props});
}
}
render() {
const {propsToShow} = this.state;
return propsToShow && this.props.render(propsToShow);
}
}
export default connect(null, {beginGlobalLoad, endGlobalLoad})(ReduxAsyncConnect);
|
iandexter/terraform-provider-databricks | workspace/resource_notebook.go | package workspace
import (
"context"
"encoding/base64"
"path/filepath"
"strings"
"sync"
"github.com/databrickslabs/terraform-provider-databricks/common"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
// ...
const (
Notebook string = "NOTEBOOK"
Directory string = "DIRECTORY"
Scala string = "SCALA"
Python string = "PYTHON"
SQL string = "SQL"
R string = "R"
)
type notebookLanguageFormat struct {
Language string
Format string
Overwrite bool
}
var extMap = map[string]notebookLanguageFormat{
".scala": {"SCALA", "SOURCE", true},
".py": {"PYTHON", "SOURCE", true},
".sql": {"SQL", "SOURCE", true},
".r": {"R", "SOURCE", true},
".dbc": {"", "DBC", false},
}
// ObjectStatus contains information when doing a get request or list request on the workspace api
type ObjectStatus struct {
ObjectID int64 `json:"object_id,omitempty" tf:"computed"`
ObjectType string `json:"object_type,omitempty" tf:"computed"`
Path string `json:"path"`
Language string `json:"language,omitempty"`
}
// ExportPath contains the base64 content of the notebook
type ExportPath struct {
Content string `json:"content,omitempty"`
}
// ImportPath contains the payload to import a notebook
type ImportPath struct {
Content string `json:"content"`
Path string `json:"path"`
Language string `json:"language,omitempty"`
Format string `json:"format,omitempty"`
Overwrite bool `json:"overwrite,omitempty"`
}
// DeletePath contains the payload to delete a notebook
type DeletePath struct {
Path string `json:"path,omitempty"`
Recursive bool `json:"recursive,omitempty"`
}
// NewNotebooksAPI creates NotebooksAPI instance from provider meta
func NewNotebooksAPI(ctx context.Context, m interface{}) NotebooksAPI {
return NotebooksAPI{m.(*common.DatabricksClient), ctx}
}
// NotebooksAPI exposes the Notebooks API
type NotebooksAPI struct {
client *common.DatabricksClient
context context.Context
}
// Mutex for synchronous deletes (api has poor limits in terms of allowed parallelism this increases stability of the deletes)
// sometimes there will be two folders with the same name at the same level due to issues with creating directories in
// parallel. This mutex just synchronizes everything to create folders one at a time. This mutex will be removed when mkdirs
// is removed from the notebooks resource. Then we will switch to TF resource retry.
var mtx = &sync.Mutex{}
// Create creates a notebook given the content and path
func (a NotebooksAPI) Create(r ImportPath) error {
mtx.Lock()
defer mtx.Unlock()
return a.client.Post(a.context, "/workspace/import", r, nil)
}
// Read returns the notebook metadata and not the contents
func (a NotebooksAPI) Read(path string) (ObjectStatus, error) {
var notebookInfo ObjectStatus
err := a.client.Get(a.context, "/workspace/get-status", map[string]string{
"path": path,
}, ¬ebookInfo)
return notebookInfo, err
}
type workspacePathRequest struct {
Format string `url:"format,omitempty"`
Path string `url:"path,omitempty"`
}
// Export returns the notebook content as a base64 string
func (a NotebooksAPI) Export(path string, format string) (string, error) {
var notebookContent ExportPath
err := a.client.Get(a.context, "/workspace/export", workspacePathRequest{
Format: format,
Path: path,
}, ¬ebookContent)
// TODO: return decoded []byte
return notebookContent.Content, err
}
// Mkdirs will make folders in a workspace recursively given a path
func (a NotebooksAPI) Mkdirs(path string) error {
// This mutex will be removed when mkdirs is removed from the notebooks resource.
// Then we will switch to TF resource retry.
mtx.Lock()
defer mtx.Unlock()
return a.client.Post(a.context, "/workspace/mkdirs", map[string]string{
"path": path,
}, nil)
}
// List will list all objects in a path on the workspace
// and with the recursive flag it will recursively list
// all the objects
func (a NotebooksAPI) List(path string, recursive bool) ([]ObjectStatus, error) {
if recursive {
var paths []ObjectStatus
err := a.recursiveAddPaths(path, &paths)
if err != nil {
return nil, err
}
return paths, err
}
return a.list(path)
}
func (a NotebooksAPI) recursiveAddPaths(path string, pathList *[]ObjectStatus) error {
notebookInfoList, err := a.list(path)
if err != nil {
return err
}
for _, v := range notebookInfoList {
if v.ObjectType == Notebook {
*pathList = append(*pathList, v)
} else if v.ObjectType == Directory {
err := a.recursiveAddPaths(v.Path, pathList)
if err != nil {
return err
}
}
}
return err
}
type ObjectList struct {
Objects []ObjectStatus `json:"objects,omitempty"`
}
func (a NotebooksAPI) list(path string) ([]ObjectStatus, error) {
var notebookList ObjectList
err := a.client.Get(a.context, "/workspace/list", map[string]string{
"path": path,
}, ¬ebookList)
return notebookList.Objects, err
}
// Delete will delete folders given a path and recursive flag
func (a NotebooksAPI) Delete(path string, recursive bool) error {
mtx.Lock()
defer mtx.Unlock()
return a.client.Post(a.context, "/workspace/delete", DeletePath{
Path: path,
Recursive: recursive,
}, nil)
}
// ResourceNotebook manages notebooks
func ResourceNotebook() *schema.Resource {
s := FileContentSchema(map[string]*schema.Schema{
"language": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{
Scala,
Python,
R,
SQL,
}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
source := d.Get("source").(string)
if source == "" {
return false
}
ext := strings.ToLower(filepath.Ext(source))
return old == extMap[ext].Language
},
},
"format": {
Type: schema.TypeString,
Optional: true,
Default: "SOURCE",
ValidateFunc: validation.StringInSlice([]string{
"SOURCE",
"DBC",
}, false),
},
"url": {
Type: schema.TypeString,
Computed: true,
},
"object_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Always is a notebook",
},
"object_id": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Deprecated: "Use id argument to retrieve object id",
},
})
s["content_base64"].RequiredWith = []string{"language"}
return common.Resource{
Schema: s,
SchemaVersion: 1,
Create: func(ctx context.Context, d *schema.ResourceData, c *common.DatabricksClient) error {
content, err := ReadContent(d)
if err != nil {
return err
}
notebooksAPI := NewNotebooksAPI(ctx, c)
path := d.Get("path").(string)
parent := filepath.ToSlash(filepath.Dir(path))
if parent != "/" {
err = notebooksAPI.Mkdirs(parent)
if err != nil {
return err
}
}
createNotebook := ImportPath{
Content: base64.StdEncoding.EncodeToString(content),
Language: d.Get("language").(string),
Format: d.Get("format").(string),
Path: path,
Overwrite: true,
}
if createNotebook.Language == "" {
// TODO: check what happens with empty source
ext := strings.ToLower(filepath.Ext(d.Get("source").(string)))
createNotebook.Language = extMap[ext].Language
createNotebook.Format = extMap[ext].Format
// Overwrite cannot be used for Dbc format
createNotebook.Overwrite = extMap[ext].Overwrite
// by default it's SOURCE, but for DBC we have to change it
d.Set("format", createNotebook.Format)
}
err = notebooksAPI.Create(createNotebook)
if err != nil {
return err
}
d.SetId(path)
return nil
},
Read: func(ctx context.Context, d *schema.ResourceData, c *common.DatabricksClient) error {
notebooksAPI := NewNotebooksAPI(ctx, c)
objectStatus, err := notebooksAPI.Read(d.Id())
if err != nil {
return err
}
d.Set("url", c.FormatURL("#workspace", d.Id()))
return common.StructToData(objectStatus, s, d)
},
Update: func(ctx context.Context, d *schema.ResourceData, c *common.DatabricksClient) error {
notebooksAPI := NewNotebooksAPI(ctx, c)
content, err := ReadContent(d)
if err != nil {
return err
}
format := d.Get("format").(string)
if format == "DBC" {
// Overwrite cannot be used for source format when importing a folder
err = notebooksAPI.Delete(d.Id(), true)
if err != nil {
return err
}
return notebooksAPI.Create(ImportPath{
Content: base64.StdEncoding.EncodeToString(content),
Format: format,
Path: d.Id(),
})
}
return notebooksAPI.Create(ImportPath{
Content: base64.StdEncoding.EncodeToString(content),
Language: d.Get("language").(string),
Format: format,
Overwrite: true,
Path: d.Id(),
})
},
Delete: func(ctx context.Context, d *schema.ResourceData, c *common.DatabricksClient) error {
return NewNotebooksAPI(ctx, c).Delete(d.Id(), true)
},
}.ToResource()
}
|
machinio/solrb | lib/solr/query/request/facet.rb | module Solr
module Query
class Request
class Facet
include Solr::Support::SchemaHelper
TERMS_TYPE = :terms
QUERY_TYPE = :query
RANGE_TYPE = :range
attr_reader :field,
:type,
:name,
:value,
:limit,
:filters,
:subfacets,
:gap,
:lower_bound,
:upper_bound,
:domain
def initialize(field:, type:, name: nil, value: nil, filters: [], subfacets: [], options: {})
if options[:limit].nil? && type == TERMS_TYPE
raise ArgumentError, "Need to specify :limit option value for 'terms' facet type"
end
if options.values_at(:gap, :lower_bound, :upper_bound).any?(&:nil?) && type == RANGE_TYPE
raise ArgumentError, "Need to specify :lower_bound, :upper_bound, :gap option values for 'range' facet type"
end
@field = field
@name = name || field
@type = type
@value = value
@filters = filters
@subfacets = subfacets
@limit = options[:limit].to_i
@gap = options[:gap]
@lower_bound = options[:lower_bound]
@upper_bound = options[:upper_bound]
@domain = options[:domain]
end
def to_solr_h
return { name.to_s => value } if type == QUERY_TYPE && value
default_solr_h
end
protected
def default_solr_h
{
"#{name}": {
type: type,
field: solarize_field(field),
limit: limit,
q: filters.any? ? filters.map(&:to_solr_s).join(' AND ') : nil,
facet: subfacets.map(&:to_solr_h).reduce(&:merge),
gap: gap,
start: lower_bound,
end: upper_bound,
domain: domain
}.compact
}
end
end
end
end
end
|
DrFaust92/terraformer | vendor/github.com/aws/aws-sdk-go-v2/service/ec2/api_op_ModifyVpnConnection.go | <gh_stars>1-10
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package ec2
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/internal/awsutil"
)
type ModifyVpnConnectionInput struct {
_ struct{} `type:"structure"`
// The ID of the customer gateway at your end of the VPN connection.
CustomerGatewayId *string `type:"string"`
// Checks whether you have the required permissions for the action, without
// actually making the request, and provides an error response. If you have
// the required permissions, the error response is DryRunOperation. Otherwise,
// it is UnauthorizedOperation.
DryRun *bool `type:"boolean"`
// The ID of the transit gateway.
TransitGatewayId *string `type:"string"`
// The ID of the VPN connection.
//
// VpnConnectionId is a required field
VpnConnectionId *string `type:"string" required:"true"`
// The ID of the virtual private gateway at the AWS side of the VPN connection.
VpnGatewayId *string `type:"string"`
}
// String returns the string representation
func (s ModifyVpnConnectionInput) String() string {
return awsutil.Prettify(s)
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ModifyVpnConnectionInput) Validate() error {
invalidParams := aws.ErrInvalidParams{Context: "ModifyVpnConnectionInput"}
if s.VpnConnectionId == nil {
invalidParams.Add(aws.NewErrParamRequired("VpnConnectionId"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
type ModifyVpnConnectionOutput struct {
_ struct{} `type:"structure"`
// Describes a VPN connection.
VpnConnection *VpnConnection `locationName:"vpnConnection" type:"structure"`
}
// String returns the string representation
func (s ModifyVpnConnectionOutput) String() string {
return awsutil.Prettify(s)
}
const opModifyVpnConnection = "ModifyVpnConnection"
// ModifyVpnConnectionRequest returns a request value for making API operation for
// Amazon Elastic Compute Cloud.
//
// Modifies the target gateway of an AWS Site-to-Site VPN connection. The following
// migration options are available:
//
// * An existing virtual private gateway to a new virtual private gateway
//
// * An existing virtual private gateway to a transit gateway
//
// * An existing transit gateway to a new transit gateway
//
// * An existing transit gateway to a virtual private gateway
//
// Before you perform the migration to the new gateway, you must configure the
// new gateway. Use CreateVpnGateway to create a virtual private gateway, or
// CreateTransitGateway to create a transit gateway.
//
// This step is required when you migrate from a virtual private gateway with
// static routes to a transit gateway.
//
// You must delete the static routes before you migrate to the new gateway.
//
// Keep a copy of the static route before you delete it. You will need to add
// back these routes to the transit gateway after the VPN connection migration
// is complete.
//
// After you migrate to the new gateway, you might need to modify your VPC route
// table. Use CreateRoute and DeleteRoute to make the changes described in VPN
// Gateway Target Modification Required VPC Route Table Updates (https://docs.aws.amazon.com/vpn/latest/s2svpn/modify-vpn-target.html#step-update-routing)
// in the AWS Site-to-Site VPN User Guide.
//
// When the new gateway is a transit gateway, modify the transit gateway route
// table to allow traffic between the VPC and the AWS Site-to-Site VPN connection.
// Use CreateTransitGatewayRoute to add the routes.
//
// If you deleted VPN static routes, you must add the static routes to the transit
// gateway route table.
//
// After you perform this operation, the AWS VPN endpoint's IP addresses on
// the AWS side and the tunnel options remain intact. Your s2slong; connection
// will be temporarily unavailable for approximately 10 minutes while we provision
// the new endpoints
//
// // Example sending a request using ModifyVpnConnectionRequest.
// req := client.ModifyVpnConnectionRequest(params)
// resp, err := req.Send(context.TODO())
// if err == nil {
// fmt.Println(resp)
// }
//
// Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpnConnection
func (c *Client) ModifyVpnConnectionRequest(input *ModifyVpnConnectionInput) ModifyVpnConnectionRequest {
op := &aws.Operation{
Name: opModifyVpnConnection,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &ModifyVpnConnectionInput{}
}
req := c.newRequest(op, input, &ModifyVpnConnectionOutput{})
return ModifyVpnConnectionRequest{Request: req, Input: input, Copy: c.ModifyVpnConnectionRequest}
}
// ModifyVpnConnectionRequest is the request type for the
// ModifyVpnConnection API operation.
type ModifyVpnConnectionRequest struct {
*aws.Request
Input *ModifyVpnConnectionInput
Copy func(*ModifyVpnConnectionInput) ModifyVpnConnectionRequest
}
// Send marshals and sends the ModifyVpnConnection API request.
func (r ModifyVpnConnectionRequest) Send(ctx context.Context) (*ModifyVpnConnectionResponse, error) {
r.Request.SetContext(ctx)
err := r.Request.Send()
if err != nil {
return nil, err
}
resp := &ModifyVpnConnectionResponse{
ModifyVpnConnectionOutput: r.Request.Data.(*ModifyVpnConnectionOutput),
response: &aws.Response{Request: r.Request},
}
return resp, nil
}
// ModifyVpnConnectionResponse is the response type for the
// ModifyVpnConnection API operation.
type ModifyVpnConnectionResponse struct {
*ModifyVpnConnectionOutput
response *aws.Response
}
// SDKResponseMetdata returns the response metadata for the
// ModifyVpnConnection request.
func (r *ModifyVpnConnectionResponse) SDKResponseMetdata() *aws.Response {
return r.response
}
|
sebastiandoe5/coronavirus-dashboard | src/components/Pane/index.js | export { default } from "./Pane"
export * from "./Pane";
|
kpodsiad/sbt | main/src/main/scala/sbt/internal/FileChangesMacro.scala | <gh_stars>1000+
/*
* sbt
* Copyright 2011 - 2018, Lightbend, Inc.
* Copyright 2008 - 2010, <NAME>
* Licensed under Apache License 2.0 (see LICENSE)
*/
package sbt
package internal
import java.nio.file.{ Path => NioPath }
import sbt.nio.Keys._
import sbt.nio.{ FileChanges, FileStamp }
import scala.annotation.compileTimeOnly
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
/**
* Provides extension methods to `TaskKey[T]` that can be use to fetch the input and output file
* dependency changes for a task. Nothing in this object is intended to be called directly but,
* because there are macro definitions, some of the definitions must be public.
*
*/
object FileChangesMacro {
private[sbt] sealed abstract class TaskOps[T](val taskKey: TaskKey[T]) {
@compileTimeOnly(
"`inputFileChanges` can only be called on a task within a task definition macro, such as :=, +=, ++=, or Def.task."
)
def inputFileChanges: FileChanges = macro changedInputFilesImpl[T]
@compileTimeOnly(
"`outputFileChanges` can only be called on a task within a task definition macro, such as :=, +=, ++=, or Def.task."
)
def outputFileChanges: FileChanges = macro changedOutputFilesImpl[T]
@compileTimeOnly(
"`inputFiles` can only be called on a task within a task definition macro, such as :=, +=, ++=, or Def.task."
)
def inputFiles: Seq[NioPath] = macro inputFilesImpl[T]
@compileTimeOnly(
"`outputFiles` can only be called on a task within a task definition macro, such as :=, +=, ++=, or Def.task."
)
def outputFiles: Seq[NioPath] = macro outputFilesImpl[T]
}
def changedInputFilesImpl[T: c.WeakTypeTag](c: blackbox.Context): c.Expr[FileChanges] = {
impl[T](c)(
c.universe.reify(allInputFiles),
c.universe.reify(changedInputFiles),
c.universe.reify(inputFileStamps)
)
}
def changedOutputFilesImpl[T: c.WeakTypeTag](
c: blackbox.Context
): c.Expr[FileChanges] = {
impl[T](c)(
c.universe.reify(allOutputFiles),
c.universe.reify(changedOutputFiles),
c.universe.reify(outputFileStamps)
)
}
def rescope[T](left: TaskKey[_], right: TaskKey[T]): TaskKey[T] =
Scoped.scopedTask(left.scope.copy(task = Select(left.key)), right.key)
def rescope[T](left: Scope, right: TaskKey[T]): TaskKey[T] =
Scoped.scopedTask(left, right.key)
private def impl[T: c.WeakTypeTag](
c: blackbox.Context
)(
currentKey: c.Expr[TaskKey[Seq[NioPath]]],
changeKey: c.Expr[TaskKey[Seq[(NioPath, FileStamp)] => FileChanges]],
mapKey: c.Expr[TaskKey[Seq[(NioPath, FileStamp)]]]
): c.Expr[FileChanges] = {
import c.universe._
val taskScope = getTaskScope(c)
reify {
val changes = rescope(taskScope.splice, changeKey.splice).value
val current = rescope(taskScope.splice, currentKey.splice).value
import sbt.nio.FileStamp.Formats._
val previous = Previous.runtimeInEnclosingTask(rescope(taskScope.splice, mapKey.splice)).value
previous.map(changes).getOrElse(FileChanges.noPrevious(current))
}
}
def inputFilesImpl[T: c.WeakTypeTag](c: blackbox.Context): c.Expr[Seq[NioPath]] = {
val taskKey = getTaskScope(c)
c.universe.reify(rescope(taskKey.splice, allInputFiles).value)
}
def outputFilesImpl[T: c.WeakTypeTag](c: blackbox.Context): c.Expr[Seq[NioPath]] = {
val taskKey = getTaskScope(c)
c.universe.reify(rescope(taskKey.splice, allOutputFiles).value)
}
private def getTaskScope[T: c.WeakTypeTag](c: blackbox.Context): c.Expr[sbt.Scope] = {
import c.universe._
val taskTpe = c.weakTypeOf[TaskKey[T]]
lazy val err = "Couldn't expand file change macro."
c.macroApplication match {
case Select(Apply(_, k :: Nil), _) if k.tpe <:< taskTpe =>
val expr = c.Expr[TaskKey[T]](k)
c.universe.reify {
if (expr.splice.scope.task.toOption.isDefined) expr.splice.scope
else expr.splice.scope.copy(task = sbt.Select(expr.splice.key))
}
case _ => c.abort(c.enclosingPosition, err)
}
}
}
|
NovaOrdis/series | src/main/java/com/novaordis/series/storage/Storage.java | <reponame>NovaOrdis/series
package com.novaordis.series.storage;
import com.novaordis.series.Row;
import java.util.Iterator;
/**
* The interface exposed by the components that store Row instances. Row counter starts from 1 - the first line in the file is line 1.
*
* Non-successive lines are acceptable - lines may be discarded, contain something else than metrics, be comments, etc.
*
* The storage does not know what those Rows are - it does not have the concept of Header. Headers are maintained by the layer above
* the storage.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
* Copyright 2012 Nova Ordis LLC
*/
public interface Storage
{
/**
* The storage implementation must make sure that the timestamp of the row being added is
* strictly bigger than the timestamp of any stored row that has a smaller row number.
*
* At the same time, the timestamp of the row being added is strictly smaller that the
* timestamp of any stored row that has a bigger row number.
*
* The implementation relies on Row implementations correctly implementing equals() and
* hashCode().
*
* @exception DuplicateTimestampException
* @exception DuplicateLineNumberException
*/
void add(Row row) throws Exception;
long getBeginTime();
long getEndTime();
long getLineCount();
boolean isEmpty();
long getMinLineNumber();
long getMaxLineNumber();
Iterator<Row> iterator();
}
|
jamessynge/mcucore | src/array_view.h | #ifndef MCUCORE_SRC_ARRAY_VIEW_H_
#define MCUCORE_SRC_ARRAY_VIEW_H_
// ArrayView references a C-style array of T of known (fixed) size. It provides
// STL style support for iterating over the C-style array, in support of dealing
// with static configuration data provided to TinyAlpacaServer.
//
// Author: <EMAIL>
#include "logging.h"
#include "mcucore_platform.h"
#include "type_traits.h"
namespace mcucore {
template <typename T>
class ArrayView {
public:
// These two definitions must be changed together.
using size_type = uint8_t;
static constexpr size_type kMaxSize = 255;
using value_type = T;
using reference = value_type&;
using const_reference = const value_type&;
using iterator = value_type*;
using const_iterator = const value_type*;
// Construct empty.
constexpr ArrayView() noexcept : ptr_(nullptr), size_(0) {}
// Construct with a specified length.
constexpr ArrayView(T* ptr, size_type length)
: ptr_(length > 0 ? ptr : nullptr), size_(length) {}
// Constructs from a literal T[N] (i.e. an array of N elements of type T). The
// goal of this is to get the compiler to populate the size, rather than
// computing it at runtime.
template <size_type N>
explicit ArrayView(T (&array)[N]) : ArrayView(array, N) {}
const_iterator begin() { return ptr_; }
const_iterator begin() const { return ptr_; }
const_iterator end() { return ptr_ + size_; }
const_iterator end() const { return ptr_ + size_; }
// Returns the number of elements in the array.
constexpr size_type size() const { return size_; }
// Returns a pointer to the first element of the underlying array.
constexpr T* data() const { return ptr_; }
// Element access:
reference operator[](size_type ndx) {
MCU_DCHECK_LT(ndx, size_);
return ptr_[ndx];
}
const_reference operator[](size_type ndx) const {
MCU_DCHECK_LT(ndx, size_);
return ptr_[ndx];
}
private:
T* ptr_;
size_type size_;
};
template <typename T, int N>
ArrayView<T> MakeArrayView(T (&array)[N]) {
return ArrayView<T>(array, N);
}
} // namespace mcucore
#endif // MCUCORE_SRC_ARRAY_VIEW_H_
|
liuweixingGitHub/AXiOSTools | AXiOSKit/Classes/Kit/Observe/AXGCDTimer.h | <reponame>liuweixingGitHub/AXiOSTools
//
// AXGCDTimer.h
// AXiOSKitDemo
//
// Created by liuweixing on 2018/6/23.
// Copyright © 2018年 liuweixing. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface AXGCDTimer : NSObject
/**
GCD timer 不会强引用 ,不自动开始,调用 sourceTimerStart
@param aInterval 间隔
@param block 回调
@return 对象
*/
- (instancetype )initWithTimer:(NSTimeInterval)aInterval block:(void(^)(void))block;
/**
主动开始
*/
- (void)sourceTimerStart;
/**
取消
*/
- (void)sourceTimerCancel;
@end
|
cameroncooke/XcodeHeaders | PlugIns/GPUTraceDebuggerUI/DYPVariablesViewGPUStateValue-Protocol.h | <filename>PlugIns/GPUTraceDebuggerUI/DYPVariablesViewGPUStateValue-Protocol.h
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "NSObject.h"
@class NSArray, NSString;
@protocol DYPVariablesViewGPUStateValue <NSObject>
@property BOOL itemDescriptionHasChanged;
@property BOOL childValuesCountValid;
@property(copy) NSArray *childValues;
- (long long)compareName:(id <DYPVariablesViewGPUStateValue>)arg1;
- (void)addChildValue:(id <DYPVariablesViewGPUStateValue>)arg1;
- (void)addChildValues:(NSArray *)arg1;
- (void)setStateValue:(NSString *)arg1 withName:(NSString *)arg2 withType:(NSString *)arg3 withItemDescription:(NSString *)arg4 withChanged:(BOOL)arg5;
@end
|
hal0x2328/neo3-boa | boa3_test/test_sc/bytes_test/BytearrayExtend.py | from boa3.builtin import public
@public
def Main() -> bytearray:
a = bytearray(b'\x01\x02\x03')
a.extend(b'\x04\x05\x06')
return a
|
lechium/tvOS130Headers | usr/libexec/securityd/CKKSReachabilityTracker.h | <reponame>lechium/tvOS130Headers
/*
* This header is generated by classdump-dyld 1.0
* on Tuesday, November 5, 2019 at 3:11:52 PM Mountain Standard Time
* Operating System: Version 13.0 (Build 17J586)
* Image Source: /usr/libexec/securityd
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
@protocol OS_dispatch_queue, OS_nw_path_monitor, OS_dispatch_source;
@class CKKSResultOperation, NSObject, NSOperationQueue;
@interface CKKSReachabilityTracker : NSObject {
BOOL _haveNetwork;
CKKSResultOperation* _reachabilityDependency;
NSObject*<OS_dispatch_queue> _queue;
NSOperationQueue* _operationQueue;
NSObject*<OS_nw_path_monitor> _networkMonitor;
NSObject*<OS_dispatch_source> _timer;
}
@property (assign) BOOL haveNetwork; //@synthesize haveNetwork=_haveNetwork - In the implementation block
@property (retain) NSObject*<OS_dispatch_queue> queue; //@synthesize queue=_queue - In the implementation block
@property (retain) NSOperationQueue * operationQueue; //@synthesize operationQueue=_operationQueue - In the implementation block
@property (retain) NSObject*<OS_nw_path_monitor> networkMonitor; //@synthesize networkMonitor=_networkMonitor - In the implementation block
@property (retain) NSObject*<OS_dispatch_source> timer; //@synthesize timer=_timer - In the implementation block
@property (retain) CKKSResultOperation * reachabilityDependency; //@synthesize reachabilityDependency=_reachabilityDependency - In the implementation block
@property (readonly) BOOL currentReachability;
+(BOOL)isNetworkError:(id)arg1 ;
+(BOOL)isNetworkFailureError:(id)arg1 ;
-(CKKSResultOperation *)reachabilityDependency;
-(BOOL)isNetworkError:(id)arg1 ;
-(void)_onQueueRunReachabilityDependency;
-(void)_onQueueResetReachabilityDependency;
-(void)_onqueueSetNetworkReachability:(BOOL)arg1 ;
-(void)setReachabilityDependency:(CKKSResultOperation *)arg1 ;
-(BOOL)haveNetwork;
-(void)setHaveNetwork:(BOOL)arg1 ;
-(id)description;
-(id)init;
-(void)setQueue:(NSObject*<OS_dispatch_queue>)arg1 ;
-(NSObject*<OS_dispatch_queue>)queue;
-(void)setTimer:(NSObject*<OS_dispatch_source>)arg1 ;
-(NSOperationQueue *)operationQueue;
-(void)setOperationQueue:(NSOperationQueue *)arg1 ;
-(NSObject*<OS_dispatch_source>)timer;
-(NSObject*<OS_nw_path_monitor>)networkMonitor;
-(BOOL)currentReachability;
-(void)setNetworkMonitor:(NSObject*<OS_nw_path_monitor>)arg1 ;
-(void)setNetworkReachability:(BOOL)arg1 ;
@end
|
Voltra/StandardClassLibrary | include/scl/concepts/NonMovable.h | #pragma once
#include <scl/tools/meta/type_check.h>
namespace scl{
namespace concepts{
/**
* NonMovable concept, a type is non movable if it is neither move constructible nor move assignable
* @tparam T being the type to check against
*/
template <class T>
struct NonMovable{
constexpr operator bool() const{
using namespace scl::tools;
static_assert(!meta::is_move_constructible<T>(), "NonMovable<T>: T is move constructible");
static_assert(!meta::is_move_assignable<T>(), "NonMovable<T>: T is move assignable");
return true;
}
};
}
} |
DYS12345/ShopTest | ShopTest/Order/ValidationViewController.h | //
// ValidationViewController.h
// ShopTest
//
// Created by dong on 2017/9/20.
// Copyright © 2017年 dong. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ValidationViewController : UIViewController
@property(nonatomic, strong) UIImage *image;
@property(nonatomic, strong) UINavigationController *navi;
@property(nonatomic, assign) NSInteger c; // 1 控制台 2 店铺订单
@end
|
Fangtian89/DebuggerTest | app/src/main/java/com/example/debuggertest/until/ToastUtil.java | package com.example.debuggertest.until;
import android.content.Context;
import android.widget.Toast;
public class ToastUtil {
public static Toast mToast;
public static void showMsg(Context context,String msg){
if(mToast==null){
mToast=Toast.makeText(context,msg,Toast.LENGTH_LONG);
}else{
mToast.setText(msg);
}
mToast.show();
}
}
|
Oagenda/agenda-docx | server/lib/isNumber.js | 'use strict';
module.exports = num => !isNaN( num ) && Number.isFinite( num );
|
9dots/artbot | lib/pages/Create/PublishPage/PublishPage.js | /**
* Imports
*/
import AddToPlaylistModal from 'components/AddToPlaylistModal'
import CreatePlaylist from 'components/CreatePlaylist'
import {component, element} from 'vdux'
import Button from 'components/Button'
import {Block, Text} from 'vdux-ui'
import mapVals from '@f/map-values'
import filter from '@f/filter'
/**
* <Publish Page/>
*/
export default component({
render ({props, context, actions}) {
const {uid, username} = context
const {draftID, publish, data} = props
const {title, description, permissions, inputType, type} = data
const capabilities = filter((val, key) => key !== 'block_end'
, data.capabilities)
const labelWidth = 150
return (
<Block w={450} m='-60px auto 0' tall column align='center center'>
<Block mb='xl' wide>
<Block fs='xl' ellipsis bold color='blue'>{title}</Block>
<Block ellipsis mt='s'>{description}</Block>
<Block mt='l' textTransform='capitalize'>
<Block align='start'>
<Text bold w={labelWidth}>Challenge Mode:</Text>
<Text>{type}</Text>
</Block>
<Block align='start' my>
<Text bold w={labelWidth}>Code Type:</Text> {inputType}
</Block>
<Block align='start'>
<Text bold w={labelWidth}>Capabilities:</Text>
<Block textTransform='none' flex fontFamily='monospace'>
{ mapVals((val, key) => key, capabilities).join(', ') }
</Block>
</Block>
</Block>
</Block>
<Block>
<Btn mr onClick={context.setUrl(`/${username}/authored/drafts`)} bgColor='#AAA'
>Save Draft</Btn>
<Btn
onClick={context.openModal(addToPlaylistModal)}>
Publish
</Btn>
</Block>
</Block>
)
function addToPlaylistModal() {
return (
<AddToPlaylistModal
onSubmit={publish(draftID)}
onCancel={context.openModal(() => <CreatePlaylist
onSuccess={context.openModal(addToPlaylistModal)}
/>)}
cancel='New Playlist'
gameID={draftID}
uid={uid} />
)
}
}
})
const Btn = component({
render({props, children}) {
return (
<Button
bgColor='green'
px='xl'
fs='m'
py
{...props}>
{children}
</Button>
)
}
})
|
JonasKunz/inspectIT | inspectit.ui.rcp/src/main/java/rocks/inspectit/ui/rcp/ci/form/part/EUMSettingsPart.java | <gh_stars>0
package rocks.inspectit.ui.rcp.ci.form.part;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IPropertyListener;
import org.eclipse.ui.forms.IFormColors;
import org.eclipse.ui.forms.SectionPart;
import org.eclipse.ui.forms.editor.FormPage;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import rocks.inspectit.shared.all.instrumentation.config.impl.JSAgentModule;
import rocks.inspectit.shared.cs.ci.Environment;
import rocks.inspectit.shared.cs.ci.eum.EndUserMonitoringConfig;
import rocks.inspectit.ui.rcp.InspectIT;
import rocks.inspectit.ui.rcp.InspectITImages;
import rocks.inspectit.ui.rcp.ci.form.input.EnvironmentEditorInput;
import rocks.inspectit.ui.rcp.editor.tooltip.ColumnAwareToolTipSupport;
import rocks.inspectit.ui.rcp.validation.ValidationControlDecoration;
/**
* Part for configuring the user experience management.
*
* @author <NAME>
*
*/
public class EUMSettingsPart extends SectionPart implements IPropertyListener {
/**
* Form page.
*/
private final FormPage formPage;
/**
* Environment being edited.
*/
private Environment environment;
/**
* The base URL under which the EUM will operate (e.g. place the script).
*/
private Text scriptBaseUrl;
/**
* Switch to disable or enable EUM.
*/
private Button eumEnabledButton;
/**
* Table for selecting the EUM modules.
*/
private Table modulesTable;
/**
* Table viewer for {@link modulesTable}.
*/
private TableViewer modulesTableViewer;
/**
* Default constructor.
*
* @param formPage
* {@link FormPage} section belongs to.
* @param parent
* Parent composite.
* @param toolkit
* {@link FormToolkit}
* @param style
* Style used for creating the section.
*/
public EUMSettingsPart(FormPage formPage, Composite parent, FormToolkit toolkit, int style) {
super(parent, toolkit, style);
EnvironmentEditorInput input = (EnvironmentEditorInput) formPage.getEditor().getEditorInput();
this.environment = input.getEnvironment();
this.formPage = formPage;
this.formPage.getEditor().addPropertyListener(this);
// client
createPart(getSection(), toolkit);
// text and description on our own
getSection().setText("User Experience Monitoring");
Label label = toolkit.createLabel(getSection(), "Configuration of the User Experience Monitoring");
label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
getSection().setDescriptionControl(label);
}
/**
* Creates complete client.
*
* @param section
* {@link Section}
* @param toolkit
* {@link FormToolkit}
*/
private void createPart(Section section, FormToolkit toolkit) {
Composite mainComposite = toolkit.createComposite(section);
GridLayout gridLayout = new GridLayout(3, false);
gridLayout.horizontalSpacing = 10;
mainComposite.setLayout(gridLayout);
section.setClient(mainComposite);
// enable / disable button
toolkit.createLabel(mainComposite, "EUM Enabled:").setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
eumEnabledButton = toolkit.createButton(mainComposite, "Active", SWT.CHECK);
eumEnabledButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
eumEnabledButton.setSelection(environment.getEumConfig().isEumEnabled());
createInfoLabel(mainComposite, toolkit, "If activated, the java agent will inject a script (the JS-Agent) into the webpages and monitor client-side performance data.");
toolkit.createLabel(mainComposite, "Script Base URL:").setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
scriptBaseUrl = toolkit.createText(mainComposite, environment.getEumConfig().getScriptBaseUrl(), SWT.BORDER | SWT.LEFT);
scriptBaseUrl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
createInfoLabel(mainComposite, toolkit,
"The url-prefix under which the agents monitoring scripts will be made accessible to the client.\nThis Url must be mapped by at least one servlet or filter, usually the base-url of other static content like scripts or images is a good choice here.\nAlso, the entered path must begin and end with a slash.");
ValidationControlDecoration<Text> scriptBaseUrlValidation = new ValidationControlDecoration<Text>(scriptBaseUrl, formPage.getManagedForm().getMessageManager()) {
@Override
protected boolean validate(Text control) {
return control.getText().startsWith("/") && control.getText().endsWith("/"); // NOPMD
}
};
scriptBaseUrlValidation.setDescriptionText("The URL must begin and end with a slash");
scriptBaseUrlValidation.registerListener(SWT.Modify);
modulesTable = toolkit.createTable(mainComposite, SWT.MULTI | SWT.FULL_SELECTION | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.CHECK);
GridData tableLayout = new GridData(SWT.FILL, SWT.FILL, true, false);
tableLayout.horizontalSpan = 2;
modulesTable.setLayoutData(tableLayout);
modulesTable.setHeaderVisible(true);
modulesTable.setLinesVisible(true);
modulesTableViewer = new TableViewer(modulesTable);
createColumns();
ColumnAwareToolTipSupport.enableFor(modulesTableViewer);
modulesTableViewer.setContentProvider(new ArrayContentProvider());
modulesTableViewer.setInput(JSAgentModule.values());
modulesTableViewer.refresh();
updateCheckedItems();
modulesTable.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (e.detail == SWT.CHECK) {
if (!isDirty()) {
markDirty();
}
}
}
});
// dirty listener
Listener dirtyListener = new Listener() {
@Override
public void handleEvent(Event event) {
updateEnabledState();
if (!isDirty()) {
markDirty();
}
}
};
eumEnabledButton.addListener(SWT.Selection, dirtyListener);
scriptBaseUrl.addListener(SWT.Modify, dirtyListener);
updateEnabledState();
}
/**
* Disables or enabled the controls depending on wheterh EUM is enalbed or not.
*/
private void updateEnabledState() {
modulesTable.setEnabled(eumEnabledButton.getSelection());
scriptBaseUrl.setEnabled(eumEnabledButton.getSelection());
}
/**
* Builds the JSAgent module table.
*/
private void createColumns() {
TableViewerColumn activeColumn = new TableViewerColumn(modulesTableViewer, SWT.NONE);
activeColumn.getColumn().setResizable(false);
activeColumn.getColumn().setWidth(60);
activeColumn.getColumn().setText("Active");
activeColumn.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
return "";
}
});
activeColumn.getColumn().setToolTipText("Only active modules will be included in the JS Agent and sent to the clients.");
TableViewerColumn moduleNameColumn = new TableViewerColumn(modulesTableViewer, SWT.NONE);
moduleNameColumn.getColumn().setResizable(true);
moduleNameColumn.getColumn().setWidth(250);
moduleNameColumn.getColumn().setText("Module");
moduleNameColumn.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
return ((JSAgentModule) element).getUiName();
}
@Override
public Image getImage(Object element) {
// TODO add images to modules;
return null; // ImageFormatter.getSensorConfigImage((ISensorConfig) element);
}
/**
* {@inheritDoc}
*/
@Override
public String getToolTipText(Object element) {
return ((JSAgentModule) element).getUiDescription();
}
});
moduleNameColumn.getColumn().setToolTipText("Module type.");
}
/**
* Updates states of the check boxes next to the elements.
*/
private void updateCheckedItems() {
for (TableItem item : modulesTableViewer.getTable().getItems()) {
JSAgentModule moduleInfo = (JSAgentModule) item.getData();
EndUserMonitoringConfig eumConfig = environment.getEumConfig();
item.setChecked(eumConfig.getActiveModules().contains(String.valueOf(moduleInfo.getIdentifier())));
}
}
/**
* {@inheritDoc}
*/
@Override
public void commit(boolean onSave) {
if (onSave) {
super.commit(onSave);
environment.getEumConfig().setEumEnabled(eumEnabledButton.getSelection());
environment.getEumConfig().setScriptBaseUrl(scriptBaseUrl.getText());
StringBuilder moduleString = new StringBuilder();
for (TableItem item : modulesTableViewer.getTable().getItems()) {
JSAgentModule moduleInfo = (JSAgentModule) item.getData();
if (item.getChecked()) {
moduleString.append(moduleInfo.getIdentifier());
}
}
environment.getEumConfig().setActiveModules(moduleString.toString());
getManagedForm().dirtyStateChanged();
}
}
/**
* Creates info icon with given text as tool-tip.
*
* @param parent
* Composite to create on.
* @param toolkit
* {@link FormToolkit} to use.
* @param text
* Information text.
*/
protected void createInfoLabel(Composite parent, FormToolkit toolkit, String text) {
Label label = toolkit.createLabel(parent, "");
label.setToolTipText(text);
label.setImage(InspectIT.getDefault().getImage(InspectITImages.IMG_INFORMATION));
}
/**
* {@inheritDoc}
*/
@Override
public void propertyChanged(Object source, int propId) {
if (propId == IEditorPart.PROP_INPUT) {
EnvironmentEditorInput input = (EnvironmentEditorInput) formPage.getEditor().getEditorInput();
environment = input.getEnvironment();
}
}
@Override
public void dispose() {
formPage.getEditor().removePropertyListener(this);
super.dispose();
}
} |
incentivetoken/offspring | com.dgex.offspring.application/src/com/dgex/offspring/application/utils/ExchangeRates.java | package com.dgex.offspring.application.utils;
import java.util.List;
import org.apache.log4j.Logger;
import com.dgex.offspring.providers.bitcoinaverage.TickerAllProvider;
import com.dgex.offspring.providers.dgex.DGEXCurrentRateProvider;
import com.dgex.offspring.providers.service.Currencies;
import com.dgex.offspring.providers.service.ICurrency;
import com.dgex.offspring.providers.service.IRate;
import com.dgex.offspring.providers.service.IRateProvider;
public class ExchangeRates {
private static final Logger logger = Logger.getLogger(ExchangeRates.class);
public static Double convertNxtToBtc(double value) {
return value
* getRate(DGEXCurrentRateProvider.getInstance(), Currencies.BTC,
Currencies.NXT);
}
public static Double convertNxtToEur(double value) {
return convertBtcToEur(convertNxtToBtc(value));
}
public static Double convertNxtToDollar(double value) {
return convertBtcToDollar(convertNxtToBtc(value));
}
public static Double convertEurToBtc(double value) {
return value
/ getRate(TickerAllProvider.getInstance(), Currencies.BTC,
Currencies.EUR);
}
public static Double convertBtcToEur(double value) {
return value
* getRate(TickerAllProvider.getInstance(), Currencies.EUR,
Currencies.BTC);
}
public static Double convertBtcToDollar(double value) {
return value
* getRate(TickerAllProvider.getInstance(), Currencies.USD,
Currencies.BTC);
}
private static double getRate(IRateProvider provider, ICurrency base,
ICurrency quote) {
List<IRate> rates = provider.getRates(base, quote);
// logger.info("Rates for " + base + "/" + quote + " " + rates);
if (rates != null && !rates.isEmpty())
return rates.get(0).getPrice();
return 0;
}
}
|
Kenneth-KT/rails-assets | app/models/build/bower_error.rb | <gh_stars>100-1000
module Build
# Encapsulate Bower errors
# parsed from Bower JSON output
class BowerError < BuildError
attr_reader :path, :command, :details, :code
ENOTFOUND = 'ENOTFOUND'.freeze
EINVALID = 'EINVALID'.freeze
def initialize(message, details, path = nil, command = nil, code = nil)
@details = details
@path = path
@command = command
@code = code
super(message)
end
def not_found?
@code == ENOTFOUND
end
def invalid?
@code == EINVALID
end
def self.from_shell_error(e)
parsed_json = JSON.parse(e.message)
error = parsed_json.find { |h| h['level'] == 'error' }
BowerError.new(error['message'], error['details'],
e.path, e.command, error['code'])
end
end
end
|
mitre/keyterms-nlp | keyterms-nlp.utilities/src/main/java/keyterms/util/io/Encoding.java | /*
* NOTICE
* This software was produced for the U.S. Government and is subject to the
* Rights in Data-General Clause 5.227-14 (May 2014).
* Copyright 2018 The MITRE Corporation. All rights reserved.
*
* “Approved for Public Release; Distribution Unlimited” Case 18-2165
*
* This project contains content developed by The MITRE Corporation.
* If this code is used in a deployment or embedded within another project,
* it is requested that you send an email to <EMAIL>
* in order to let us know where this software is being used.
*
* 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 keyterms.util.io;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.slf4j.LoggerFactory;
import keyterms.util.Errors;
import keyterms.util.collect.Bags;
import keyterms.util.collect.Keyed;
import keyterms.util.lang.Lazy;
import keyterms.util.text.Strings;
/**
* Methods for interacting with character encoding constructs.
*/
public final class Encoding {
/**
* The character set for US_ASCII.
*/
public static final Charset ASCII = StandardCharsets.US_ASCII;
/**
* The character set for UTF-8.
*/
public static final Charset UTF8 = StandardCharsets.UTF_8;
/**
* The character set for UTF-16.
*/
public static final Charset UTF16 = StandardCharsets.UTF_16;
/**
* The character set for UTF-16LE.
*/
public static final Charset UTF16LE = StandardCharsets.UTF_16LE;
/**
* The character set for UTF-16BE.
*/
public static final Charset UTF16BE = StandardCharsets.UTF_16BE;
/**
* The character set for UTF-32.
*/
public static final Charset UTF32 = getCharset("UTF-32");
/**
* The character set for UTF-32LE.
*/
public static final Charset UTF32LE = getCharset("UTF-32LE");
/**
* The character set for UTF-32BE.
*/
public static final Charset UTF32BE = getCharset("UTF-32BE");
/**
* The default character set for the operating system.
*/
public static final Charset PLATFORM_DEFAULT = Charset.defaultCharset();
/**
* The UTF-8 byte order mark sequence.
*/
public static final byte[] UTF8_BOM = new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF };
/**
* The UTF-16 byte order mark sequence.
*/
public static final byte[] UTF16_BOM = new byte[] { (byte)0xFE, (byte)0xFF };
/**
* The UTF-16 little endian byte order mark sequence.
*/
public static final byte[] UTF16LE_BOM = new byte[] { (byte)0xFF, (byte)0xFE };
/**
* The UTF-32 byte order mark sequence.
*/
public static final byte[] UTF32_BOM = new byte[] { (byte)0x00, (byte)0x00, (byte)0xFE, (byte)0xFF };
/**
* The UTF-32 little endian byte order mark sequence.
*/
public static final byte[] UTF32LE_BOM = new byte[] { (byte)0xFF, (byte)0xFE, (byte)0x00, (byte)0x00 };
/**
* A map of the known character set byte order marks.
*/
private static final Map<Charset, byte[]> BOM_MAP = Bags.staticMap(
Keyed.of(UTF8, UTF8_BOM),
Keyed.of(UTF16, UTF16_BOM),
Keyed.of(UTF16LE, UTF16LE_BOM),
Keyed.of(UTF16BE, UTF16_BOM),
Keyed.of(UTF32, UTF32_BOM),
Keyed.of(UTF32LE, UTF32LE_BOM),
Keyed.of(UTF32BE, UTF32_BOM)
);
/**
* A sorted set of unattributed byte order marks, sorted in descending order based on the length of the byte order
* sequence.
*/
private static final Set<byte[]> BOMS = BOM_MAP.values().stream()
.collect(Collectors.toCollection(() -> new TreeSet<>((b1, b2) -> {
int l1 = (b1 != null) ? b1.length : -1;
int l2 = (b2 != null) ? b2.length : -1;
int diff = l2 - l1;
if ((diff == 0) && (l1 > 0)) {
for (int b = 0; b < l1; b++) {
diff = b2[b] - b1[b];
if (diff != 0) {
break;
}
}
}
return diff;
})));
/**
* A cache of the available character sets, maintained and retrieved via lazy initialization as the call to {@code
* Charset.availableCharsets()} is consistently expensive.
*/
private static final Lazy<SortedSet<Charset>> AVAILABLE = new Lazy<>(() ->
Collections.unmodifiableSortedSet(new TreeSet<>(Charset.availableCharsets().values())));
/**
* A cache of the available character sets, maintained and retrieved via lazy initialization as the call to {@code
* Charset.availableCharsets()} is consistently expensive.
*/
private static final Lazy<Map<String, Charset>> LENIENT_INDEX = new Lazy<>(() -> {
Map<String, Charset> nameIndex = new HashMap<>();
AVAILABLE.value().stream()
.map(charset -> new Keyed<>(getLenientName(charset.name()), charset))
.forEach(keyed -> nameIndex.put(keyed.getKey(), keyed.getValue()));
return Collections.unmodifiableMap(nameIndex);
});
/**
* A set of the lenient encoding names that have been reported as unsupported.
*/
private static final Set<String> REPORTED = new HashSet<>();
/**
* Get the available character sets on the system.
*
* @return A sorted set of the available character sets on the system.
*/
public static SortedSet<Charset> getAvailableCharsets() {
return AVAILABLE.value();
}
/**
* Get the name for the lenient character set index.
*
* @param encodingName The encoding name of interest.
*
* @return The name for the lenient character set index.
*/
public static String getLenientName(CharSequence encodingName) {
String lenientName = null;
if (encodingName != null) {
lenientName = encodingName.toString()
.toLowerCase()
.replaceAll("[\\s\\-_]", "")
.trim();
}
return lenientName;
}
/**
* A non-error producing character set locator.
*
* <p> A value of {@code null} will be returned if the character set cannot be located. </p>
*
* @param charsetName The name of the desired encoding.
*
* @return The specified {@code Charset}.
*/
public static Charset getCharset(CharSequence charsetName) {
Charset charset = null;
if (Strings.hasText(charsetName)) {
String lenientName = null;
try {
charset = Charset.forName(charsetName.toString());
} catch (Exception error) {
Errors.check(error);
}
if (charset == null) {
lenientName = getLenientName(charsetName);
assert (LENIENT_INDEX != null);
charset = LENIENT_INDEX.value().get(lenientName);
}
if (charset == null) {
assert (REPORTED != null);
if (!REPORTED.contains(lenientName)) {
REPORTED.add(lenientName);
LoggerFactory.getLogger(Encoding.class).error("UnsupportedCharSetException: " + lenientName);
}
}
}
return charset;
}
/**
* Get the character set associated with the specified byte order mark.
*
* <p> A value of {@code null} will be returned if the byte order mark sequence is not known. </p>
*
* @param bom The byte order mark.
*
* @return The character set associated with the specified byte order mark.
*/
public static Charset getCharset(byte[] bom) {
return BOM_MAP.entrySet().stream()
.filter((e) -> !Objects.equals(e.getKey(), UTF16BE))
.filter((e) -> !Objects.equals(e.getKey(), UTF32BE))
.filter((e) -> Arrays.equals(bom, e.getValue()))
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);
}
/**
* Get the byte order mark for the specified character set.
*
* @param charset The character set.
*
* @return The byte order mark for the specified character set.
*/
public static byte[] getBom(Charset charset) {
return BOM_MAP.get(charset);
}
/**
* Determine if a known byte order mark is present in the specified bytes.
*
* @param bytes The encoded bytes.
*
* @return The character encoding of the associated byte order mark if one is detected.
*/
public static Charset detectBom(byte[] bytes) {
Charset encoding = null;
if (bytes != null) {
for (byte[] bom : BOMS) {
if (bom.length <= bytes.length) {
boolean detected = false;
for (int b = 0; b < bom.length; b++) {
detected = (bom[b] == bytes[b]);
if (!detected) {
break;
}
}
if (detected) {
encoding = getCharset(bom);
break;
}
}
}
}
return encoding;
}
/**
* Presuming a byte order mark has accidentally been prepended to the specified text, attempt to remove it.
*
* @param text The text.
* @param charset The original encoding which generated the text.
*
* @return The text with the inadvertent bom character(s) stripped.
*/
public static String stripBom(CharSequence text, Charset charset) {
String stripped = (text != null) ? text.toString() : null;
if (stripped != null) {
ByteBuffer data = charset.encode(stripped);
stripBom(data, getBom(charset));
stripped = charset.decode(data).toString();
}
return stripped;
}
/**
* Attempt to effectively strip the specified byte order mark from the byte buffer by repositioning the read cursor
* of the buffer.
*
* @param buffer The byte buffer to strip.
* @param bom The byte order mark to strip.
*/
private static void stripBom(ByteBuffer buffer, byte[] bom) {
if ((buffer != null) && (bom != null)) {
int position = buffer.position();
int limit = buffer.limit();
int numBytes = limit - position;
if (numBytes > bom.length) {
byte[] testBytes = new byte[bom.length];
buffer.get(testBytes, 0, bom.length);
buffer.position(position);
if (Arrays.equals(bom, testBytes)) {
buffer.position(position + bom.length);
}
}
}
}
/**
* Encode the specified text using the platform's default encoding without a byte order mark sequence.
*
* <p> This method will not return {@code null}. </p>
*
* @param text The text to encode.
*
* @return The encoded bytes.
*/
public static byte[] encode(CharSequence text) {
return encode(text, null, false);
}
/**
* Encode the specified text without a byte order mark sequence.
*
* <p> This method will not return {@code null}. </p>
*
* <p> If the specified character set encoding is {@code null}, the system default encoding will be used. </p>
*
* @param text The text to encode.
* @param charset The character set encoding.
*
* @return The encoded bytes.
*/
public static byte[] encode(CharSequence text, Charset charset) {
return encode(text, charset, false);
}
/**
* Encode the specified text.
*
* <p> This method will not return {@code null}. </p>
*
* <p> If the specified character set encoding is {@code null}, the system default encoding will be used. </p>
*
* @param text The text to encode.
* @param charset The character set encoding.
* @param prependBom A flag indicating whether the applicable byte order mark should be prepended to the results.
*
* @return The encoded bytes.
*/
public static byte[] encode(CharSequence text, Charset charset, boolean prependBom) {
Charset encoding = (charset != null) ? charset : PLATFORM_DEFAULT;
byte[] encoded = new byte[0];
byte[] bom = getBom(encoding);
if ((text != null) && (text.length() > 0)) {
ByteBuffer buffer = encoding.encode(text.toString());
stripBom(buffer, bom);
int bufferLength = buffer.remaining();
encoded = new byte[bufferLength];
buffer.get(encoded, 0, bufferLength);
}
if ((prependBom) && (bom != null)) {
byte[] expanded = new byte[encoded.length + bom.length];
System.arraycopy(bom, 0, expanded, 0, bom.length);
System.arraycopy(encoded, 0, expanded, bom.length, encoded.length);
encoded = expanded;
}
return encoded;
}
/**
* Decode the given bytes using the specified character encoding scheme.
*
* <p> This method will return {@code null} if the specified data is {@code null}. </p>
*
* <p> A detected character set will be used if a known byte order mark is present at the beginning of the bytes,
* otherwise the platform default encoding will be used. </p>
*
* <p> The known byte order marks are for {@code UTF-8, UTF-16, UTF-32} and their variants. </p>
*
* @param bytes The bytes to decode.
*
* @return The decoded text.
*/
public static String decode(byte[] bytes) {
return decode(bytes, null);
}
/**
* Decode the given bytes using the specified character encoding scheme.
*
* <p> This method will return {@code null} if the specified data is {@code null}. </p>
*
* <p> If the specified character set encoding is {@code null}, a detected character set will be used if a known
* byte order mark is present at the beginning of the bytes, otherwise the platform default encoding will be used.
* </p>
*
* @param bytes The bytes to decode.
* @param charset The character set encoding.
*
* @return The decoded text.
*/
public static String decode(byte[] bytes, Charset charset) {
Charset encoding = charset;
if (encoding == null) {
encoding = detectBom(bytes);
encoding = (encoding != null) ? encoding : PLATFORM_DEFAULT;
}
String decoded = null;
if (bytes != null) {
byte[] bom = getBom(encoding);
ByteBuffer buffer = ByteBuffer.wrap(bytes);
stripBom(buffer, bom);
decoded = encoding.decode(buffer).toString();
}
return decoded;
}
/**
* Constructor.
*/
private Encoding() {
super();
}
} |
sdressler/objekt | examples/mantevo/miniFE-1.1/optional/stk_util/environment/Demangle.hpp | /*------------------------------------------------------------------------*/
/* Copyright 2010 Sandia Corporation. */
/* Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive */
/* license for use of this work by or on behalf of the U.S. Government. */
/* Export of this program may require a license from the */
/* United States Government. */
/*------------------------------------------------------------------------*/
#ifndef stk_util_environment_Demangle_hpp
#define stk_util_environment_Demangle_hpp
#include <string>
#if __GNUC__ == 3 || __GNUC__ == 4
#define STK_USE_PLATFORM_DEMANGLER
#endif
namespace stk {
/**
* @brief Function <b>demangle</b> returns the demangled C++ symbol from the mangled
* C++ symbol. The mangled named is obtained from the <b>type_info</b>
* <b>name()</b> function. From some compilers, the name is already demangled.
*
* @param symbol a <b>char</b> const pointer to the symbol.
*
* @return a <b>std::string</b> value of the demangled name.
*/
#ifdef STK_USE_PLATFORM_DEMANGLER
std::string demangle(const char *symbol);
#else
const char *demangle(const char *symbol);
#endif
} // namespace stk
#endif // stk_util_environment_Demangle_hpp
|
ael-noblegas/pychron | pychron/processing/tests/plateau.py | <reponame>ael-noblegas/pychron<gh_stars>1-10
from __future__ import absolute_import
__author__ = 'ross'
import unittest
from pychron.processing.plateau import Plateau
class PlateauTestCase(unittest.TestCase):
def test_find_plateaus_real_fail(self):
ages, errors, signals, idx = self._get_test_data_real_fail()
p = Plateau(ages=ages, errors=errors, signals=signals)
pidx = p.find_plateaus()
self.assertEqual(pidx, idx)
#
def _get_test_data_real_fail(self):
from numpy import array
# ages=array((35.868552979882665, 28.65120030078213, 42.50497290609334, 7.07438966261561, 4.195660871265764,
# 1.0858792249353095, -0.4221166626917233, -0.12004830840675619, 1.8853011443998902, 1.5780258768875648,
# -10.101645211071741))
# errors=array((6.919989216306931, 7.049527127933513, 9.145756003423196, 6.686552442442291, 0.8886617073346395,
# 0.7169908023518705, 0.8929036679198642, 0.8519646228626566, 0.731753931175695, 0.5282504703465821,
# 0.6748271815689348))
# signals=array((0.7810246769509941, 0.8740964805271505, 0.6292251586876362, 0.7018528668884262, 17.38003337391667,
# 27.8410907332066, 20.16578297006377, 21.992348007909765, 27.11825018093817, 54.38147532790856,
# 52.794784404872196))
# idx = []
# ages = array((-4.532789592132701, 3.0251903778384652, 12.984282904655316, 7.415675559405696, 9.915514634333844,
# 5.073849627600819, 11.366067628509356, 9.84552044626644, 8.666915528926422, 5.651212206628916))
# errors = array(
# (9.675981872958216, 2.040698750519321, 1.2507687776259215, 1.6834363119706215, 1.6428286793048248,
# 2.34821762863906, 2.261712182530417, 1.3828420070106184, 0.8055989308667363, 12.159308987062149))
# signals = (
# (0.008781579340722387, 0.022572166331206355, 0.02555511093162022, 0.01598356585916768, 0.017556082863965577,
# 0.018822676982304394, 0.017648844197362533, 0.013847882976741893, 0.07265460797899809, 0.00247174971560797))
# idx = (3, 9)
ages = array((
0.0, -1.7876025629846548, 6.032764579857944, 2.7397332580523464, 4.460694361094021, 10.315258068397155,
1.9608161615417614, 4.243254226544221, 2.351015213399544, 20.30464547047681, 35.661743844775906,
2.6230194593952936))
errors = array((
0.0, 2.512262658455881, 1.1274599800062448, 1.4118647248494784, 1.6742580841211745, 1.2757804416214515,
1.0106219474747273, 1.0445217309056742, 1.7340042145883465, 1.5479507323926824, 3.1237570168227484,
4.443268510171474))
k39 = array((
4.589247099994707e-06, 0.03635680262539634, 0.0470548608081756, 0.03438849848233932, 0.03450855667611368,
0.049794029194755805, 0.03710497981315457, 0.019496051872155938, 0.02132742877176139, 0.11441612176437539,
0.020311606200646422, 0.004718409859914923))
idx = []
return ages, errors, k39, idx
def test_find_plateaus_pass1(self):
ages, errors, signals, idx = self._get_test_data_pass1()
p = Plateau(ages=ages, errors=errors, signals=signals)
pidx = p.find_plateaus()
self.assertEqual(pidx, idx)
def _get_test_data_pass1(self):
# ages = [1, 1, 1, 1, 1, 6, 7]
ages = [1, 1, 1, 1, 1, 1, 1]
errors = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
signals = [1, 1, 1, 1, 1, 1, 1]
idx = (0, 6)
return ages, errors, signals, idx
#
def test_find_plateaus_pass2(self):
ages, errors, signals, idx = self._get_test_data_pass2()
p = Plateau(ages=ages, errors=errors, signals=signals)
pidx = p.find_plateaus()
self.assertEqual(pidx, idx)
def _get_test_data_pass2(self):
ages = [7, 1, 1, 1, 1, 6, 7]
errors = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
signals = [1, 1, 1, 1, 1, 1, 1]
idx = (1, 4)
return ages, errors, signals, idx
def test_find_plateaus_fail1(self):
ages, errors, signals, idx = self._get_test_data_fail1()
p = Plateau(ages=ages, errors=errors, signals=signals)
pidx = p.find_plateaus()
self.assertEqual(pidx, idx)
def _get_test_data_fail1(self):
ages = [7, 1, 1, 1, 1, 6, 7]
errors = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
signals = [1, 1, 1, 1, 1, 1, 100]
idx = []
return ages, errors, signals, idx
def test_find_plateaus_exclude_pass(self):
ages, errors, signals, exclude, idx = self._get_test_data_exclude_pass()
p = Plateau(ages=ages, errors=errors,
exclude=exclude,
signals=signals)
pidx = p.find_plateaus()
self.assertEqual(pidx, idx)
def _get_test_data_exclude_pass(self):
ages = [7, 1, 1, 1, 1, 6, 7]
errors = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
signals = [1, 1, 1, 1, 1, 1, 1]
exclude = [6]
idx = (1, 4)
return ages, errors, signals, exclude, idx
if __name__ == '__main__':
unittest.main()
|
tharinduperera/student_management_Layered | src/lk/ijse/student_management/util/CourseTM.java | package lk.ijse.student_management.util;
import java.math.BigDecimal;
public class CourseTM {
private String cid;
private String cname;
private String ctype;
private String duration;
private BigDecimal cfee;
private BigDecimal discount;
private BigDecimal tax;
private BigDecimal dscfull;
private BigDecimal dsctwice;
public CourseTM() {
}
public CourseTM(String cid, String cname, String ctype, String duration, BigDecimal cfee, BigDecimal discount, BigDecimal tax, BigDecimal dscfull, BigDecimal dsctwice) {
this.cid = cid;
this.cname = cname;
this.ctype = ctype;
this.duration = duration;
this.cfee = cfee;
this.discount = discount;
this.tax = tax;
this.dscfull = dscfull;
this.dsctwice = dsctwice;
}
public CourseTM(String cid, String cname, String ctype, String duration, BigDecimal cfee, BigDecimal dscfull, BigDecimal dsctwice) {
this.cid = cid;
this.cname = cname;
this.ctype = ctype;
this.duration = duration;
this.cfee = cfee;
this.dscfull = dscfull;
this.dsctwice = dsctwice;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCtype() {
return ctype;
}
public void setCtype(String ctype) {
this.ctype = ctype;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public BigDecimal getCfee() {
return cfee;
}
public void setCfee(BigDecimal cfee) {
this.cfee = cfee;
}
public BigDecimal getDiscount() {
return discount;
}
public void setDiscount(BigDecimal discount) {
this.discount = discount;
}
public BigDecimal getTax() {
return tax;
}
public void setTax(BigDecimal tax) {
this.tax = tax;
}
public BigDecimal getDscfull() {
return dscfull;
}
public void setDscfull(BigDecimal dscfull) {
this.dscfull = dscfull;
}
public BigDecimal getDsctwice() {
return dsctwice;
}
public void setDsctwice(BigDecimal dsctwice) {
this.dsctwice = dsctwice;
}
@Override
public String toString() {
return "CourseTM{" +
"cid='" + cid + '\'' +
", cname='" + cname + '\'' +
", ctype='" + ctype + '\'' +
", duration='" + duration + '\'' +
", cfee=" + cfee +
", discount=" + discount +
", tax=" + tax +
", dscfull=" + dscfull +
", dsctwice=" + dsctwice +
'}';
}
}
|
MikaSoftware/academicstoday-paas-django | academicstoday/shared_foundation/models/user.py | from __future__ import unicode_literals
from datetime import date, datetime, timedelta
from phonenumber_field.modelfields import PhoneNumberField
from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.gis.db.models import PointField
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from starterkit.utils import (
get_random_string,
generate_hash
)
from shared_foundation import constants
def get_expiry_date(days=2):
"""Returns the current date plus paramter number of days."""
return timezone.now() + timedelta(days=days)
class SharedUserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, password, **extra_fields)
class SharedUser(AbstractBaseUser, PermissionsMixin):
#
# PERSON FIELDS - http://schema.org/Person
#
first_name = models.CharField(
_("First Name"),
max_length=63,
help_text=_('The users given name.'),
blank=True,
null=True,
db_index=True,
)
middle_name = models.CharField(
_("Middle Name"),
max_length=63,
help_text=_('The users middle name.'),
blank=True,
null=True,
db_index=True,
)
last_name = models.CharField(
_("Last Name"),
max_length=63,
help_text=_('The users last name.'),
blank=True,
null=True,
db_index=True,
)
avatar = models.ImageField(upload_to='avatars/', null=True, blank=True)
birthdate = models.DateField(
_('Birthdate'),
help_text=_('The users birthdate.'),
blank=True,
null=True
)
join_date = models.DateTimeField(
_("Join Date"),
help_text=_('The date the customer joined this organization.'),
null=True,
blank=True,
)
nationality = models.CharField(
_("Nationality"),
max_length=63,
help_text=_('Nationality of the person.'),
blank=True,
null=True,
)
gender = models.CharField(
_("Gender"),
max_length=63,
help_text=_('Gender of the person. While Male and Female may be used, text strings are also acceptable for people who do not identify as a binary gender.'),
blank=True,
null=True,
)
date_joined = models.DateTimeField(_('Date Joined'), auto_now_add=True)
#
# SYSTEM FIELD
#
is_active = models.BooleanField(_('active'), default=True)
was_email_activated = models.BooleanField(
_("Was Email Activated"),
help_text=_('Was the email address verified as an existing address?'),
default=False,
blank=True
)
last_modified = models.DateTimeField(auto_now=True, db_index=True,)
salt = models.CharField( #DEVELOPERS NOTE: Used for cryptographic signatures.
_("Salt"),
max_length=127,
help_text=_('The unique salt value me with this object.'),
default=generate_hash,
unique=True,
blank=True,
null=True
)
type_of = models.PositiveSmallIntegerField(
_("Type of"),
help_text=_('The type of user this is. Value represents ID of user type.'),
default=0,
blank=True,
db_index=True,
)
is_ok_to_email = models.BooleanField(
_("Is OK to email"),
help_text=_('Indicates whether customer allows being reached by email'),
default=True,
blank=True
)
is_ok_to_text = models.BooleanField(
_("Is OK to text"),
help_text=_('Indicates whether customer allows being reached by text.'),
default=True,
blank=True
)
created_at = models.DateTimeField(auto_now_add=True)
last_modified_at = models.DateTimeField(auto_now=True)
#
# PASSWORD RESET FIELDS
#
pr_access_code = models.CharField(
_("Password Reset Access Code"),
max_length=127,
help_text=_('The access code to enter the password reset page to be granted access to restart your password.'),
blank=True,
default=generate_hash,
)
pr_expiry_date = models.DateTimeField(
_('Password Reset Access Code Expiry Date'),
help_text=_('The date where the access code expires and no longer works.'),
blank=True,
default=get_expiry_date,
)
#
# CONTACT POINT FIELDS - http://schema.org/ContactPoint
#
area_served = models.CharField(
_("Area Served"),
max_length=127,
help_text=_('The geographic area where a service or offered item is provided.'),
blank=True,
null=True,
)
available_language = models.CharField(
_("Available Language"),
max_length=127,
help_text=_('A language someone may use with or at the item, service or place. Please use one of the language codes from the <a href="https://tools.ietf.org/html/bcp47">IETF BCP 47 standard</a>.'),
null=True,
blank=True,
)
contact_type = models.CharField(
_("Contact Type"),
max_length=127,
help_text=_('A person or organization can have different contact points, for different purposes. For example, a sales contact point, a PR contact point and so on. This property is used to specify the kind of contact point.'),
blank=True,
null=True,
)
email = models.EmailField( # THIS FIELD IS REQUIRED.
_("Email"),
help_text=_('Email address.'),
db_index=True
)
fax_number = PhoneNumberField(
_("Fax Number"),
help_text=_('The fax number.'),
blank=True,
null=True
)
telephone = PhoneNumberField(
_("Telephone"),
help_text=_('The telephone number.'),
blank=True,
null=True,
db_index=True
)
telephone_extension = models.CharField(
_("Telephone Extension"),
max_length=31,
help_text=_('The telephone number.'),
blank=True,
null=True,
)
mobile = PhoneNumberField( # Not standard in Schema.org
_("Mobile"),
help_text=_('The mobile telephone number.'),
blank=True,
null=True,
db_index=True,
)
#
# GEO-COORDINATE FIELDS - http://schema.org/GeoCoordinates
#
elevation = models.FloatField(
_("Elevation"),
help_text=_('The elevation of a location (<a href="https://en.wikipedia.org/wiki/World_Geodetic_System">WGS 84</a>).'),
blank=True,
null=True
)
latitude = models.DecimalField(
_("Latitude"),
max_digits=8,
decimal_places=3,
help_text=_('The latitude of a location. For example 37.42242 (<a href="https://en.wikipedia.org/wiki/World_Geodetic_System">WGS 84</a>).'),
blank=True,
null=True
)
longitude = models.DecimalField(
_("Longitude"),
max_digits=8,
decimal_places=3,
help_text=_('The longitude of a location. For example -122.08585 (<a href="https://en.wikipedia.org/wiki/World_Geodetic_System">WGS 84</a>).'),
blank=True,
null=True
)
location = PointField(
_("Location"),
help_text=_('A longitude and latitude coordinates of this location.'),
null=True,
blank=True,
srid=4326,
db_index=True
)
#
# POSTAL ADDRESS - http://schema.org/PostalAddress
#
address_country = models.CharField(
_("Address Country"),
max_length=127,
help_text=_('The country. For example, USA. You can also provide the two-letter <a href="https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements">ISO 3166-1 alpha-2</a> country code.'),
blank=True,
null=True,
)
address_locality = models.CharField(
_("Address Locaility"),
max_length=127,
help_text=_('The locality. For example, Mountain View.'),
blank=True,
null=True,
)
address_region = models.CharField(
_("Address Region"),
max_length=127,
help_text=_('The region. For example, CA.'),
blank=True,
null=True,
)
post_office_box_number = models.CharField(
_("Post Office Box Number"),
max_length=255,
help_text=_('Apartment, suite, unit, building, floor, etc.'),
blank=True,
null=True,
)
postal_code = models.CharField(
_("Postal Code"),
max_length=127,
help_text=_('The postal code. For example, 94043.'),
db_index=True,
blank=True,
null=True,
)
street_address = models.CharField(
_("Street Address"),
max_length=255,
help_text=_('The street address. For example, 1600 Amphitheatre Pkwy.'),
blank=True,
null=True,
)
street_address_extra = models.CharField(
_("Street Address (Extra Line)"),
max_length=255,
help_text=_('Apartment, suite, unit, building, floor, etc.'),
blank=True,
null=True,
)
#
# SYSTEM UNIQUE IDENTIFIER
#
identifier = models.CharField(
_('Identifier'),
help_text=_('The unique identifier which has email plus a tenant_id number appended to it. If no tenant_id is append then this user has not been assigned anywhere.'),
max_length=255,
db_index=True,
unique=True
)
academy = models.ForeignKey(
"SharedAcademy",
help_text=_('The academy this user belongs to.'),
blank=True,
null=True,
related_name="%(app_label)s_%(class)s_academy_related",
on_delete=models.CASCADE
)
# DEVELOPERS NOTE:
# WE WILL BE USING "EMAIL" AND "ACADEMY" AS THE UNIQUE PAIR THAT WILL
# DETERMINE WHETHER THE AN ACCOUNT EXISTS. WE ARE DOING THIS TO SUPPORT
# TENANT SPECIFIC USER ACCOUNTS WHICH DO NOT EXIST ON OTHER TENANTS.
# WE USE CUSTOM "AUTHENTICATION BACKEND" TO SUPPORT THE LOGGING IN.
USERNAME_FIELD = 'identifier'
REQUIRED_FIELDS = []
objects = SharedUserManager()
class Meta:
app_label = 'shared_foundation'
db_table = 'at_users'
verbose_name = _('User')
verbose_name_plural = _('Users')
unique_together = ('email', 'academy',)
def get_full_name(self):
'''
Returns the first_name plus the last_name, with a space in between.
'''
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
'''
Returns the short name for the user.
'''
return self.first_name
def email_user(self, subject, message, from_email=None, **kwargs):
'''
Sends an email to this SharedUser.
'''
send_mail(subject, message, from_email, [self.email], **kwargs)
def generate_pr_code(self):
"""
Function generates a new password reset code and expiry date.
"""
self.pr_access_code = get_random_string(length=127)
self.pr_expiry_date = get_expiry_date()
self.save()
return self.pr_access_code
def has_pr_code_expired(self):
"""
Returns true or false depending on whether the password reset code
has expired or not.
"""
today = timezone.now()
return today >= self.pr_expiry_date
|
CarysT/medusa | Gui3d/EditPassword.cpp | <filename>Gui3d/EditPassword.cpp
/*
EditPassword.cpp
(c)2005 Palestar, <NAME>
*/
#define GUI3D_DLL
#include "Debug/Assert.h"
#include "Draw/Draw.h"
#include "System/Messages.h"
#include "Gui3d/EditPassword.h"
#include <ctype.h>
//-------------------------------------------------------------------------------
IMPLEMENT_FACTORY( EditPassword, WindowEdit );
REGISTER_FACTORY_KEY( EditPassword, 4097044393062231240 );
EditPassword::EditPassword()
{}
//----------------------------------------------------------------------------
void EditPassword::onRender( RenderContext & context, const RectInt & window )
{
// save the text
CharString password( m_Text );
// replace the text with '*'
m_Text.allocate( '*', m_Text.length() );
// render with the base class
WindowEdit::onRender( context, window );
// restore the text
m_Text = password;
}
//-------------------------------------------------------------------------------
// EOF
|
giacomo-ascari/digital-pedal | code/lib/pedalboard.h | <reponame>giacomo-ascari/digital-pedal<gh_stars>1-10
#ifndef _PEDALBOARD_H
#define _PEDALBOARD_H
#include <stdlib.h>
#define MAX_PEDALS_COUNT 8
#define INT_PARAM_TYPES 3
#define FLOAT_PARAM_TYPES 9
// ENUMERATION
enum pedal_types {
AMPLIFIER, // amp
BITCRUSHER_RS, // brs
BYPASS, // bps
DYN_AMPLIFIER, // damp
FUZZ, // fzz
LPF, // lpf
OVERDRIVE, // ovr
OVERDRIVE_SQRT, // ovrs
TREMOLO, // trm
};
enum int_param_type {
WIDTH, // width
COUNTER, // multipurpose counter
REDUCT_INTENSITY, // reduction intensity
};
enum float_param_type {
INTENSITY, // gain intensity
THRESHOLD_HIGH, // high (e.g. clip) threshold
THRESHOLD_LOW, // low (e.g. soft) threshold
SOFTENER, // softener
BALANCE_1, // gain on primary channel
BALANCE_2, // gain on secondary channel
HEIGHT, // height
SPEED, // speed
PAST, // past
};
// PARAMETERS structs _ DO NOT TOUCH
typedef struct _int_parameter_t {
int32_t value, min, max, step;
} int_parameter_t;
typedef struct _float_parameter_t {
float value, min, max, step;
} float_parameter_t;
// PEDALS structs
typedef struct _pedal_config_t {
int_parameter_t int_params[INT_PARAM_TYPES];
float_parameter_t float_params[FLOAT_PARAM_TYPES];
} pedal_config_t;
typedef struct _pedal_t {
pedal_config_t config;
enum pedal_types type;
float (*pedal_process)(float in, pedal_config_t *p_config);
} pedal_t;
enum pedal_types pedal_type_parse(char *type_str);
// PEDALBOARD
typedef struct _pedalboard_t {
u_int8_t active_pedals;
pedal_t pedals[MAX_PEDALS_COUNT];
} pedalboard_t;
void pedalboard_append(pedalboard_t *p_pb, enum pedal_types type);
int16_t pedalboard_process(pedalboard_t *p_pb, int16_t in);
#endif |
zenoss-ce/serviced | facade/lock.go | <reponame>zenoss-ce/serviced
// Copyright 2015 The Serviced 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 facade
import (
"errors"
"sync"
"time"
"github.com/control-center/serviced/datastore"
"github.com/control-center/serviced/domain/service"
"github.com/zenoss/glog"
)
// TenantLocker keeps track of locks per tenant
type TenantLocker struct {
sync.Locker
tenants map[string]*sync.RWMutex
}
// tlock is the global list of tenant locks
var tlock = &TenantLocker{Locker: &sync.Mutex{}, tenants: make(map[string]*sync.RWMutex)}
// getTenantLock returns the locker for a given tenant
func getTenantLock(tenantID string) (mutex *sync.RWMutex) {
tlock.Lock()
mutex, ok := tlock.tenants[tenantID]
if !ok {
tlock.tenants[tenantID] = &sync.RWMutex{}
mutex = tlock.tenants[tenantID]
}
tlock.Unlock()
return
}
// lockTenant sets the write lock for a given tenant and locks all services for
// that tenant
func (f *Facade) lockTenant(ctx datastore.Context, tenantID string) (err error) {
defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.lockTenant"))
mutex := getTenantLock(tenantID)
mutex.Lock()
defer func() {
if err != nil {
mutex.Unlock()
}
}()
// Wait for current processing by the service state manager to complete
// The lock above will prevent any new requests to the service state manager
f.ssm.Wait(tenantID)
var svcs []service.ServiceDetails
if svcs, err = f.GetServiceDetailsByTenantID(ctx, tenantID); err != nil {
glog.Errorf("Could not get services for tenant %s: %s", tenantID, err)
return
}
if err = f.zzk.LockServices(ctx, svcs); err != nil {
glog.Errorf("Could not lock services for tenant %s: %s", tenantID, err)
return
}
return
}
// unlockTenant unsets the write lock for a given tenant and unlocks all
// services for that tenant
func (f *Facade) unlockTenant(ctx datastore.Context, tenantID string) (err error) {
defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.unlockTenant"))
mutex := getTenantLock(tenantID)
var svcs []service.ServiceDetails
if svcs, err = f.GetServiceDetailsByTenantID(ctx, tenantID); err != nil {
glog.Errorf("Could not get services for tenant %s: %s", tenantID, err)
return
}
if err = f.zzk.UnlockServices(ctx, svcs); err != nil {
glog.Errorf("Could not unlock services for tenant %s: %s", tenantID, err)
return
}
mutex.Unlock()
return
}
// retryUnlockTenant is a persistent unlock for a given tenant
func (f *Facade) retryUnlockTenant(ctx datastore.Context, tenantID string, cancel <-chan time.Time, interval time.Duration) error {
for {
if err := f.unlockTenant(ctx, tenantID); err == nil {
return nil
}
glog.Warningf("Could not unlock, retrying in %s", interval)
select {
case <-time.After(interval):
case <-cancel:
return errors.New("operation cancelled")
}
}
}
|
Jiss-Jose/scmi-tests | platform/mocker/mocker/include/protocol_common.h | /** @file
* Copyright (c) 2019, Arm Limited or its affiliates. All rights reserved.
* SPDX-License-Identifier : Apache-2.0
*
* 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.
**/
#ifndef __PROTOCOL_COMMON_H__
#define __PROTOCOL_COMMON_H__
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <inttypes.h>
#include <stddef.h>
#include <stdarg.h>
#include <string.h>
#include <inttypes.h>
#include <base_protocol.h>
#include <assert.h>
#define SCMI_NAME_STR_SIZE 16
#define NUM_ELEMS(x) (sizeof(x) / sizeof((x)[0]))
/*
* These macros are used to compute the offset values of return and parameters
* fields.
*/
#define OFFSET_BYTES_RET(st, elem) \
((offsetof(st, returns.elem) - offsetof(st, returns)))
#define OFFSET_RET(st, elem) \
(OFFSET_BYTES_RET(st, elem)/sizeof(uint32_t))
#define OFFSET_PARAM(st, elem) \
(((offsetof(st, parameters.elem) - offsetof(st, parameters)))/sizeof(uint32_t))
enum SCMI_STATUS_CODES {
SCMI_STATUS_SUCCESS = 0,
SCMI_STATUS_NOT_SUPPORTED = -1,
SCMI_STATUS_INVALID_PARAMETERS = -2,
SCMI_STATUS_DENIED = -3,
SCMI_STATUS_NOT_FOUND = -4,
SCMI_STATUS_OUT_OF_RANGE = -5,
SCMI_STATUS_BUSY = -6,
SCMI_STATUS_COMMS_ERROR = -7,
SCMI_STATUS_GENERIC_ERROR = -8,
SCMI_STATUS_HARDWARE_ERROR = -9,
SCMI_STATUS_PROTOCOL_ERROR = -10,
SCMI_RESERVED = -11,
SCMI_STATUS_NOT_SPECIFIED = -100
};
#endif
|
wk0122/CoreJava | src/tech/aistar/util/LocalTimeDemo.java | <gh_stars>0
package tech.aistar.util;
import java.time.LocalTime;
/**
* @author success
* @version 1.0
* @description:本类用来演示:
* @date 2019/3/28 0028
*/
public class LocalTimeDemo {
public static void main(String[] args) {
LocalTime localTime = LocalTime.now();
System.out.println(localTime);//18:20:21.378
//清除毫秒
System.out.println(localTime.withNano(0));//18:20:56
//构造时间
LocalTime myLocalTime = LocalTime.of(21,9,12);
System.out.println(myLocalTime);
//解析字符串
LocalTime strTime = LocalTime.parse("21:08:12");
System.out.println(strTime);
}
}
|
expensivecow/jadx | jadx-cli/app-release/sources/android/support/v4/widget/CircularProgressDrawable.java | package android.support.v4.widget;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.Cap;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.Path.FillType;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.RestrictTo;
import android.support.annotation.RestrictTo.Scope;
import android.support.v4.util.Preconditions;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public class CircularProgressDrawable extends Drawable implements Animatable {
private static final int ANIMATION_DURATION = 1332;
private static final int ARROW_HEIGHT = 5;
private static final int ARROW_HEIGHT_LARGE = 6;
private static final int ARROW_WIDTH = 10;
private static final int ARROW_WIDTH_LARGE = 12;
private static final float CENTER_RADIUS = 7.5f;
private static final float CENTER_RADIUS_LARGE = 11.0f;
private static final int[] COLORS = new int[]{-16777216};
private static final float COLOR_CHANGE_OFFSET = 0.75f;
public static final int DEFAULT = 1;
private static final float GROUP_FULL_ROTATION = 216.0f;
public static final int LARGE = 0;
private static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator();
private static final Interpolator MATERIAL_INTERPOLATOR = new FastOutSlowInInterpolator();
private static final float MAX_PROGRESS_ARC = 0.8f;
private static final float MIN_PROGRESS_ARC = 0.01f;
private static final float RING_ROTATION = 0.20999998f;
private static final float SHRINK_OFFSET = 0.5f;
private static final float STROKE_WIDTH = 2.5f;
private static final float STROKE_WIDTH_LARGE = 3.0f;
private Animator mAnimator;
private boolean mFinishing;
private Resources mResources;
private final Ring mRing = new Ring();
private float mRotation;
private float mRotationCount;
@RestrictTo({Scope.LIBRARY_GROUP})
@Retention(RetentionPolicy.SOURCE)
public @interface ProgressDrawableSize {
}
private static class Ring {
int mAlpha;
Path mArrow;
int mArrowHeight;
final Paint mArrowPaint = new Paint();
float mArrowScale;
int mArrowWidth;
final Paint mCirclePaint = new Paint();
int mColorIndex;
int[] mColors;
int mCurrentColor;
float mEndTrim;
final Paint mPaint = new Paint();
float mRingCenterRadius;
float mRotation;
boolean mShowArrow;
float mStartTrim;
float mStartingEndTrim;
float mStartingRotation;
float mStartingStartTrim;
float mStrokeWidth;
final RectF mTempBounds = new RectF();
Ring() {
float f = 0.0f;
this.mStartTrim = f;
this.mEndTrim = f;
this.mRotation = f;
this.mStrokeWidth = 5.0f;
this.mArrowScale = 1.0f;
this.mAlpha = 255;
this.mPaint.setStrokeCap(Cap.SQUARE);
boolean z = true;
this.mPaint.setAntiAlias(z);
this.mPaint.setStyle(Style.STROKE);
this.mArrowPaint.setStyle(Style.FILL);
this.mArrowPaint.setAntiAlias(z);
this.mCirclePaint.setColor(0);
}
void setArrowDimensions(float f, float f2) {
this.mArrowWidth = (int) f;
this.mArrowHeight = (int) f2;
}
void setStrokeCap(Cap cap) {
this.mPaint.setStrokeCap(cap);
}
Cap getStrokeCap() {
return this.mPaint.getStrokeCap();
}
float getArrowWidth() {
return (float) this.mArrowWidth;
}
float getArrowHeight() {
return (float) this.mArrowHeight;
}
void draw(Canvas canvas, Rect rect) {
RectF rectF = this.mTempBounds;
float f = 2.0f;
float f2 = this.mRingCenterRadius + (this.mStrokeWidth / f);
if (this.mRingCenterRadius <= 0.0f) {
f2 = (((float) Math.min(rect.width(), rect.height())) / f) - Math.max((((float) this.mArrowWidth) * this.mArrowScale) / f, this.mStrokeWidth / f);
}
rectF.set(((float) rect.centerX()) - f2, ((float) rect.centerY()) - f2, ((float) rect.centerX()) + f2, ((float) rect.centerY()) + f2);
f2 = 360.0f;
float f3 = (this.mStartTrim + this.mRotation) * f2;
float f4 = ((this.mEndTrim + this.mRotation) * f2) - f3;
this.mPaint.setColor(this.mCurrentColor);
this.mPaint.setAlpha(this.mAlpha);
f2 = this.mStrokeWidth / f;
rectF.inset(f2, f2);
canvas.drawCircle(rectF.centerX(), rectF.centerY(), rectF.width() / f, this.mCirclePaint);
f2 = -f2;
rectF.inset(f2, f2);
canvas.drawArc(rectF, f3, f4, false, this.mPaint);
drawTriangle(canvas, f3, f4, rectF);
}
void drawTriangle(Canvas canvas, float f, float f2, RectF rectF) {
if (this.mShowArrow) {
if (this.mArrow == null) {
this.mArrow = new Path();
this.mArrow.setFillType(FillType.EVEN_ODD);
} else {
this.mArrow.reset();
}
float f3 = 2.0f;
float min = Math.min(rectF.width(), rectF.height()) / f3;
float f4 = (((float) this.mArrowWidth) * this.mArrowScale) / f3;
float f5 = 0.0f;
this.mArrow.moveTo(f5, f5);
this.mArrow.lineTo(((float) this.mArrowWidth) * this.mArrowScale, f5);
this.mArrow.lineTo((((float) this.mArrowWidth) * this.mArrowScale) / f3, ((float) this.mArrowHeight) * this.mArrowScale);
this.mArrow.offset((min + rectF.centerX()) - f4, rectF.centerY() + (this.mStrokeWidth / f3));
this.mArrow.close();
this.mArrowPaint.setColor(this.mCurrentColor);
this.mArrowPaint.setAlpha(this.mAlpha);
canvas.save();
canvas.rotate(f + f2, rectF.centerX(), rectF.centerY());
canvas.drawPath(this.mArrow, this.mArrowPaint);
canvas.restore();
}
}
void setColors(@NonNull int[] iArr) {
this.mColors = iArr;
setColorIndex(0);
}
int[] getColors() {
return this.mColors;
}
void setColor(int i) {
this.mCurrentColor = i;
}
void setBackgroundColor(int i) {
this.mCirclePaint.setColor(i);
}
int getBackgroundColor() {
return this.mCirclePaint.getColor();
}
void setColorIndex(int i) {
this.mColorIndex = i;
this.mCurrentColor = this.mColors[this.mColorIndex];
}
int getNextColor() {
return this.mColors[getNextColorIndex()];
}
int getNextColorIndex() {
return (this.mColorIndex + 1) % this.mColors.length;
}
void goToNextColor() {
setColorIndex(getNextColorIndex());
}
void setColorFilter(ColorFilter colorFilter) {
this.mPaint.setColorFilter(colorFilter);
}
void setAlpha(int i) {
this.mAlpha = i;
}
int getAlpha() {
return this.mAlpha;
}
void setStrokeWidth(float f) {
this.mStrokeWidth = f;
this.mPaint.setStrokeWidth(f);
}
float getStrokeWidth() {
return this.mStrokeWidth;
}
void setStartTrim(float f) {
this.mStartTrim = f;
}
float getStartTrim() {
return this.mStartTrim;
}
float getStartingStartTrim() {
return this.mStartingStartTrim;
}
float getStartingEndTrim() {
return this.mStartingEndTrim;
}
int getStartingColor() {
return this.mColors[this.mColorIndex];
}
void setEndTrim(float f) {
this.mEndTrim = f;
}
float getEndTrim() {
return this.mEndTrim;
}
void setRotation(float f) {
this.mRotation = f;
}
float getRotation() {
return this.mRotation;
}
void setCenterRadius(float f) {
this.mRingCenterRadius = f;
}
float getCenterRadius() {
return this.mRingCenterRadius;
}
void setShowArrow(boolean z) {
if (this.mShowArrow != z) {
this.mShowArrow = z;
}
}
boolean getShowArrow() {
return this.mShowArrow;
}
void setArrowScale(float f) {
if (f != this.mArrowScale) {
this.mArrowScale = f;
}
}
float getArrowScale() {
return this.mArrowScale;
}
float getStartingRotation() {
return this.mStartingRotation;
}
void storeOriginals() {
this.mStartingStartTrim = this.mStartTrim;
this.mStartingEndTrim = this.mEndTrim;
this.mStartingRotation = this.mRotation;
}
void resetOriginals() {
float f = 0.0f;
this.mStartingStartTrim = f;
this.mStartingEndTrim = f;
this.mStartingRotation = f;
setStartTrim(f);
setEndTrim(f);
setRotation(f);
}
}
private int evaluateColorChange(float f, int i, int i2) {
int i3 = (i >> 24) & 255;
int i4 = (i >> 16) & 255;
int i5 = (i >> 8) & 255;
i &= 255;
return ((((i3 + ((int) (((float) (((i2 >> 24) & 255) - i3)) * f))) << 24) | ((i4 + ((int) (((float) (((i2 >> 16) & 255) - i4)) * f))) << 16)) | ((i5 + ((int) (((float) (((i2 >> 8) & 255) - i5)) * f))) << 8)) | (i + ((int) (f * ((float) ((i2 & 255) - i)))));
}
public int getOpacity() {
return -3;
}
public CircularProgressDrawable(Context context) {
this.mResources = ((Context) Preconditions.checkNotNull(context)).getResources();
this.mRing.setColors(COLORS);
setStrokeWidth(2.5f);
setupAnimators();
}
private void setSizeParameters(float f, float f2, float f3, float f4) {
Ring ring = this.mRing;
float f5 = this.mResources.getDisplayMetrics().density;
ring.setStrokeWidth(f2 * f5);
ring.setCenterRadius(f * f5);
ring.setColorIndex(0);
ring.setArrowDimensions(f3 * f5, f4 * f5);
}
public void setStyle(int i) {
if (i == 0) {
setSizeParameters(11.0f, 3.0f, 12.0f, 6.0f);
} else {
setSizeParameters(7.5f, 2.5f, 10.0f, 5.0f);
}
invalidateSelf();
}
public float getStrokeWidth() {
return this.mRing.getStrokeWidth();
}
public void setStrokeWidth(float f) {
this.mRing.setStrokeWidth(f);
invalidateSelf();
}
public float getCenterRadius() {
return this.mRing.getCenterRadius();
}
public void setCenterRadius(float f) {
this.mRing.setCenterRadius(f);
invalidateSelf();
}
public void setStrokeCap(Cap cap) {
this.mRing.setStrokeCap(cap);
invalidateSelf();
}
public Cap getStrokeCap() {
return this.mRing.getStrokeCap();
}
public float getArrowWidth() {
return this.mRing.getArrowWidth();
}
public float getArrowHeight() {
return this.mRing.getArrowHeight();
}
public void setArrowDimensions(float f, float f2) {
this.mRing.setArrowDimensions(f, f2);
invalidateSelf();
}
public boolean getArrowEnabled() {
return this.mRing.getShowArrow();
}
public void setArrowEnabled(boolean z) {
this.mRing.setShowArrow(z);
invalidateSelf();
}
public float getArrowScale() {
return this.mRing.getArrowScale();
}
public void setArrowScale(float f) {
this.mRing.setArrowScale(f);
invalidateSelf();
}
public float getStartTrim() {
return this.mRing.getStartTrim();
}
public float getEndTrim() {
return this.mRing.getEndTrim();
}
public void setStartEndTrim(float f, float f2) {
this.mRing.setStartTrim(f);
this.mRing.setEndTrim(f2);
invalidateSelf();
}
public float getProgressRotation() {
return this.mRing.getRotation();
}
public void setProgressRotation(float f) {
this.mRing.setRotation(f);
invalidateSelf();
}
public int getBackgroundColor() {
return this.mRing.getBackgroundColor();
}
public void setBackgroundColor(int i) {
this.mRing.setBackgroundColor(i);
invalidateSelf();
}
public int[] getColorSchemeColors() {
return this.mRing.getColors();
}
public void setColorSchemeColors(int... iArr) {
this.mRing.setColors(iArr);
this.mRing.setColorIndex(0);
invalidateSelf();
}
public void draw(Canvas canvas) {
Rect bounds = getBounds();
canvas.save();
canvas.rotate(this.mRotation, bounds.exactCenterX(), bounds.exactCenterY());
this.mRing.draw(canvas, bounds);
canvas.restore();
}
public void setAlpha(int i) {
this.mRing.setAlpha(i);
invalidateSelf();
}
public int getAlpha() {
return this.mRing.getAlpha();
}
public void setColorFilter(ColorFilter colorFilter) {
this.mRing.setColorFilter(colorFilter);
invalidateSelf();
}
private void setRotation(float f) {
this.mRotation = f;
}
private float getRotation() {
return this.mRotation;
}
public boolean isRunning() {
return this.mAnimator.isRunning();
}
public void start() {
this.mAnimator.cancel();
this.mRing.storeOriginals();
if (this.mRing.getEndTrim() != this.mRing.getStartTrim()) {
this.mFinishing = true;
this.mAnimator.setDuration(666);
this.mAnimator.start();
return;
}
this.mRing.setColorIndex(0);
this.mRing.resetOriginals();
this.mAnimator.setDuration(1332);
this.mAnimator.start();
}
public void stop() {
this.mAnimator.cancel();
setRotation(0.0f);
boolean z = false;
this.mRing.setShowArrow(z);
this.mRing.setColorIndex(z);
this.mRing.resetOriginals();
invalidateSelf();
}
private void updateRingColor(float f, Ring ring) {
float f2 = 0.75f;
if (f > f2) {
ring.setColor(evaluateColorChange((f - f2) / 0.25f, ring.getStartingColor(), ring.getNextColor()));
} else {
ring.setColor(ring.getStartingColor());
}
}
private void applyFinishTranslation(float f, Ring ring) {
updateRingColor(f, ring);
float floor = (float) (Math.floor((double) (ring.getStartingRotation() / 0.8f)) + 1.0d);
ring.setStartTrim(ring.getStartingStartTrim() + (((ring.getStartingEndTrim() - 0.01f) - ring.getStartingStartTrim()) * f));
ring.setEndTrim(ring.getStartingEndTrim());
ring.setRotation(ring.getStartingRotation() + ((floor - ring.getStartingRotation()) * f));
}
private void applyTransformation(float f, Ring ring, boolean z) {
if (this.mFinishing) {
applyFinishTranslation(f, ring);
return;
}
float f2 = 1.0f;
if (f != f2 || z) {
float f3;
float startingRotation = ring.getStartingRotation();
float f4 = 0.5f;
float f5 = 0.01f;
float f6 = 0.79f;
if (f < f4) {
f2 = f / f4;
f4 = ring.getStartingStartTrim();
f2 = f4;
f4 = ((f6 * MATERIAL_INTERPOLATOR.getInterpolation(f2)) + f5) + f4;
} else {
f3 = (f - f4) / f4;
f4 = ring.getStartingStartTrim() + f6;
f2 = f4 - ((f6 * (f2 - MATERIAL_INTERPOLATOR.getInterpolation(f3))) + f5);
}
startingRotation += 0.20999998f * f;
f3 = 216.0f * (f + this.mRotationCount);
ring.setStartTrim(f2);
ring.setEndTrim(f4);
ring.setRotation(startingRotation);
setRotation(f3);
}
}
private void setupAnimators() {
final Ring ring = this.mRing;
int i = 2;
Animator ofFloat = ValueAnimator.ofFloat(new float[]{0.0f, 1.0f});
ofFloat.addUpdateListener(new AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float floatValue = ((Float) valueAnimator.getAnimatedValue()).floatValue();
CircularProgressDrawable.this.updateRingColor(floatValue, ring);
CircularProgressDrawable.this.applyTransformation(floatValue, ring, false);
CircularProgressDrawable.this.invalidateSelf();
}
});
ofFloat.setRepeatCount(-1);
ofFloat.setRepeatMode(1);
ofFloat.setInterpolator(LINEAR_INTERPOLATOR);
ofFloat.addListener(new AnimatorListener() {
public void onAnimationCancel(Animator animator) {
}
public void onAnimationEnd(Animator animator) {
}
public void onAnimationStart(Animator animator) {
CircularProgressDrawable.this.mRotationCount = 0.0f;
}
public void onAnimationRepeat(Animator animator) {
float f = 1.0f;
CircularProgressDrawable.this.applyTransformation(f, ring, true);
ring.storeOriginals();
ring.goToNextColor();
if (CircularProgressDrawable.this.mFinishing) {
boolean z = false;
CircularProgressDrawable.this.mFinishing = z;
animator.cancel();
animator.setDuration(1332);
animator.start();
ring.setShowArrow(z);
return;
}
CircularProgressDrawable.this.mRotationCount = CircularProgressDrawable.this.mRotationCount + f;
}
});
this.mAnimator = ofFloat;
}
}
|
xyt2008/frcnn | examples/FRCNN/loc_merge_frcnn.cpp | #include <gflags/gflags.h>
#include <glog/logging.h>
#include "boost/algorithm/string.hpp"
#include "caffe/util/benchmark.hpp"
#include "caffe/util/signal_handler.h"
#include "api/api.hpp"
DEFINE_string(gpu, "",
"Optional; run in GPU mode on the given device ID, Empty is CPU");
DEFINE_string(model, "",
"The model definition protocol buffer text file.");
DEFINE_string(weights, "",
"Trained Model By Faster RCNN End-to-End Pipeline.");
DEFINE_string(default_c, "",
"Default config file path.");
DEFINE_string(image_list, "",
"Optional;Test images list.");
DEFINE_string(image_root, "",
"Optional;Test images root directory.");
DEFINE_string(out_file, "",
"Optional;Output images file.");
using std::string;
using std::vector;
inline string INT(float x) { char A[100]; sprintf(A,"%.1f",x); return string(A);};
inline string FloatToString(float x) { char A[100]; sprintf(A,"%.4f",x); return string(A);};
float mean_[3];
void Set_Model(boost::shared_ptr<caffe::Net<float> >& net_, std::string &proto_file, std::string &model_file) {
net_.reset(new caffe::Net<float>(proto_file, caffe::TEST));
net_->CopyTrainedLayersFrom(model_file);
::mean_[0] = caffe::Frcnn::FrcnnParam::pixel_means[0];
::mean_[1] = caffe::Frcnn::FrcnnParam::pixel_means[1];
::mean_[2] = caffe::Frcnn::FrcnnParam::pixel_means[2];
DLOG(INFO) << "SET MODEL DONE";
caffe::Frcnn::FrcnnParam::print_param();
}
vector<float> predict(boost::shared_ptr<caffe::Net<float> >& net_, const cv::Mat &img_in, const vector<caffe::Frcnn::BBox<float> > results) {
CHECK(caffe::Frcnn::FrcnnParam::test_scales.size() == 1) << "Only single-image batch implemented";
float scale_factor = caffe::Frcnn::get_scale_factor(img_in.cols, img_in.rows, caffe::Frcnn::FrcnnParam::test_scales[0], caffe::Frcnn::FrcnnParam::test_max_size);
cv::Mat img;
const int height = img_in.rows;
const int width = img_in.cols;
DLOG(INFO) << "height: " << height << " width: " << width;
img_in.convertTo(img, CV_32FC3);
for (int r = 0; r < img.rows; r++) {
for (int c = 0; c < img.cols; c++) {
int offset = (r * img.cols + c) * 3;
reinterpret_cast<float *>(img.data)[offset + 0] -= ::mean_[0]; // B
reinterpret_cast<float *>(img.data)[offset + 1] -= ::mean_[1]; // G
reinterpret_cast<float *>(img.data)[offset + 2] -= ::mean_[2]; // R
}
}
cv::resize(img, img, cv::Size(), scale_factor, scale_factor);
float im_info[3];
im_info[0] = img.rows;
im_info[1] = img.cols;
im_info[2] = scale_factor;
CHECK(img.isContinuous()) << "Warning : cv::Mat img is not Continuous !";
DLOG(ERROR) << "img (CHW) : " << img.channels() << ", " << img.rows << ", " << img.cols;
boost::shared_ptr<caffe::Blob<float> > image_blob = net_->blob_by_name("data");
image_blob->Reshape(1, img.channels(), img.rows, img.cols);
const int cols = img.cols;
const int rows = img.rows;
for (int i = 0; i < cols * rows; i++) {
image_blob->mutable_cpu_data()[cols * rows * 0 + i] =
reinterpret_cast<float*>(img.data)[i * 3 + 0] ;// mean_[0];
image_blob->mutable_cpu_data()[cols * rows * 1 + i] =
reinterpret_cast<float*>(img.data)[i * 3 + 1] ;// mean_[1];
image_blob->mutable_cpu_data()[cols * rows * 2 + i] =
reinterpret_cast<float*>(img.data)[i * 3 + 2] ;// mean_[2];
}
boost::shared_ptr<caffe::Blob<float> > info_blob = net_->blob_by_name("im_info");
info_blob->Reshape(1, 3, 1, 1);
std::memcpy(info_blob->mutable_cpu_data(), im_info, sizeof(float) * 3);
boost::shared_ptr<caffe::Blob<float> > rois_blob = net_->blob_by_name("rois");
rois_blob->Reshape(results.size(), 5, 1, 1);
for (size_t index = 0; index < results.size(); index++) {
rois_blob->mutable_cpu_data()[ index *5 + 0 ] = 0;
rois_blob->mutable_cpu_data()[ index *5 + 1 ] = std::max(0.f, results[index][0] * scale_factor);
rois_blob->mutable_cpu_data()[ index *5 + 2 ] = std::max(0.f, results[index][1] * scale_factor);
rois_blob->mutable_cpu_data()[ index *5 + 3 ] = std::min(im_info[1]-1.f, results[index][2] * scale_factor);
rois_blob->mutable_cpu_data()[ index *5 + 4 ] = std::min(im_info[0]-1.f, results[index][3] * scale_factor);
}
float loss;
net_->Forward(&loss);
boost::shared_ptr<caffe::Blob<float> > cls_prob = net_->blob_by_name("cls_prob");
const int cls_num = cls_prob->channels();
vector<float> answer(results.size());
CHECK_EQ(int(results.size()), cls_prob->num());
for (size_t index = 0; index < results.size(); index++) {
const int cls = results[index].id;
CHECK_GT(cls, 0); CHECK_LT(cls, cls_num);
answer[index] = cls_prob->cpu_data()[index * cls_num + cls];
}
DLOG(INFO) << "FORWARD END, LOSS : " << loss;
return answer;
}
int main(int argc, char** argv){
// Print output to stderr (while still logging).
FLAGS_alsologtostderr = 1;
// Set version
gflags::SetVersionString(AS_STRING(CAFFE_VERSION));
// Usage message.
gflags::SetUsageMessage("command line brew\n"
"usage: demo_frcnn_api <args>\n\n"
"args:\n"
" --gpu 7 use 7-th gpu device, default is cpu model\n"
" --model file protocol buffer text file\n"
" --weights file Trained Model\n"
" --default_c file Default Config File\n"
" --image_list file input image list\n"
" --image_root file input image dir\n"
" --out_file file output amswer file");
// Run tool or show usage.
caffe::GlobalInit(&argc, &argv);
CHECK( FLAGS_gpu.size() == 0 || FLAGS_gpu.size() == 1 || (FLAGS_gpu.size()==2&&FLAGS_gpu=="-1")) << "Can only support one gpu or none or -1(for cpu)";
int gpu_id = -1;
if( FLAGS_gpu.size() > 0 )
gpu_id = boost::lexical_cast<int>(FLAGS_gpu);
if (gpu_id >= 0) {
#ifndef CPU_ONLY
caffe::Caffe::SetDevice(gpu_id);
caffe::Caffe::set_mode(caffe::Caffe::GPU);
#else
LOG(FATAL) << "CPU ONLY MODEL, BUT PROVIDE GPU ID";
#endif
} else {
caffe::Caffe::set_mode(caffe::Caffe::CPU);
}
boost::shared_ptr<caffe::Net<float> > net_;
string proto_file = FLAGS_model.c_str();
string model_file = FLAGS_weights.c_str();
string default_config_file = FLAGS_default_c.c_str();
const string image_list = FLAGS_image_list.c_str();
const string image_root = FLAGS_image_root.c_str();
const string out_file = FLAGS_out_file.c_str();
API::Set_Config(default_config_file);
Set_Model(net_, proto_file, model_file);
LOG(INFO) << "image list : " << image_list;
LOG(INFO) << "output file : " << out_file;
LOG(INFO) << "image_root : " << image_root;
std::ifstream infile(image_list.c_str());
std::ofstream otfile(out_file.c_str());
int count = 0;
string shot_dir;
int frames;
string HASH, image;
int ids_;
while ( infile >> HASH >> ids_ >> shot_dir >> frames ) {
CHECK(HASH == "#");
CHECK(ids_ >= 0);
otfile << "#\t" << ids_ << "\t" << shot_dir << "\t" << frames << std::endl;
CHECK_GE(frames, 0);
for (int ii = 0; ii < frames; ii++) {
int boxes_num = 0;
infile >> HASH >> image >> boxes_num;
otfile << "&\t" << image << "\t" << boxes_num << std::endl;
CHECK(HASH == "&");
CHECK(image.find(".jpeg") != string::npos);
if (boxes_num == 0) {
LOG(INFO) << "Handle " << count << " th shot[" << shot_dir << "] : " << ii << " / " << frames << " frame : " << image << " -> " << boxes_num << " boxes";
continue;
}
cv::Mat cv_image = cv::imread(image_root + "/" + shot_dir + "/" + image);
vector<caffe::Frcnn::BBox<float> > results;
for (int ibs = 0; ibs < boxes_num; ibs++) {
int id;
float x1, y1, x2, y2, conf;
infile >> id >> x1 >> y1 >> x2 >> y2 >> conf;
results.push_back(caffe::Frcnn::BBox<float>(x1, y1, x2, y2, 1, id));
}
vector<float> scores = predict(net_, cv_image, results);
CHECK_EQ(scores.size(), results.size());
for (size_t obj = 0; obj < scores.size(); obj++) {
otfile << FloatToString(scores[obj]) << std::endl;
}
LOG(INFO) << "Handle " << count << " th shot[" << shot_dir << "] : " << ii << " / " << frames << " frame : " << image << " -> " << results.size() << " boxes";
}
count ++;
}
infile.close();
otfile.close();
return 0;
}
|
ssSlowDown/onemall | shop-web-app/src/main/java/cn/iocoder/mall/shopweb/convert/user/PassportConvert.java | package cn.iocoder.mall.shopweb.convert.user;
import cn.iocoder.mall.shopweb.controller.user.vo.passport.PassportAccessTokenRespVO;
import cn.iocoder.mall.shopweb.controller.user.vo.passport.PassportLoginBySmsReqVO;
import cn.iocoder.mall.shopweb.controller.user.vo.passport.PassportSendSmsRespVO;
import cn.iocoder.mall.systemservice.rpc.oauth.dto.OAuth2AccessTokenRespDTO;
import cn.iocoder.mall.userservice.rpc.sms.dto.UserSendSmsCodeReqDTO;
import cn.iocoder.mall.userservice.rpc.sms.dto.UserVerifySmsCodeReqDTO;
import cn.iocoder.mall.userservice.rpc.user.dto.UserCreateReqDTO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@Mapper
public interface PassportConvert {
PassportConvert INSTANCE = Mappers.getMapper(PassportConvert.class);
UserVerifySmsCodeReqDTO convert(PassportLoginBySmsReqVO bean);
UserCreateReqDTO convert02(PassportLoginBySmsReqVO bean);
UserSendSmsCodeReqDTO convert(PassportSendSmsRespVO bean);
PassportAccessTokenRespVO convert(OAuth2AccessTokenRespDTO bean);
}
|
vvvpic/xxtime | app/src/main/java/net/xxtime/adapter/FocusBusAdapter.java | <filename>app/src/main/java/net/xxtime/adapter/FocusBusAdapter.java
package net.xxtime.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.longtu.base.util.StringUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import net.xxtime.R;
import net.xxtime.bean.FocusBusBean;
import net.xxtime.utils.OptionsUtils;
import java.util.List;
/**
* Created by 唯图 on 2016/8/26.
*/
public class FocusBusAdapter extends BaseAdapter {
private List<FocusBusBean.DefaultAListBean> listfocus;
private Context context;
public FocusBusAdapter(List<FocusBusBean.DefaultAListBean> listfocus,Context context){
this.listfocus=listfocus;
this.context=context;
}
@Override
public int getCount() {
return listfocus.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Focus_item focus_item;
if (convertView==null){
convertView= LayoutInflater.from(context).inflate(R.layout.focus_item,null);
focus_item=new Focus_item();
focus_item.ivAvatar=(ImageView)convertView.findViewById(R.id. ivAvatar);
focus_item.tvName=(TextView)convertView.findViewById(R.id.tvName);
convertView.setTag(focus_item);
}else {
focus_item= (Focus_item) convertView.getTag();
}
if (!StringUtils.isEmpty(listfocus.get(position).getBuslogo())){
ImageLoader.getInstance().displayImage(listfocus.get(position).getBuslogo(),focus_item.ivAvatar, OptionsUtils.getSimpleOptions(20));
}
if (!StringUtils.isEmpty(listfocus.get(position).getBusfullname())){
focus_item.tvName.setText(listfocus.get(position).getBusfullname());
}
return convertView;
}
class Focus_item{
ImageView ivAvatar;
TextView tvName;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.